@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
package/sources.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// Generated by site/build.mjs: the app's fetched files as strings, for the claude.ai shell.
|
|
2
|
+
export default {"version":"0.2.1","files":{"index.html":"<title>Kairotic</title>\n<link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100' role='img' aria-label='Kairotic'%3E%3Ctitle%3EKairotic%3C/title%3E%3Cstyle%3Eg{fill:none;stroke:%231b2430;stroke-linecap:round}.f,.t{fill:%231b2430}.t{stroke:none}.d{fill:%23b4472e}@media (prefers-color-scheme:dark){g{stroke:%23e3e8ee}.f,.t{fill:%23e3e8ee}.d{fill:%23e58a6f}}%3C/style%3E%3Cg%3E%3Cpath d='M24 10 C6 30 6 70 24 90' stroke-width='12'/%3E\n%3Cpath d='M76 10 C94 30 94 70 76 90' stroke-width='12'/%3E\n%3Cpath d='M40 22 V78' stroke-width='12'/%3E\n%3Cpath d='M40 56 C52 56 56 34 64 28 M40 56 C52 56 57 68 65 74' stroke-width='10'/%3E\n%3Ccircle cx='40' cy='56' r='10' class='d' stroke='none'/%3E%3C/g%3E%3C/svg%3E\">\n<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans+Condensed:wght@500;600&family=IBM+Plex+Sans:wght@400;500&display=swap\">\n<style>\n/* hidden must hide, even on elements whose class sets a display (claude.ai adds this rule around the page; elsewhere it is ours) */\n[hidden] { display: none !important; }\n/* Layout: work table. Patch (score paper) and its code projection on top, the branching history as a full-width timeline band, REPL along the foot. */\n:root {\n --paper: #eef1f4;\n --sheet: #f8f9fb;\n --grid: #d9dfe6;\n --ink: #1b2430;\n --ink-soft: #5a6676;\n --rule: #c3ccd6;\n --box: #ffffff;\n --accent: #2f55d4;\n --accent-soft: rgba(47, 85, 212, 0.12);\n --kairos: #b4472e;\n --error: #b42318;\n --ok: #2e7d4f;\n --f-ui: \"IBM Plex Sans\", \"Helvetica Neue\", Arial, sans-serif;\n --f-head: \"IBM Plex Sans Condensed\", \"Arial Narrow\", \"Helvetica Neue\", sans-serif;\n --f-code: \"IBM Plex Mono\", ui-monospace, \"SFMono-Regular\", Menlo, Consolas, monospace;\n}\n@media (prefers-color-scheme: dark) {\n :root:not([data-theme=\"light\"]) {\n --paper: #12161c; --sheet: #171c23; --grid: #232a33; --ink: #e3e8ee; --ink-soft: #95a1b0;\n --rule: #333c48; --box: #1e252e; --accent: #7d9bff; --accent-soft: rgba(125, 155, 255, 0.16);\n --kairos: #e58a6f; --error: #ff8a80; --ok: #7fd1a0; color-scheme: dark;\n }\n}\n:root[data-theme=\"dark\"] {\n --paper: #12161c; --sheet: #171c23; --grid: #232a33; --ink: #e3e8ee; --ink-soft: #95a1b0;\n --rule: #333c48; --box: #1e252e; --accent: #7d9bff; --accent-soft: rgba(125, 155, 255, 0.16);\n --kairos: #e58a6f; --error: #ff8a80; --ok: #7fd1a0; color-scheme: dark;\n}\nhtml, body { height: 100%; }\nbody { background: var(--paper); color: var(--ink); font-family: var(--f-ui); font-size: 14px; }\n.app { box-sizing: border-box; min-height: 100%; display: grid; grid-template-rows: auto auto auto auto; gap: 12px; padding-inline: 16px; padding-block: 14px 16px; }\nheader { display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 16px; }\nheader h1 { margin: 0; font-family: var(--f-head); font-weight: 600; font-size: 20px; letter-spacing: 0.01em; line-height: 1; }\n/* the logotype (brand/kairotic-logo.svg, drawn in the theme's ink and kairos) */\nheader h1 .logo { display: inline-block; height: 26px; width: auto; vertical-align: -4px; }\n.logo g { fill: none; stroke: var(--ink); stroke-linecap: round; }\n.logo .t, .logo .f { fill: var(--ink); } .logo .t { stroke: none; } .logo .d { fill: var(--kairos); }\nheader .sub { color: var(--ink-soft); font-size: 13px; }\nheader .status { margin-left: auto; font-family: var(--f-code); font-size: 12px; color: var(--ink-soft); }\nheader .status b { font-weight: 500; }\nheader .status b.on { color: var(--ok); }\nheader .status b.off { color: var(--kairos); }\n.work { display: grid; grid-template-columns: minmax(0, 1.55fr) 12px minmax(0, 1fr); gap: 0; min-height: 0; }\n/* the patch and the panel on the right have a height of their own, from the window (issue #166): what grows in\n one (a long step of a lesson, a long list in a tab) scrolls inside it, and does not make the other taller */\n:root { --work-h: clamp(460px, calc(100vh - 120px), 660px); }\n.work > .pane { height: var(--work-h); }\n.side-pane > .panel { overflow: auto; }\n/* the panel on the right (issue #40): dragged to a width of its own, or hidden; the splitter between them */\n.work.sized { grid-template-columns: minmax(0, 1fr) 12px var(--side-w, 420px); }\n.work.side-off { grid-template-columns: minmax(0, 1fr) 12px; }\n.work.side-off > .side-pane { display: none; }\n.splitter { position: relative; cursor: col-resize; touch-action: none; display: flex; justify-content: center; }\n.splitter::before { content: \"\"; position: absolute; top: 0; bottom: 0; left: 5px; width: 2px; border-radius: 1px; background: transparent; transition: background 0.15s; }\n.splitter:hover::before, .splitter.dragging::before { background: var(--accent); }\n.side-off .splitter { cursor: default; }\n.side-off .splitter:hover::before { background: transparent; }\n.side-toggle { position: relative; z-index: 1; margin-top: 8px; width: 12px; height: 40px; padding: 0; border: 1px solid var(--rule); border-radius: 4px; background: var(--sheet); color: var(--ink-soft); font-size: 11px; line-height: 1; cursor: pointer; }\n.side-toggle:hover { color: var(--ink); border-color: var(--accent); }\n.side-hide { margin-left: auto; font: inherit; font-size: 13px; background: none; border: 0; color: var(--ink-soft); cursor: pointer; padding: 0 4px; }\n.side-hide:hover { color: var(--ink); }\n@media (max-width: 860px) {\n .work, .work.sized, .work.side-off { grid-template-columns: minmax(0, 1fr); }\n .splitter { cursor: default; height: 12px; align-items: center; }\n .splitter::before { display: none; }\n .side-toggle { margin-top: 0; width: 48px; height: 12px; }\n}\n.pane { background: var(--sheet); border: 1px solid var(--rule); border-radius: 6px; min-width: 0; display: flex; flex-direction: column; min-height: 0; }\n.pane-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 10px; border-bottom: 1px solid var(--rule); font-size: 12px; color: var(--ink-soft); }\n.pane-head .label { font-family: var(--f-head); font-weight: 600; font-size: 13px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink); }\n.pane-head .hint { margin-left: auto; text-align: right; }\n.canvas-wrap { position: relative; overflow: auto; flex: 1 1 0; min-height: 180px; }\n#canvas { display: block; width: 900px; height: 680px; max-width: none; touch-action: none; user-select: none; -webkit-user-select: none; }\n#canvas .bg { fill: url(#grid); }\n#canvas .box rect.body { fill: var(--box); stroke: var(--ink); stroke-width: 1; }\n#canvas .box.kairos rect.body { stroke: var(--kairos); stroke-width: 1.25; }\n#canvas .box.sub rect.body { stroke: var(--accent); stroke-width: 2; }\n/* patch @name: a line used as a sub-patch (#117) — following it, pinned, or with something wrong */\n#canvas .box.ref rect.body { stroke-dasharray: 6 3; }\n#canvas .box.ref.pinned rect.body { stroke: var(--kairos); }\n#canvas .box.ref.warn rect.body { stroke: var(--error); }\n#canvas .box .ref-badge { fill: var(--accent); font-family: var(--f-code); font-size: 11px; }\n#canvas .box.ref.pinned .ref-badge { fill: var(--kairos); }\n#canvas .box.ref.warn .ref-badge { fill: var(--error); }\n#canvas .box.presented rect.body { stroke-dasharray: 5 3; }\n#canvas .box.panel rect.head { fill: var(--accent-soft); stroke: none; }\n#canvas .pres-area { fill: transparent; cursor: pointer; }\n#canvas .resize-corner { fill: var(--rule); cursor: nwse-resize; opacity: 0.6; }\n#canvas .box:hover .resize-corner { fill: var(--accent); opacity: 1; }\n#canvas .chip { fill: var(--sheet); stroke: var(--rule); }\n.pres .port, .pres .grip { display: none; }\n.pres #canvas { background-image: none; }\n#pres-toggle.on { background: var(--accent); color: var(--paper); }\n/* Perform (issue #5): the take is outside the history; the patch says so */\n#perform-toggle.on { background: var(--kairos); border-color: var(--kairos); color: var(--paper); }\n#perform-toggle.on::before { content: \"● \"; }\n.perform-info { font-family: var(--f-code); font-size: 12px; color: var(--kairos); }\nbody.performing .canvas-wrap { box-shadow: inset 0 0 0 2px var(--kairos); }\nbody.performing #canvas .bg { opacity: 0.6; }\n.perform-pop, .jam-invite { position: fixed; z-index: 60; max-width: min(440px, calc(100vw - 32px)); box-sizing: border-box; padding: 12px 14px;\n background: var(--sheet); color: var(--ink); border: 1px solid var(--rule); border-left: 3px solid var(--kairos); border-radius: 6px;\n box-shadow: 0 8px 28px rgba(0, 0, 0, 0.18); font-size: 13px; }\n.perform-pop { top: 76px; left: 50%; transform: translateX(-50%); }\n.jam-invite { right: 16px; bottom: 16px; }\n.perform-pop p, .jam-invite p { margin: 0 0 10px; line-height: 1.45; }\n.pp-actions { display: flex; flex-wrap: wrap; gap: 6px; }\n#tree .keyframe { fill: var(--sheet); stroke-width: 2.5; cursor: pointer; }\n#tree .keyframe.take { fill: var(--kairos); fill-opacity: 0.25; }\n#tree .perform-at { fill: none; stroke: var(--kairos); stroke-width: 2; stroke-dasharray: 3 3; pointer-events: none; }\n/* embedding (Study 22) */\nbody:not(.embed) .embed-only { display: none; }\na.act { text-decoration: none; display: inline-block; }\n.embed-pop { margin: 8px 10px 0; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 6px; background: var(--paper); font-size: 12px; display: grid; gap: 6px; }\n.embed-pop .ep-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 14px; }\n.embed-pop .ep-file { display: grid; gap: 6px; padding: 2px 0 10px; margin-bottom: 4px; border-bottom: 1px solid var(--rule); }\n.embed-pop .ep-file .ep-row { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; }\n.embed-pop .ep-modes { display: flex; flex-wrap: wrap; gap: 4px 12px; color: var(--ink-soft); }\n.embed-pop .spacer { flex: 1; }\n.embed-pop .ep-l { color: var(--ink-soft); }\n.embed-pop .ep-row { display: flex; gap: 6px; align-items: flex-start; }\n.embed-pop input, .embed-pop textarea { flex: 1; min-width: 0; font-family: var(--f-code); font-size: 11px; color: var(--ink); background: var(--sheet); border: 1px solid var(--rule); border-radius: 4px; padding: 4px 6px; resize: vertical; }\n.embed-pop .ep-what, .embed-pop .ep-note { margin: 0; color: var(--ink-soft); }\nbody.embed .app { height: 100vh; height: 100dvh; min-height: 0; padding: 0; gap: 0; grid-template-rows: minmax(0, 1fr); }\nbody.embed header, body.embed .manager, body.embed .pane[aria-label=\"Projections\"], body.embed .pane[aria-label=\"History\"],\nbody.embed .pane.repl, body.embed #side-split, body.embed .pane-head .hint, body.embed #perform-toggle, body.embed #annot-toggle, body.embed #annot-bar, body.embed #perform-info, body.embed #snap-btn, body.embed #embed-btn, body.embed #embed-pop, body.embed #lesson-back { display: none !important; }\nbody.embed .work { display: flex; min-height: 0; height: 100%; }\nbody.embed .work > .pane { height: auto; }\nbody.embed .pane { flex: 1; border: 0; border-radius: 0; }\nbody.embed .pane-head { padding: 5px 8px; }\nbody.embed .embed-only { display: inline-block; }\nbody.embed .canvas-wrap { min-height: 0; max-height: none; overflow: hidden; }\nbody.embed #canvas .bg { display: none; }\nbody.embed .lesson-note { max-height: 30vh; overflow: auto; }\n/* only the presentation: the controls float in a corner, over the patch */\nbody.present .pane-head { position: absolute; z-index: 5; top: 6px; right: 6px; border: 1px solid var(--rule); border-radius: 6px; background: var(--sheet); opacity: 0.55; transition: opacity 0.2s; }\nbody.present .pane-head:hover, body.present .pane-head:focus-within { opacity: 1; }\nbody.present .pane-head .label, body.present #crumbs, body.present #transport-info, body.present #pres-toggle { display: none; }\nbody.present .pane { position: relative; }\nbody.present .lesson { display: none; }\n.trust-bar { margin: 6px 10px 0; padding: 6px 10px; border: 1px solid var(--kairos); border-radius: 6px; font-size: 12px; color: var(--ink); }\nbody.present .trust-bar { position: absolute; z-index: 5; left: 6px; top: 6px; margin: 0; background: var(--sheet); max-width: 60%; }\n/* the lines of the work (#117): independent histories, a tab each, above the patch */\n.line-tabs { display: flex; align-items: flex-end; gap: 2px; padding: 4px 10px 0; border-bottom: 1px solid var(--rule); overflow-x: auto; scrollbar-width: thin; font-size: 12px; }\n.ltab { flex: none; display: inline-flex; align-items: baseline; gap: 5px; font: 500 12.5px var(--f-code); color: var(--ink-soft); background: none; border: 1px solid transparent; border-bottom: none; border-radius: 5px 5px 0 0; padding: 4px 10px 5px; margin-bottom: -1px; cursor: pointer; }\n.ltab:hover { color: var(--ink); background: var(--sheet); }\n.ltab[aria-selected=\"true\"] { color: var(--ink); background: var(--box); border-color: var(--rule); border-bottom: 1px solid var(--box); }\n.ltab .star { color: var(--kairos); font-size: 10.5px; }\n.ltab .plays { color: var(--accent); font-size: 10px; }\n.ltab .who { font: 11px var(--f-ui); color: var(--ink-soft); }\n.ltab .x { font: 13px var(--f-ui); color: var(--ink-soft); padding: 0 0 0 2px; border-radius: 3px; }\n.ltab .x:hover { color: var(--error); }\n.line-tabs .ladd { flex: none; border: 0; background: none; color: var(--accent); font: 600 15px var(--f-ui); padding: 2px 9px 5px; cursor: pointer; }\n.line-tabs input { flex: none; width: 10em; font: 12px var(--f-code); padding: 2px 6px; margin: 0 4px 4px; border: 1px solid var(--accent); border-radius: 4px; background: var(--box); color: var(--ink); }\n.line-tabs select { flex: none; margin: 0 0 4px 8px; font: 12px var(--f-ui); padding: 2px 4px; color: var(--ink-soft); background: var(--box); border: 1px solid var(--rule); border-radius: 4px; }\nbody.embed .line-tabs, body.present .line-tabs { display: none !important; }\n.crumbs { font-family: var(--f-code); font-size: 12px; color: var(--ink-soft); }\n.crumbs button { font: inherit; color: var(--accent); background: none; border: 0; padding: 0 2px; cursor: pointer; }\n.crumbs button:hover { text-decoration: underline; }\n.crumbs .here { color: var(--ink); }\n/* boxes are always opaque, so the wires never show through them (the tint mixed with the box colour) */\n#canvas .box.sel rect.body { stroke: var(--accent); stroke-width: 2; fill: color-mix(in srgb, var(--accent) 12%, var(--box)); }\n#canvas .box.hit rect.body { stroke: var(--accent); stroke-width: 1.5; }\n#canvas .marquee { fill: var(--accent-soft); stroke: var(--accent); stroke-width: 1; stroke-dasharray: 4 3; pointer-events: none; }\n#canvas .box.drop rect.body { stroke: var(--accent); stroke-dasharray: 3 3; }\n#canvas .box > text, #canvas .box text.lbl { font-family: var(--f-code); font-size: 12.5px; fill: var(--ink); pointer-events: none; }\n#canvas .box text.lbl.info { font-size: 11px; fill: var(--ink-soft); }\n#canvas .box .hchip { cursor: pointer; }\n#canvas .box .hchip rect { fill: var(--box); stroke: var(--rule); stroke-width: 1; }\n#canvas .box .hchip text { font-family: var(--f-code); font-size: 10.5px; fill: var(--accent); pointer-events: none; }\n#canvas .box .hchip:hover rect { fill: var(--accent-soft); stroke: var(--accent); }\n#canvas .mus rect.head { fill: var(--accent-soft); stroke: none; }\n#canvas .mus-body { cursor: crosshair; }\n#canvas .rbg { fill: var(--sheet); }\n#canvas .rrow.blk { fill: var(--ink); fill-opacity: 0.06; }\n#canvas .rbeat { stroke: var(--grid); stroke-width: 1; }\n#canvas .rbar { stroke: var(--rule); stroke-width: 1.25; }\n#canvas .box text.rlabel { font-family: var(--f-code); font-size: 9px; fill: var(--ink-soft); pointer-events: none; }\n#canvas .rnota { fill: var(--accent); fill-opacity: 0.85; stroke: var(--accent); stroke-width: 1; cursor: grab; }\n#canvas .rnota.sel { fill: var(--kairos); stroke: var(--ink); stroke-width: 1.25; }\n#canvas .paper { fill: #fbfaf6; stroke: var(--rule); }\n#canvas .score-slot { color: #1b2430; fill: #1b2430; }\n#canvas .score-slot g.note, #canvas .score-slot g.rest { cursor: pointer; }\n#canvas .score-slot g.note.sel, #canvas .score-slot g.note.sel * { fill: #c2410c; stroke: #c2410c; color: #c2410c; }\n#canvas .box text.wait { font-family: var(--f-ui); font-size: 12px; fill: #5a6676; }\n#canvas .cur { stroke: var(--kairos); stroke-width: 2; pointer-events: none; }\n#canvas .cur2 { stroke: var(--accent); stroke-width: 1.5; stroke-dasharray: 3 3; pointer-events: none; }\n#canvas .sounding { fill: var(--kairos); stroke: var(--sheet); stroke-width: 1.5; pointer-events: none; }\n#canvas .lbg { fill: var(--sheet); cursor: crosshair; }\n#canvas .lgx0, #canvas .lgy0 { stroke: var(--grid); stroke-width: 1; }\n#canvas .lgx1, #canvas .lgy1 { stroke: var(--rule); stroke-width: 1.25; }\n#canvas .lgx2 { stroke: var(--ink-soft); stroke-width: 1.25; stroke-opacity: 0.7; }\n#canvas .stroke { fill: none; stroke: var(--accent); stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }\n#canvas .stroke.sel { stroke: var(--kairos); stroke-width: 3.5; }\n#canvas .stroke.new { stroke: var(--kairos); stroke-dasharray: 5 3; }\n#canvas .stroke-hit { fill: none; stroke: transparent; stroke-width: 11; stroke-linecap: round; cursor: grab; }\n#canvas .box.act .grip { fill: var(--ink); fill-opacity: 0.18; cursor: grab; }\n#canvas .box.act { cursor: pointer; }\n/* one pointer for everything that is played (no resize arrows on views made of parts) */\n#canvas .box.act.number { cursor: pointer; }\n#canvas .box.act.ctl, #canvas .ctl-area { cursor: pointer; }\n/* the part of a component's view under (or near) the pointer */\n#canvas .hit-hover .shape { stroke: var(--accent) !important; stroke-width: 2.5px; fill: var(--accent) !important; fill-opacity: 0.28; }\n#canvas .hit-hover text.shape { fill-opacity: 1; stroke-width: 0.6px; }\n#canvas .ctl-area { fill: transparent; }\n#canvas .shapes, #canvas .shapes * { pointer-events: none; }\n/* layers (Study 26): marks and projections, over or under the boxes; they do not take the pointer */\n#layers-under, #layers-over, #layers-under *, #layers-over * { pointer-events: none; }\n#canvas .amark { fill: none; stroke: var(--kairos); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }\n#canvas .amark.new { stroke: var(--accent); stroke-dasharray: 4 3; }\n#canvas .ahead { fill: var(--kairos); stroke: none; }\n#canvas .atext { fill: var(--kairos); font: italic 15px var(--f-ui); }\n#canvas .proj { opacity: 0.9; }\n.annot-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; padding: 6px 10px; border-bottom: 1px solid var(--rule); background: var(--box); font-size: 12px; }\n.annot-bar .spacer { flex: 1; }\n.annot-tools { display: inline-flex; gap: 4px; }\n.annot-tools .act[aria-pressed=\"true\"] { border-color: var(--kairos); color: var(--kairos); }\n.annot-bar input:not([type]) { font: inherit; padding: 3px 6px; border: 1px solid var(--rule); border-radius: 4px; background: var(--sheet); color: var(--ink); min-width: 0; }\n#annot-text { flex: 1 1 160px; } #annot-layer { width: 8em; }\n.annot-l { display: inline-flex; align-items: center; gap: 4px; color: var(--ink-soft); }\nbody.annotating #canvas { cursor: crosshair; }\nbody.annotating.annot-move #canvas { cursor: move; }\n#annot-toggle.on, #learn-toggle.on { border-color: var(--kairos); color: var(--kairos); }\n.learn-scope { display: grid; gap: 4px; margin: 0 0 10px; font-size: 13px; }\n.learn-scope label { display: flex; gap: 6px; align-items: baseline; }\n.learn-mine { font: 12px var(--f-code); color: var(--ink-soft); }\n#canvas .shape { fill: none; stroke: none; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; font-family: var(--f-code); }\n#canvas .shape.s-ink { stroke: var(--ink); } #canvas .shape.f-ink { fill: var(--ink); }\n#canvas .shape.s-soft { stroke: var(--ink-soft); } #canvas .shape.f-soft { fill: var(--ink-soft); }\n#canvas .shape.s-accent { stroke: var(--accent); } #canvas .shape.f-accent { fill: var(--accent); }\n#canvas .shape.s-kairos { stroke: var(--kairos); } #canvas .shape.f-kairos { fill: var(--kairos); }\n#canvas .shape.s-bg { stroke: var(--sheet); } #canvas .shape.f-bg { fill: var(--sheet); }\n#canvas .shape.s-grid { stroke: var(--grid); } #canvas .shape.f-grid { fill: var(--grid); }\n#canvas .box.act.msg rect.body { fill: color-mix(in srgb, var(--accent) 12%, var(--box)); }\n#canvas .box .bangc { fill: none; stroke: var(--ink); stroke-width: 1.5; pointer-events: none; }\n#canvas .flash { fill: var(--kairos); fill-opacity: 0.35; pointer-events: none; }\n#canvas text.value { font-family: var(--f-code); font-size: 12.5px; fill: var(--ink); pointer-events: none; }\n#canvas .wire.buffer { stroke-dasharray: 6 3; stroke: var(--kairos); }\n#canvas .code-area { fill: var(--sheet); cursor: pointer; }\n#canvas .box text.code { font-family: var(--f-code); font-size: 11px; fill: var(--ink); white-space: pre; pointer-events: none; }\n#canvas .box text.lbl.st-ok { font-size: 11px; fill: var(--ok); }\n#canvas .box text.lbl.st-err { font-size: 11px; fill: var(--error); pointer-events: auto; }\n#canvas .box text.lbl.st-wait { font-size: 11px; fill: var(--ink-soft); }\n#canvas .box text.lbl.pname { font-size: 11px; fill: var(--ink-soft); }\n#canvas .param { fill: var(--grid); stroke: var(--rule); cursor: ew-resize; }\n#canvas .param.button { cursor: pointer; }\n#canvas .pfill { fill: var(--accent); fill-opacity: 0.55; pointer-events: none; }\n#canvas text.pval { font-family: var(--f-code); font-size: 11px; fill: var(--ink); pointer-events: none; }\n#canvas .pval-hit { fill: transparent; cursor: text; }\n#canvas .box.code rect.head { fill: rgba(46, 125, 79, 0.14); }\n.comp-list { padding: 4px 12px 14px; overflow: auto; max-height: 520px; font-size: 13px; }\n.comp-list h4 { margin: 14px 0 6px; font-family: var(--f-head); font-weight: 600; font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-soft); }\n.comp-list ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }\n.comp-list li { display: flex; align-items: center; gap: 8px; padding: 5px 8px; border: 1px solid var(--rule); border-radius: 5px; background: var(--box); }\n.comp-list li span { flex: 1; min-width: 0; color: var(--ink-soft); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.comp-list code { font-family: var(--f-code); font-size: 12px; color: var(--ink); }\n.comp-list .empty { color: var(--ink-soft); margin: 0; }\n.comp-list .core-defs { display: flex; flex-wrap: wrap; gap: 4px 10px; margin: 0; }\n.comp-list form { display: flex; gap: 6px; }\n.comp-list .core-defs code.help-link { cursor: pointer; text-decoration: underline dotted; }\n.comp-list li.def { cursor: pointer; }\n.comp-list li.def small { color: var(--ink-soft); font-size: 11px; margin-left: 4px; }\n.comp-list li.def.chosen { border-color: var(--accent); box-shadow: inset 3px 0 0 var(--accent); }\n.comp-list li.def.err span { color: var(--error); }\n.comp-list .comp-new { margin: 8px 0 0; display: flex; align-items: center; gap: 8px; }\n.comp-list .comp-new small { color: var(--ink-soft); }\n/* Help tab (Study 18) */\n.help-view { padding: 6px 14px 16px; overflow: auto; max-height: 560px; font-size: 13px; line-height: 1.5; }\n.help-view h3 { margin: 6px 0 2px; font-family: var(--f-code); font-size: 16px; }\n.help-view h4 { margin: 14px 0 6px; font-family: var(--f-head); font-weight: 600; font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-soft); }\n.help-view .usage { font-family: var(--f-code); font-size: 12px; color: var(--ink-soft); }\n.help-view .pkg { font-size: 11px; color: var(--accent); margin-left: 6px; }\n.help-view ol, .help-view ul.msgs { margin: 0; padding-left: 20px; }\n.help-view ol li::marker { font-family: var(--f-code); color: var(--ink-soft); }\n.help-view table { border-collapse: collapse; font-size: 12px; }\n.help-view td { padding: 2px 10px 2px 0; vertical-align: top; }\n.help-view td:first-child { font-family: var(--f-code); }\n.help-view .doc { max-width: 760px; }\n.help-view .about { max-width: 760px; }\n.help-view .about p { margin: 0 0 8px; }\n.help-view details.all-doc { max-width: 760px; margin: 4px 0 8px; color: var(--ink-soft); }\n.help-view details.all-doc summary { cursor: pointer; font-size: 12px; }\n.help-view td:nth-child(3) { color: var(--ink-soft); }\n.help-view .doc .dh { font-family: var(--f-head); font-weight: 600; color: var(--ink); text-transform: none; letter-spacing: 0; margin: 16px 0 6px; }\n.help-view .doc h2.dh { font-size: 20px; } .help-view .doc h3.dh { font-size: 16px; } .help-view .doc h4.dh { font-size: 14px; } .help-view .doc h5.dh, .help-view .doc h6.dh { font-size: 13px; }\n.help-view .doc pre { font: 12px/1.45 var(--f-code); background: var(--paper); border: 1px solid var(--rule); border-radius: 4px; padding: 8px 10px; overflow: auto; white-space: pre; margin: 6px 0; }\n.help-view .doc code { font-family: var(--f-code); font-size: 12px; }\n.help-view .doc ul, .help-view .doc ol { padding-left: 20px; margin: 6px 0; }\n.help-view .doc li { margin: 2px 0; }\n.help-view .doc blockquote { margin: 8px 0; padding: 4px 12px; border-left: 3px solid var(--rule); color: var(--ink-soft); }\n.help-view .doc table.dt { margin: 8px 0; } .help-view .doc table.dt th, .help-view .doc table.dt td { border-bottom: 1px solid var(--rule); padding: 3px 10px 3px 0; text-align: left; font-family: inherit; }\n.help-view .doc a { color: var(--accent); }\n.help-view .doc .doc-try { margin: 0 0 10px; }\n.help-view .chips { display: flex; flex-wrap: wrap; gap: 4px 8px; }\n.help-view .chip { font-family: var(--f-code); font-size: 12px; padding: 1px 6px; border: 1px solid var(--rule); border-radius: 4px; background: var(--box); cursor: pointer; }\n.help-view .chip:hover, .help-view .tut:hover { border-color: var(--accent); }\n.help-view .try { margin-top: 10px; padding: 6px 10px; border-left: 3px solid var(--accent); background: var(--accent-soft); }\n.help-view .tuts { display: flex; flex-direction: column; gap: 4px; margin: 0; padding: 0; list-style: none; }\n.help-view .tut { display: flex; gap: 8px; align-items: baseline; padding: 5px 8px; border: 1px solid var(--rule); border-radius: 5px; background: var(--box); cursor: pointer; }\n.help-view .tut small { color: var(--ink-soft); }\n.help-view .back { font-size: 12px; }\n.help-view input.help-find { width: 100%; box-sizing: border-box; font: 12px var(--f-code); padding: 4px 8px; border: 1px solid var(--rule); border-radius: 4px; background: var(--box); color: var(--ink); }\n/* lesson bar (Study 18): the note of the step you are at */\n#canvas .wire.edits { stroke-dasharray: 5 4; }\n#canvas .score-slot .tsel, #canvas .score-slot .tsel * { fill: var(--accent) !important; stroke: var(--accent); }\n.lesson { border-bottom: 1px solid var(--rule); background: var(--accent-soft); padding: 6px 12px 8px; font-size: 13px; line-height: 1.5;\n display: flex; flex-direction: column; flex: 0 1 auto; min-height: 0; max-height: 45%; }\n/* a long explanation scrolls inside the strip: the patch keeps the rest of the pane */\n.lesson-note { overflow: auto; min-height: 0; }\n.lesson-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }\n.lesson-head .t { font-weight: 600; }\n.lesson-head .n { font-family: var(--f-code); font-size: 12px; color: var(--ink-soft); }\n.lesson-head .spacer { flex: 1; }\n.lesson-head .lang button[aria-pressed=\"true\"] { border-color: var(--accent); color: var(--accent); }\n.lesson-note p { margin: 6px 0 0; }\n.lesson-note .step-t { font-weight: 600; }\n.lesson-note .try { margin-top: 6px; color: var(--ink-soft); }\n.lesson-note .away { margin-top: 6px; font-style: italic; }\n.lesson-note code, .help-view code.run { font-family: var(--f-code); font-size: 12px; background: var(--box); border: 1px solid var(--rule); border-radius: 3px; padding: 0 4px; }\n.lesson-note code.run, .help-view code.run { cursor: pointer; }\n.comp-list input { flex: 1; min-width: 0; font: inherit; font-family: var(--f-code); font-size: 12px; padding: 4px 8px; border: 1px solid var(--rule); border-radius: 4px; background: var(--box); color: var(--ink); }\n/* the code editor (issue #8): a window over the page, moved by its bar, resized by its corner */\n.code-win { position: fixed; z-index: 40; display: flex; flex-direction: column; box-sizing: border-box; min-width: 300px; min-height: 180px;\n max-width: calc(100vw - 16px); max-height: calc(100vh - 16px); resize: both; overflow: hidden;\n background: var(--box); color: var(--ink); border: 1px solid var(--rule); border-radius: 8px;\n box-shadow: 0 14px 40px rgba(0, 0, 0, 0.22), 0 2px 6px rgba(0, 0, 0, 0.08); }\n.code-win:focus-within { border-color: var(--accent); }\n.cw-bar { display: flex; align-items: center; gap: 8px; padding: 6px 6px 6px 12px; background: var(--sheet); border-bottom: 1px solid var(--rule);\n cursor: grab; user-select: none; -webkit-user-select: none; touch-action: none; }\n.cw-bar:active { cursor: grabbing; }\n.cw-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--f-code); font-size: 12.5px; }\n.cw-title b { font-weight: 600; color: var(--accent); }\n.cw-lang { font-family: var(--f-head); font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-soft);\n border: 1px solid var(--rule); border-radius: 3px; padding: 0 5px; }\n.cw-bar .cw-x { padding: 2px 9px; font-size: 15px; line-height: 1; }\n.cw-confirm { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 7px 12px; font-size: 12.5px;\n background: var(--accent-soft); border-bottom: 1px solid var(--rule); }\n.cw-confirm[hidden] { display: none; }\n.cw-body { flex: 1; min-height: 0; overflow: hidden; }\n.cw-body .cm-editor { height: 100%; }\n/* a faust~: its patch (@kairotic/faust-units) on the left, its code on the right; Patch in the bar hides it */\n.cw-body.split { display: flex; }\n.cw-body.split .cw-patch { flex: 1.15 1 0; min-width: 0; border-right: 1px solid var(--rule); }\n.cw-body.split .cw-text { flex: 1 1 0; min-width: 0; height: 100%; }\n.cw-body.split.nopatch .cw-patch { display: none; }\n.cw-bar .cw-pv { padding: 2px 9px; font-size: 12px; }\n.cw-bar .cw-pv[aria-pressed=\"true\"] { background: var(--accent-soft); border-color: var(--accent); }\n.cw-pv-err { margin: 12px; font-size: 12px; color: var(--error); }\n/* a faust~'s recipe (discussion #114, Study 35): the settings of its sliders that sound like a sound */\n.cw-rcp { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 6px 12px; font-size: 12.5px;\n background: var(--sheet); border-bottom: 1px solid var(--rule); }\n.cw-rcp[hidden] { display: none; }\n.cw-rcp select { font: inherit; font-size: 12px; padding: 2px 4px; border: 1px solid var(--rule); border-radius: 4px; background: var(--box); color: var(--ink); max-width: 14em; }\n.cw-rcp .rcp-st { flex: 1 1 12em; min-width: 0; font-family: var(--f-code); font-size: 11.5px; color: var(--ink-soft); }\n.cw-rcp .rcp-st.err { color: var(--error); }\n.cw-rcp .rcp-play[hidden] { display: none; }\n@media (max-width: 700px) { .cw-body.split { flex-direction: column; } .cw-body.split .cw-patch { border-right: 0; border-bottom: 1px solid var(--rule); } }\n.cw-plain { box-sizing: border-box; width: 100%; height: 100%; border: 0; outline: none; resize: none; padding: 8px 10px;\n font-family: var(--f-code); font-size: 12.5px; line-height: 1.5; background: var(--box); color: var(--ink); white-space: pre; tab-size: 2; }\n.cw-foot { padding: 4px 12px; font-family: var(--f-code); font-size: 11.5px; color: var(--ink-soft); background: var(--sheet);\n border-top: 1px solid var(--rule); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n.cw-foot.err { color: var(--error); }\n#canvas .code-area.open { fill: var(--accent-soft); stroke: var(--accent); }\n#canvas .box text.code.lines { fill: var(--ink-soft); font-size: 10.5px; }\n.transport { display: inline-flex; align-items: center; gap: 4px; }\n.transport button { font-family: var(--f-code); min-width: 34px; }\n.transport button.on { background: var(--ok); border-color: var(--ok); color: #fff; }\n#transport-info { font-family: var(--f-code); font-size: 12px; color: var(--ink-soft); }\n#canvas .box { cursor: grab; }\n/* in presentation a plain drag does not move a box (⌥+drag does) */\n#canvas-wrap.pres .box { cursor: default; }\n#canvas-wrap.pres .box.act, #canvas-wrap.pres .box .grip { cursor: pointer; }\n#canvas-wrap.pres .mus-body { cursor: crosshair; }\n/* patching, as in every patcher of Kairotic (the patch of a faust~ too: packages/faust-units/assets/view.mjs):\n curved wires; an outlet within reach lights up and the pointer is a cross; the inlet a wire would land on too */\n#canvas .port { fill: var(--ink); transform-box: fill-box; transform-origin: center; transition: transform 0.08s ease-out, fill 0.08s; }\n#canvas .port.out { cursor: crosshair; }\n#canvas .box.kairos .port { fill: var(--kairos); }\n#canvas .port.out.hot, #canvas .port.in.target { fill: var(--accent); transform: scale(1.4, 2); }\n#canvas.near-out, #canvas.near-out *, #canvas.wiring, #canvas.wiring * { cursor: crosshair !important; }\n#canvas .wire { fill: none; stroke: var(--ink); stroke-width: 1.5; }\n#canvas .wire.sel { stroke: var(--accent); stroke-width: 2.5; }\n#canvas .wire.probed { stroke: var(--accent); stroke-dasharray: 2 3; stroke-width: 2; }\n#canvas .probe rect { fill: var(--sheet); stroke: var(--accent); stroke-width: 1; }\n#canvas .probe text { font: 11px var(--f-code); fill: var(--ink); }\n#canvas .probe.hot rect { fill: var(--accent); }\n#canvas .probe.hot text { fill: var(--paper); }\n#canvas .probe { pointer-events: none; }\n#canvas .wire-hit { fill: none; stroke: transparent; stroke-width: 12; cursor: pointer; }\n#canvas .wire.temp { stroke: var(--accent); stroke-dasharray: 4 4; pointer-events: none; }\n#inspector { position: absolute; z-index: 6; width: max-content; max-width: 340px; padding: 6px 8px; background: var(--box); color: var(--ink); border: 1px solid var(--rule); border-left: 3px solid var(--accent); border-radius: 4px; box-shadow: 0 2px 10px rgba(0,0,0,0.14); font: 12px var(--f-ui); }\n#inspector .insp-head span { color: var(--ink-soft); font-family: var(--f-code); font-size: 11px; }\n#inspector .insp-acts { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; align-items: center; }\n#inspector .insp-acts .act { font-size: 11.5px; padding: 2px 8px; }\n#inspector .insp-args { display: flex; flex-wrap: wrap; gap: 4px 10px; margin: 6px 0 4px; }\n#inspector label { font-family: var(--f-code); font-size: 11.5px; color: var(--ink-soft); white-space: nowrap; }\n#inspector input { font-family: var(--f-code); font-size: 12px; background: var(--sheet); color: var(--ink); border: 1px solid var(--rule); border-radius: 3px; padding: 2px 4px; }\n#inspector input:focus { outline: none; border-color: var(--accent); }\n#inspector .insp-text { display: block; width: 100%; box-sizing: border-box; margin-top: 4px; }\n.ask { display: flex; flex-direction: column; gap: 8px; padding: 10px 12px; overflow: auto; flex: 1; }\n.ask-note { margin: 0; font-size: 12px; color: var(--ink-soft); line-height: 1.45; }\n.ask-what { display: flex; gap: 14px; font-size: 12px; }\n.askbar { margin: 6px 10px 0; padding: 8px 10px; border: 1px solid var(--accent); border-radius: 6px; font-size: 12px; display: grid; gap: 6px; background: var(--sheet); }\n.askbar .ab-q { color: var(--ink); line-height: 1.4; }\n.askbar .ab-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }\n.askbar input { flex: 1; min-width: 160px; font-family: var(--f-code); font-size: 11px; color: var(--ink); background: var(--paper); border: 1px solid var(--rule); border-radius: 4px; padding: 4px 6px; }\n.askbar .ab-status { color: var(--ink-soft); font-family: var(--f-code); font-size: 11px; }\n.askbar .ab-note { margin: 0; color: var(--ink-soft); }\nbody.present .askbar { position: absolute; z-index: 6; left: 6px; top: 6px; margin: 0; max-width: min(520px, 70%); }\n#ask-text { min-height: 92px; resize: vertical; font: 13px/1.45 var(--f-ui); color: var(--ink); background: var(--sheet); border: 1px solid var(--rule); border-radius: 4px; padding: 8px; }\n#ask-text:focus { outline: none; border-color: var(--accent); }\n.ask-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }\n.fb { display: grid; gap: 8px; padding: 10px 14px 16px; overflow: auto; max-height: 560px; }\n.fb .fb-kind, .fb .fb-opts { display: flex; flex-wrap: wrap; gap: 4px 14px; font-size: 12px; }\n.fb .fb-opts { color: var(--ink-soft); }\n.fb input#fb-title, .fb textarea { font: 13px var(--f-ui); color: var(--ink); background: var(--paper); border: 1px solid var(--rule); border-radius: 4px; padding: 6px 8px; }\n.fb textarea { min-height: 130px; resize: vertical; }\n.fb h4 { margin: 10px 0 0; font-family: var(--f-head); font-weight: 600; font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-soft); }\n.fb .fb-prev summary { cursor: pointer; font-size: 12px; color: var(--ink-soft); }\n.fb .fb-prev pre { font: 11px/1.45 var(--f-code); white-space: pre-wrap; background: var(--paper); border: 1px solid var(--rule); border-radius: 4px; padding: 6px 8px; max-height: 220px; overflow: auto; }\n.fb .fb-list { margin: 0; padding-left: 18px; font-size: 12px; display: grid; gap: 3px; }\n.fb .fb-list a { color: var(--ink); } .fb .fb-list .lb { font: 10.5px var(--f-code); color: var(--ink-soft); margin-left: 6px; }\n.fb .fb-list a.fb-claude { margin-left: 8px; font: 10.5px var(--f-code); color: var(--accent); text-decoration: none; border: 1px solid var(--rule);\n border-radius: 3px; padding: 0 5px; white-space: nowrap; }\n.fb .fb-list a.fb-claude:hover { border-color: var(--accent); background: var(--accent-soft); }\n.fb .soft { color: var(--ink-soft); }\n.ask-bar select { font: 12px var(--f-ui); background: var(--sheet); color: var(--ink); border: 1px solid var(--rule); border-radius: 3px; padding: 3px 4px; }\n.ask-hist summary { cursor: pointer; font-size: 12px; color: var(--ink); }\n.ask-hist-list { margin: 6px 0 0; padding: 0; list-style: none; display: grid; gap: 6px; }\n.ask-hist-list li { border: 1px solid var(--rule); border-radius: 5px; padding: 6px 8px; font-size: 12px; display: grid; gap: 3px; }\n.ask-hist-list .ah-top { color: var(--ink-soft); font: 11px var(--f-code); }\n.ask-hist-list .ah-top .made { color: var(--ok); } .ask-hist-list .ah-top .failed { color: var(--error); }\n.ask-hist-list .ah-q { color: var(--ink); }\n.ask-hist-list .ah-acts { display: flex; flex-wrap: wrap; gap: 4px; }\n.ask-log { margin: 0; padding-left: 18px; font: 11.5px/1.5 var(--f-code); color: var(--ink-soft); }\n.ask-log li.ok { color: var(--ok); } .ask-log li.err { color: var(--error); } .ask-log li.done { color: var(--ink); font-weight: 600; }\n.ask-key { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }\n.ask-key input { flex: 1; min-width: 180px; font: 12px var(--f-code); background: var(--sheet); color: var(--ink); border: 1px solid var(--rule); border-radius: 3px; padding: 4px 6px; }\n.ask-key-state { font-size: 11.5px; color: var(--ink-soft); }\n.ask-out { margin: 0; white-space: pre-wrap; font: 12px/1.5 var(--f-code); color: var(--ink); background: var(--sheet); border: 1px solid var(--grid); border-radius: 4px; padding: 8px; max-height: 360px; overflow: auto; }\n.ask-out:empty { display: none; }\n.edit { position: absolute; font-family: var(--f-code); font-size: 12.5px; padding: 4px 8px; border: 2px solid var(--accent); border-radius: 3px; background: var(--box); color: var(--ink); outline: none; min-width: 140px; }\n.edit.num { min-width: 0; width: 96px; z-index: 5; } /* a number typed into a control (issue #32) */\n/* the field of a new box as a line of the REPL, and what it gave (issue #163) */\n.edit.as-repl { border-color: var(--kairos); min-width: 320px; z-index: 6; }\n.edit-out { position: absolute; z-index: 6; max-width: 520px; font-family: var(--f-code); font-size: 12px; color: var(--ink-soft);\n background: var(--box); border: 1px solid var(--rule); border-radius: 3px; padding: 2px 8px; white-space: pre-wrap; word-break: break-word; }\n.edit-out:empty { display: none; }\n/* the line of the REPL on the patch as a code editor: what it gave goes right below, inside it */\n.edit.repl-line { padding: 0 6px; display: flex; flex-direction: column; max-width: 640px; }\n.repl-line-host { min-width: 0; max-height: 40vh; overflow: auto; }\n.repl-line-host .cm-editor { background: transparent !important; font-size: 12.5px; }\n.repl-line-host .cm-content { padding: 4px 0 !important; }\n.repl-line-host .cm-line { padding: 0; }\n.repl-line-host .cm-placeholder { color: var(--ink-soft); }\n.repl-line .edit-out { position: static; max-width: none; border: 0; border-top: 1px solid var(--rule); border-radius: 0; margin: 0 -6px; }\n.edit-out.err { color: var(--error); }\n/* box ids (issue #163): on a box hovered or selected, on all of them with I; a box under the pointer while a\n line of code waits for one is marked, and a click writes its id there */\n#canvas .idtag { display: none; font-family: var(--f-code); font-size: 10.5px; fill: var(--accent); pointer-events: none;\n paint-order: stroke; stroke: var(--sheet); stroke-width: 3px; stroke-linejoin: round; }\n#canvas .box:hover .idtag, #canvas .box.sel .idtag, #canvas.show-ids .idtag { display: inline; }\n#canvas.picking .box, #canvas.picking .box * { cursor: copy !important; }\n#canvas.picking .box:hover > rect.body { stroke: var(--kairos); stroke-width: 2; }\n#canvas.picking .box:hover .idtag { fill: var(--kairos); font-weight: 600; }\n#canvas .box.picked > rect.body { stroke: var(--kairos); stroke-width: 3; }\n.edit.num.bad { border-color: var(--error); }\n.tabs { display: flex; gap: 2px; }\n.tab { font: inherit; font-family: var(--f-head); font-weight: 600; font-size: 13px; letter-spacing: 0.06em; text-transform: uppercase; background: none; border: 0; border-bottom: 2px solid transparent; color: var(--ink-soft); padding: 2px 8px 4px; cursor: pointer; }\n.tab[aria-selected=\"true\"] { color: var(--ink); border-bottom-color: var(--accent); }\n.tab:focus-visible, button:focus-visible, textarea:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }\n.panel { flex: 1; min-height: 0; display: flex; flex-direction: column; }\n#code { flex: 1; min-height: 300px; resize: none; border: 0; background: transparent; color: var(--ink); font-family: var(--f-code); font-size: 12.5px; line-height: 1.6; padding: 10px 12px; white-space: pre; overflow: auto; tab-size: 2; }\n#code:focus { outline: none; background: var(--accent-soft); }\n.code-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 10px; border-top: 1px solid var(--rule); font-size: 12px; color: var(--ink-soft); }\n.code-bar .state.dirty { color: var(--kairos); font-weight: 500; }\n.code-bar .spacer { flex: 1; }\nbutton.act { font: inherit; font-size: 12.5px; padding: 4px 10px; border-radius: 4px; border: 1px solid var(--rule); background: var(--box); color: var(--ink); cursor: pointer; }\nbutton.act.primary { background: var(--accent); border-color: var(--accent); color: #fff; }\n:root[data-theme=\"dark\"] button.act.primary { color: #0e1420; }\n@media (prefers-color-scheme: dark) { :root:not([data-theme=\"light\"]) button.act.primary { color: #0e1420; } }\nbutton.act[disabled] { opacity: 0.45; cursor: default; }\npre.view { margin: 0; flex: 1; min-height: 300px; overflow: auto; padding: 10px 12px; font-family: var(--f-code); font-size: 12px; line-height: 1.55; color: var(--ink); }\n/* Calls / Data: the two ways the Code tab shows the work */\n.code-views { display: inline-flex; }\n.code-views button.act { border-radius: 0; font-size: 12px; padding: 3px 9px; }\n.code-views button.act:first-child { border-radius: 4px 0 0 4px; }\n.code-views button.act:last-child { border-radius: 0 4px 4px 0; margin-left: -1px; }\n.code-views button.act[aria-pressed=\"true\"] { background: var(--accent-soft); border-color: var(--accent); color: var(--ink); font-weight: 600; position: relative; }\n\n/* history band */\n.hist-nav { display: flex; gap: 4px; }\n.hist-nav button { font-family: var(--f-code); min-width: 34px; }\n.peers { display: flex; flex-wrap: wrap; gap: 6px; }\n.chip { display: inline-flex; align-items: center; gap: 6px; font: inherit; font-size: 12px; padding: 2px 9px 2px 6px; border-radius: 999px; border: 1px solid var(--rule); background: var(--box); color: var(--ink); cursor: pointer; }\n.chip .dot { width: 9px; height: 9px; border-radius: 50%; display: inline-block; }\n.chip.me { cursor: default; }\n.chip.following { border-color: var(--accent); background: var(--accent-soft); }\n.hist-wrap { overflow: auto; max-height: 230px; min-height: 96px; }\n#tree { display: block; }\n#tree .lane { stroke-width: 2.5; stroke-linecap: round; fill: none; }\n#tree .fork { stroke-width: 1.25; fill: none; stroke-dasharray: 2 3; }\n#tree .ev { cursor: pointer; }\n#tree .ev:hover { stroke: var(--ink); stroke-width: 2; }\n#tree .picked { stroke: var(--error); stroke-width: 3; }\n#tree .origin { fill: var(--sheet); stroke: var(--ink-soft); stroke-width: 1.5; cursor: pointer; }\n#tree .here { fill: none; stroke: var(--accent); stroke-width: 2.5; pointer-events: none; }\n#tree .peer { fill: none; stroke-width: 2; pointer-events: none; }\n#tree .merge { fill: none; stroke-width: 1.5; stroke-dasharray: 5 3; }\n#tree .mergemark { stroke: var(--sheet); stroke-width: 1.5; }\n.opt { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; color: var(--ink); white-space: nowrap; }\n.opt input[type=\"number\"] { width: 64px; font: inherit; font-family: var(--f-code); padding: 2px 4px; border: 1px solid var(--rule); border-radius: 4px; background: var(--box); color: var(--ink); }\n.picking #tree .ev, .picking #tree .origin { cursor: copy; }\n#tree .axis { fill: var(--ink-soft); font-family: var(--f-code); font-size: 10.5px; }\n#tree .tick { stroke: var(--grid); }\n.hist-foot { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; padding: 8px 10px; border-top: 1px solid var(--rule); font-size: 12px; color: var(--ink-soft); }\n.hist-foot .ahead { color: var(--kairos); }\n.empty-hist { padding: 14px 12px; display: flex; flex-wrap: wrap; align-items: center; gap: 10px; color: var(--ink-soft); }\n\n.work-bar { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; color: var(--ink-soft); }\n.work-bar b { color: var(--ink); font-weight: 600; }\n\n/* session manager */\n.manager { position: fixed; inset: 0; z-index: 20; background: rgba(18, 22, 28, 0.42); display: flex; align-items: flex-start; justify-content: center; overflow: auto; padding: calc(24px + env(safe-area-inset-top, 0px)) 16px 24px; }\n.mgr-panel { box-sizing: border-box; width: 100%; max-width: 920px; background: var(--sheet); border: 1px solid var(--rule); border-radius: 8px; box-shadow: 0 12px 40px rgba(0, 0, 0, 0.25); }\n.mgr-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 14px; padding: 16px 18px 12px; border-bottom: 1px solid var(--rule); }\n.mgr-head h2 { margin: 0; font-family: var(--f-head); font-weight: 600; font-size: 20px; }\n.mgr-sub { color: var(--ink-soft); font-size: 13px; flex: 1; min-width: 220px; }\n#mgr-body { padding: 14px 18px 18px; }\n.mgr-cols { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }\n@media (max-width: 720px) { .mgr-cols { grid-template-columns: minmax(0, 1fr); } }\n.mgr-col h3 { margin: 0; font-family: var(--f-head); font-weight: 600; font-size: 13px; letter-spacing: 0.06em; text-transform: uppercase; }\n.mgr-hint { margin: 4px 0 10px; color: var(--ink-soft); font-size: 12px; }\n.mgr-note, .mgr-empty { color: var(--ink-soft); font-size: 13px; }\n.mgr-busy { color: var(--accent); font-size: 13px; margin: 0 0 10px; }\n.mgr-foot { margin: 16px 0 0; }\n.mgr-welcome { border: 1px solid var(--rule); border-radius: 6px; padding: 10px 14px; margin: 0 0 14px; background: var(--sheet); font-size: 13px; line-height: 1.5; }\n.mgr-welcome p { margin: 6px 0; } .mgr-welcome ul { margin: 6px 0; padding-left: 18px; } .mgr-welcome li { margin: 3px 0; }\n.mgr-welcome .wt { font-family: var(--f-head); font-size: 17px; margin-top: 2px; }\n.mgr-welcome .alpha { font: 11px var(--f-code); color: var(--kairos); border: 1px solid var(--kairos); border-radius: 10px; padding: 1px 7px; margin-left: 6px; vertical-align: 2px; }\n.mgr-welcome .alpha-note { color: var(--ink-soft); }\n.mgr-welcome code { font-family: var(--f-code); font-size: 12px; }\n.items { list-style: none; margin: 0 0 12px; padding: 0; display: flex; flex-direction: column; gap: 6px; }\n.item { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 10px; padding: 8px 10px; border: 1px solid var(--rule); border-radius: 6px; background: var(--box); }\n.item.current { border-color: var(--accent); }\n.item.invited { border-color: var(--kairos); }\n.item-main { flex: 1; min-width: 160px; display: flex; flex-direction: column; gap: 2px; }\n.item-name { font-weight: 500; overflow-wrap: anywhere; }\n.item-meta { font-size: 12px; color: var(--ink-soft); }\n.item-meta b { color: var(--ok); font-weight: 500; }\n.item-acts { display: flex; flex-wrap: wrap; gap: 6px; }\nbutton.act.danger { color: var(--error); }\nbutton.act.danger.armed { background: var(--error); border-color: var(--error); color: #fff; }\n.invite { padding: 10px 12px; margin-bottom: 14px; border: 1px solid var(--kairos); border-radius: 6px; background: var(--box); }\nform.new { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }\nform.new input:not([type]) { flex: 1; min-width: 140px; font: inherit; padding: 5px 8px; border: 1px solid var(--rule); border-radius: 4px; background: var(--box); color: var(--ink); }\n/* the relays of Pages, in the session manager */\n.relays { border: 1px solid var(--rule); border-radius: 6px; padding: 8px 12px; margin: 0 0 14px; background: var(--box); font-size: 13px; }\n.relays > summary { cursor: pointer; color: var(--ink); }\n.relays .rlabel { font-family: var(--f-head); font-weight: 600; font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-soft); margin-right: 4px; }\n.relays[open] > summary { margin-bottom: 4px; }\n.rlist { list-style: none; margin: 6px 0 10px; padding: 0; display: grid; gap: 4px; }\n.rlist li { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }\n.rlist code, .relays .rtest code { font-family: var(--f-code); font-size: 12px; overflow-wrap: anywhere; }\n.rdot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--ink-soft); vertical-align: 1px; }\n.rdot.ok { background: var(--ok); } .rdot.wait { background: var(--kairos); }\n.rstate { color: var(--ink-soft); font-size: 12px; }\n.rtest { margin: 6px 0 0; font-size: 12px; color: var(--ink-soft); } .rtest.ok { color: var(--ok); } .rtest.fail { color: var(--error); }\n.rchoices { margin: 8px 0 0; display: flex; flex-wrap: wrap; gap: 6px; } .rchoices:empty { display: none; }\n.rown { margin-top: 8px; } .rown > summary { cursor: pointer; color: var(--accent); font-size: 12px; }\n.rown p { margin: 6px 0; line-height: 1.5; max-width: 72ch; }\n.rown pre { margin: 6px 0; padding: 6px 10px; background: var(--sheet); border: 1px solid var(--rule); border-radius: 4px; font: 12px var(--f-code); overflow-x: auto; }\nbutton.act.small { padding: 1px 8px; font-size: 12px; }\n\n.repl { min-height: 0; }\n#repl-out { max-height: 150px; min-height: 80px; overflow: auto; padding: 8px 12px; font-family: var(--f-code); font-size: 12.5px; line-height: 1.55; }\n#repl-out .in { color: var(--ink); }\n#repl-out .in .p { color: var(--accent); margin-right: 6px; }\n#repl-out .in.from-patch { color: var(--ink-soft); }\n#repl-out .in.from-patch .p { color: var(--kairos); }\n#repl-out .out { color: var(--ink-soft); padding-left: 20px; white-space: pre-wrap; word-break: break-word; }\n#repl-out .err { color: var(--error); padding-left: 20px; white-space: pre-wrap; }\n.repl-line { display: flex; align-items: center; gap: 8px; border-top: 1px solid var(--rule); padding: 6px 12px; }\n.repl-line label { font-family: var(--f-code); color: var(--accent); font-weight: 600; }\n#repl-in { flex: 1; min-width: 0; border: 0; background: transparent; color: var(--ink); font-family: var(--f-code); font-size: 13px; padding: 6px 0; }\n#repl-in:focus { outline: none; }\n/* the Code tab and the REPL line, with the code editor (14-editor.cljs) */\n.code-host, .data-host { flex: 1; min-height: 300px; max-height: 560px; display: flex; min-width: 0; }\n.code-host[hidden], .data-host[hidden] { display: none; }\n.data-host .cm-editor { flex: 1; min-width: 0; background: transparent !important; }\n.data-host .cm-gutters { background: transparent !important; }\n.code-host .cm-editor { flex: 1; min-width: 0; background: transparent !important; }\n.code-host .cm-gutters { background: transparent !important; }\n.repl-host { flex: 1; min-width: 0; max-height: 30vh; overflow: auto; }\n.repl-host .cm-editor { background: transparent !important; font-size: 13px; }\n.repl-host .cm-content { padding: 5px 0 !important; }\n.repl-host .cm-line { padding: 0; }\n.repl-host .cm-placeholder { color: var(--ink-soft); }\n.help { padding: 6px 12px 10px; font-size: 12px; color: var(--ink-soft); display: flex; flex-wrap: wrap; gap: 4px 14px; }\n.help code { font-family: var(--f-code); color: var(--ink); }\n/* the Room tab: talking with the people in a shared room (#135) */\n.tab.attn::after { content: \" •\"; color: var(--kairos); }\n.talk { display: flex; flex-direction: column; gap: 8px; padding: 8px 10px; min-height: 0; flex: 1; overflow: auto; }\n.talk-on { display: flex; flex-direction: column; gap: 8px; min-height: 0; flex: 1; }\n.talk-on[hidden] { display: none; }\n.talk-head { display: flex; gap: 8px; align-items: center; }\n.talk-head input { font: 13px var(--f-ui); color: var(--ink); background: var(--box); border: 1px solid var(--rule); border-radius: 6px; padding: 4px 6px; width: 11em; }\n.talk-state { font: 11.5px var(--f-code); color: var(--ink-soft); }\n.talk-state.ok { color: var(--ok); } .talk-state.bad { color: var(--error); }\n.talk-peers { display: flex; flex-wrap: wrap; gap: 5px; font: 11.5px var(--f-code); }\n.tpeer { border: 1px solid var(--rule); background: var(--sheet); border-radius: 3px; padding: 1px 6px; }\n.tpeer.p2p { border-color: var(--ok); } .tpeer.talk { border-color: var(--kairos); background: var(--accent-soft); }\n.tpeer i { font-style: normal; color: var(--ink-soft); }\n.talk-chat { flex: 1; min-height: 160px; overflow-y: auto; background: var(--sheet); border: 1px solid var(--grid); border-radius: 4px; padding: 6px; display: flex; flex-direction: column; gap: 4px; }\n.titem { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 1px 8px; padding: 3px 5px; border-radius: 4px; }\n.titem.mine { background: var(--accent-soft); }\n.twho { font: 600 12px var(--f-ui); } .twho time { font: 400 10.5px var(--f-code); color: var(--ink-soft); margin-left: 6px; }\n.twhat { grid-column: 1; font-size: 13px; line-height: 1.4; overflow-wrap: anywhere; }\n.twhat audio { display: block; height: 28px; max-width: 100%; } .twhat img { display: block; max-width: 160px; border-radius: 3px; }\n.tside { grid-row: 1 / span 2; grid-column: 2; display: flex; flex-direction: column; gap: 3px; align-items: end; }\n.tst { font: 10.5px var(--f-code); color: var(--ink-soft); } .tst.ok { color: var(--ok); } .tst.bad { color: var(--error); }\n.tchip { font: 11px var(--f-code); border: 1px solid var(--accent); color: var(--accent); border-radius: 3px; padding: 0 4px; margin-right: 3px; }\n.talk-say { display: flex; gap: 6px; }\n.talk-say input { flex: 1; font: 13px var(--f-ui); color: var(--ink); background: var(--box); border: 1px solid var(--rule); border-radius: 6px; padding: 5px 7px; }\n.talk-bar { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }\n.talk-hold { border: 2px solid var(--kairos); background: var(--box); color: var(--kairos); font: 600 12.5px var(--f-ui); padding: 5px 12px; border-radius: 999px; cursor: pointer; touch-action: none; user-select: none; -webkit-user-select: none; }\n.talk-hold[aria-pressed=\"true\"] { background: var(--kairos); color: #fff; } .talk-hold:disabled { opacity: 0.4; cursor: default; }\n#talk-cam[aria-pressed=\"true\"] { border-color: var(--kairos); }\n.talk-tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 6px; }\n.ttile { position: relative; aspect-ratio: 4 / 3; background: #000; border-radius: 4px; overflow: hidden; }\n.ttile[hidden] { display: none; } .ttile.talk { outline: 2px solid var(--kairos); }\n.ttile video { width: 100%; height: 100%; object-fit: cover; display: block; }\n.ttile .tlabel { position: absolute; left: 5px; bottom: 4px; font: 10.5px var(--f-code); color: #fff; background: rgba(0,0,0,.55); padding: 0 4px; border-radius: 3px; }\n.ttile button { position: absolute; right: 4px; top: 4px; }\n#net-bpm { width: 4.5em; font: 12.5px var(--f-code); color: var(--ink); background: var(--box); border: 1px solid var(--rule); border-radius: 6px; padding: 3px 5px; }\n.net-metro { display: inline-flex; gap: 4px; align-items: center; font-size: 12px; }\n.net-beat { font: 600 15px var(--f-code); min-width: 2.6em; text-align: center; color: var(--ink-soft); border-radius: 4px; padding: 0 4px; }\n.net-beat.on { background: var(--kairos); color: #fff; }\n.talk-asks { display: grid; gap: 6px; } .talk-asks[hidden] { display: none; }\n.task { border: 1px solid var(--kairos); border-left-width: 3px; border-radius: 6px; padding: 6px 8px; font-size: 12.5px; display: grid; gap: 4px; }\n</style>\n\n<div class=\"app\">\n <header>\n <h1><svg class=\"logo\" viewBox=\"15.2 -86.5 627.6 104.3\" role=\"img\" aria-label=\"Kairotic\"><g><path class=\"t\" d=\"M19.2 -31.1Q19.2 -38.4 20.85 -45.15Q22.5 -51.9 25.35 -57.7Q28.2 -63.5 32 -68.15Q35.8 -72.8 40 -76H50.9Q46.4 -72.8 42.4 -68.5Q38.4 -64.2 35.4 -59Q32.4 -53.8 30.6 -47.95Q28.8 -42.1 28.8 -35.7V-26.5Q28.8 -20.1 30.6 -14.25Q32.4 -8.4 35.4 -3.2Q38.4 2 42.4 6.3Q46.4 10.6 50.9 13.8H40Q35.8 10.7 32 6Q28.2 1.3 25.35 -4.5Q22.5 -10.3 20.85 -17.05Q19.2 -23.8 19.2 -31.1Z\"/><svg x=\"60\" y=\"-75\" width=\"60\" height=\"78\" viewBox=\"20 6 68 88\"><path d=\"M30 12 V88\" stroke-width=\"11\"/>\n<path d=\"M30 56 C48 56 54 26 67 20.7\" stroke-width=\"9\"/>\n<path d=\"M30 56 C48 56 56 76 75 82\" stroke-width=\"9\"/>\n<circle cx=\"76\" cy=\"17\" r=\"7.5\" stroke-width=\"4.5\"/>\n<circle cx=\"78\" cy=\"83\" r=\"7.5\" class=\"f\" stroke=\"none\"/>\n<circle cx=\"30\" cy=\"56\" r=\"11\" class=\"d\" stroke=\"none\"/></svg><path class=\"t\" d=\"M169.2 0Q164.5 0 162.15 -2.4Q159.8 -4.8 159.3 -8.7H158.8Q157.3 -4 153.35 -1.4Q149.4 1.2 143.3 1.2Q135.4 1.2 130.7 -2.95Q126 -7.1 126 -14.4Q126 -21.9 131.55 -25.85Q137.1 -29.8 148.6 -29.8H158.5V-33.8Q158.5 -44.3 147.4 -44.3Q142.4 -44.3 139.3 -42.35Q136.2 -40.4 134.1 -37.2L127.6 -42.5Q129.8 -46.7 135 -49.75Q140.2 -52.8 148.4 -52.8Q158.2 -52.8 163.8 -48.1Q169.4 -43.4 169.4 -34.5V-8.6H175.9V0ZM146.4 -6.8Q151.7 -6.8 155.1 -9.2Q158.5 -11.6 158.5 -15.4V-22.9H148.8Q137 -22.9 137 -15.8V-13.8Q137 -10.3 139.5 -8.55Q142 -6.8 146.4 -6.8Z\"/><path class=\"t\" d=\"M213.2 -61Q209 -61 207.35 -62.7Q205.7 -64.4 205.7 -66.9V-69Q205.7 -71.5 207.35 -73.2Q209 -74.9 213.1 -74.9Q217.3 -74.9 218.95 -73.2Q220.6 -71.5 220.6 -69V-66.9Q220.6 -64.4 218.95 -62.7Q217.3 -61 213.2 -61ZM190.1 -8.8H207.7V-42.8H190.1V-51.6H218.6V-8.8H235.1V0H190.1Z\"/><path class=\"t\" d=\"M247.6 -8.8H261.3V-42.8H247.6V-51.6H272.2V-37.9H272.8Q273.5 -40.6 274.8 -43.1Q276.1 -45.6 278.1 -47.45Q280.1 -49.3 283 -50.45Q285.9 -51.6 289.8 -51.6H296V-41.2H285.8Q279.8 -41.2 276 -37.65Q272.2 -34.1 272.2 -28.1V-8.8H286.9V0H247.6Z\"/><path class=\"t\" d=\"M330 1.2Q324.3 1.2 319.75 -0.7Q315.2 -2.6 312.05 -6.1Q308.9 -9.6 307.2 -14.6Q305.5 -19.6 305.5 -25.8Q305.5 -32 307.2 -37Q308.9 -42 312.05 -45.5Q315.2 -49 319.75 -50.9Q324.3 -52.8 330 -52.8Q335.7 -52.8 340.25 -50.9Q344.8 -49 347.95 -45.5Q351.1 -42 352.8 -37Q354.5 -32 354.5 -25.8Q354.5 -19.6 352.8 -14.6Q351.1 -9.6 347.95 -6.1Q344.8 -2.6 340.25 -0.7Q335.7 1.2 330 1.2ZM330 -7.4Q336 -7.4 339.55 -11.05Q343.1 -14.7 343.1 -21.9V-29.7Q343.1 -36.9 339.55 -40.55Q336 -44.2 330 -44.2Q324 -44.2 320.45 -40.55Q316.9 -36.9 316.9 -29.7V-21.9Q316.9 -14.7 320.45 -11.05Q324 -7.4 330 -7.4Z\"/><path class=\"t\" d=\"M393.1 0Q386.3 0 383.1 -3.65Q379.9 -7.3 379.9 -13.1V-42.8H364V-51.6H375.3Q378.2 -51.6 379.4 -52.75Q380.6 -53.9 380.6 -56.9V-69.8H390.8V-51.6H412.8V-42.8H390.8V-8.8H412.8V0Z\"/><path class=\"t\" d=\"M453.2 -61Q449 -61 447.35 -62.7Q445.7 -64.4 445.7 -66.9V-69Q445.7 -71.5 447.35 -73.2Q449 -74.9 453.1 -74.9Q457.3 -74.9 458.95 -73.2Q460.6 -71.5 460.6 -69V-66.9Q460.6 -64.4 458.95 -62.7Q457.3 -61 453.2 -61ZM430.1 -8.8H447.7V-42.8H430.1V-51.6H458.6V-8.8H475.1V0H430.1Z\"/><path class=\"t\" d=\"M511.9 1.2Q506.1 1.2 501.55 -0.7Q497 -2.6 493.85 -6.1Q490.7 -9.6 489.05 -14.6Q487.4 -19.6 487.4 -25.8Q487.4 -32 489.05 -37Q490.7 -42 493.85 -45.5Q497 -49 501.55 -50.9Q506.1 -52.8 511.8 -52.8Q519.8 -52.8 524.65 -49.4Q529.5 -46 531.9 -40.6L523.4 -36Q522 -39.6 519.15 -41.7Q516.3 -43.8 511.8 -43.8Q505.6 -43.8 502.2 -40.05Q498.8 -36.3 498.8 -30.1V-21.5Q498.8 -15.4 502.2 -11.6Q505.6 -7.8 512 -7.8Q516.8 -7.8 519.85 -10Q522.9 -12.2 524.7 -16L532.7 -11.1Q530.2 -5.7 525.1 -2.25Q520 1.2 511.9 1.2Z\"/><svg x=\"544\" y=\"-82.5\" width=\"50\" height=\"90\" viewBox=\"30 14 40 72\"><path d=\"M34 50 H44 M44 50 C52 50 54 33 62 32 M44 50 C52 50 54 67 62 68\" stroke-width=\"7\"/>\n<circle cx=\"44\" cy=\"50\" r=\"7.5\" class=\"d\" stroke=\"none\"/></svg><path class=\"t\" d=\"M638.8 -31.1Q638.8 -23.8 637.15 -17.05Q635.5 -10.3 632.65 -4.5Q629.8 1.3 626 6Q622.2 10.7 618 13.8H607.1Q611.6 10.6 615.6 6.3Q619.6 2 622.6 -3.2Q625.6 -8.4 627.4 -14.25Q629.2 -20.1 629.2 -26.5V-35.7Q629.2 -42.1 627.4 -47.95Q625.6 -53.8 622.6 -59Q619.6 -64.2 615.6 -68.5Q611.6 -72.8 607.1 -76H618Q622.2 -72.8 626 -68.15Q629.8 -63.5 632.65 -57.7Q635.5 -51.9 637.15 -45.15Q638.8 -38.4 638.8 -31.1Z\"/></g></svg></h1>\n <span class=\"sub\" id=\"edition\">0.2.0-alpha · a collaborative patcher of music where the patch and its code are one work, with its whole history · <a href=\"https://github.com/bonuoq/kairotic/blob/main/docs/README.md\" target=\"_blank\" rel=\"noopener\">docs</a></span>\n <span class=\"status\" id=\"status\">loading ClojureScript…</span>\n <span class=\"work-bar\"><span id=\"work-name\">No work open</span><button class=\"act\" id=\"open-manager\">Sessions</button></span>\n </header>\n\n <input type=\"file\" id=\"kfile-in\" accept=\".kairotic,application/zip\" hidden>\n <div class=\"manager\" id=\"manager\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"mgr-title\">\n <div class=\"mgr-panel\">\n <div class=\"mgr-head\">\n <h2 id=\"mgr-title\">Sessions</h2>\n <span class=\"mgr-sub\">Work solo or share a room. You can move from one to the other by copying the work with its history.</span>\n <button class=\"act\" id=\"mgr-close\" title=\"Back to the open work, or start locally (Esc)\">Close</button>\n </div>\n <div id=\"mgr-body\"><p class=\"mgr-note\">Loading…</p></div>\n </div>\n </div>\n\n <div class=\"work\">\n <section class=\"pane\" aria-label=\"Patch\">\n <div class=\"pane-head\">\n <span class=\"label\">Patch</span>\n <span id=\"crumbs\" class=\"crumbs\"></span>\n <span class=\"transport\">\n <button class=\"act\" id=\"play\" title=\"Start the engine and fire the loadbang boxes (space)\">▶</button>\n <button class=\"act\" id=\"stop\" title=\"Stop the engine: silence and initial state\">■</button>\n <span id=\"transport-info\">engine stopped</span>\n <button class=\"act\" id=\"pres-toggle\" title=\"Presentation: only the presented boxes, where the performer sees them (with boxes selected, it offers to present them where they are)\">Present</button>\n <button class=\"act\" id=\"perform-toggle\" title=\"Perform: rehearse, try and improvise outside the history\">Perform</button>\n <button class=\"act\" id=\"learn-toggle\" title=\"Learn: select a box, press Learn and move a controller (MIDI, a gamepad, the phone's tilt, OSC): it is wired to the box\">Learn</button>\n <button class=\"act\" id=\"annot-toggle\" title=\"Annotate: draw lines, arrows and texts on a layer of the patch, anchored to the boxes nearest them\">Annotate</button>\n <span id=\"perform-info\" class=\"perform-info\" hidden></span>\n <button class=\"act\" id=\"embed-btn\" title=\"Share or export this patch (or this tutorial step): a link, or an iframe to put it in another page\">Share/Export</button>\n <button class=\"act embed-only\" id=\"fs-btn\" title=\"Fullscreen\">⛶</button>\n <a class=\"act embed-only\" id=\"open-full\" target=\"_blank\" rel=\"noopener\" title=\"Open it in Kairotic, with the whole editor\">Kairotic ↗</a>\n </span>\n <span class=\"hint\">Messages travel without ▶ (▶: sound and time) · ⌘/Ctrl+click a box to edit it below: its arguments and its text (Enter applies) · ⇧+click or a frame drawn on the paper selects several: drag them together, Delete removes them, ⌘/Ctrl+A selects all · playable boxes (bang, msg, number, knobs…) are selected by their left grip; their body only plays · Code boxes: double-click their code row to open the editor (a window you can move; Ctrl/⌘+Enter applies) · their sliders can be dragged · Canvas: drag = stroke, ⇧ straight, ⌥ freehand, click = position</span>\n </div>\n <div class=\"line-tabs\" id=\"line-tabs\" role=\"tablist\" aria-label=\"The lines of this work\" hidden></div>\n <div class=\"embed-pop\" id=\"embed-pop\" hidden>\n <div class=\"ep-head\">\n <b>Share/Export</b>\n <span class=\"spacer\"></span>\n <button class=\"act\" id=\"ep-close\">Close</button>\n </div>\n <div class=\"ep-file\" id=\"ep-file\">\n <span class=\"ep-l\">The work as a file (<code>.kairotic</code>): every line, its whole history, the sounds recorded</span>\n <span class=\"ep-row\">\n <button class=\"act primary\" data-kfile=\"history\" title=\"To keep it, or to open it in another Kairotic (Pages ⇄ claude.ai): Sessions → Open a file\">Download the work</button>\n <button class=\"act\" data-kfile=\"release\" title=\"One line, one point per keyframe: as a release is\">Download a release</button>\n <label class=\"ep-l\"><input type=\"checkbox\" id=\"ep-anon\"> anonymous</label>\n </span>\n </div>\n <div class=\"ep-head\">\n <b>A link</b>\n <span class=\"ep-modes\">\n <label><input type=\"radio\" name=\"ep-mode\" value=\"embed\" checked> Patch</label>\n <label><input type=\"radio\" name=\"ep-mode\" value=\"present\" title=\"A release of the patch (presets boxes keep their presets), opened in Perform: what is played there is a take, never the work\"> Release/Perform</label>\n </span>\n </div>\n <p class=\"ep-what\" id=\"ep-what\"></p>\n <label class=\"ep-l\"><input type=\"checkbox\" id=\"ep-ask\"> Carry a description instead: whoever opens it makes the patch with Claude (their own key or account)</label>\n <div class=\"ep-row\" id=\"ep-ask-row\" hidden><input id=\"ep-ask-text\" spellcheck=\"true\" placeholder=\"a sine at 440 Hz with a volume knob, and a knob that does FM synthesis\"></div>\n <label class=\"ep-l\">Link <small>(in Notion: type <code>/embed</code> and paste it)</small></label>\n <div class=\"ep-row\"><input id=\"ep-url\" readonly spellcheck=\"false\"><button class=\"act\" data-copy=\"ep-url\">Copy</button></div>\n <label class=\"ep-l\">iframe <small>(any page or blog)</small></label>\n <div class=\"ep-row\"><textarea id=\"ep-iframe\" readonly spellcheck=\"false\" rows=\"3\"></textarea><button class=\"act\" data-copy=\"ep-iframe\">Copy</button></div>\n <p class=\"ep-note\">The link carries the patch itself (its code, compressed): it is a copy of this moment, not a live work. Whoever opens it plays it in their browser, without saving anything; “Kairotic ↗” opens it with the whole editor.</p>\n </div>\n <div class=\"askbar\" id=\"askbar\" hidden>\n <div class=\"ab-q\"><b>Claude</b> · <span id=\"ab-text\"></span></div>\n <div class=\"ab-row\" id=\"ab-keyrow\" hidden>\n <input type=\"password\" id=\"ab-key\" autocomplete=\"off\" spellcheck=\"false\" placeholder=\"Your Anthropic API key (sk-ant-…)\" aria-label=\"Anthropic API key\">\n <button class=\"act\" id=\"ab-key-save\">Save</button>\n </div>\n <div class=\"ab-row\">\n <button class=\"act primary\" id=\"ab-go\">Make it with Claude</button>\n <button class=\"act\" id=\"ab-fix\" hidden title=\"A link with this result in it: everyone sees the same patch, and nobody spends anything\">Copy the link of this result</button>\n <button class=\"act\" id=\"ab-hide\" title=\"Hide this bar\">✕</button>\n <span class=\"ab-status\" id=\"ab-status\"></span>\n </div>\n <p class=\"ab-note\" id=\"ab-note\"></p>\n </div>\n <div class=\"trust-bar\" id=\"trust-bar\" hidden><span id=\"trust-text\"></span> <button class=\"act\" id=\"trust-run\">Run them</button></div>\n <div class=\"lesson\" id=\"lesson\" hidden>\n <div class=\"lesson-head\">\n <span class=\"t\" id=\"lesson-title\"></span>\n <span class=\"n\" id=\"lesson-n\"></span>\n <button class=\"act\" id=\"lesson-prev\" title=\"Previous step\">◀</button>\n <button class=\"act\" id=\"lesson-next\" title=\"Next step\">▶</button>\n <span class=\"spacer\"></span>\n <span class=\"lang\"><button class=\"act\" data-lang=\"es\">ES</button> <button class=\"act\" data-lang=\"en\">EN</button></span>\n <button class=\"act\" id=\"lesson-back\" title=\"Close the lesson and go back to what you had open\">Close</button>\n </div>\n <div class=\"lesson-note\" id=\"lesson-note\"></div>\n </div>\n <div class=\"annot-bar\" id=\"annot-bar\" hidden>\n <span class=\"annot-tools\" role=\"group\" aria-label=\"Annotation tool\">\n <button class=\"act\" data-atool=\"draw\" title=\"Draw a line by hand\">Draw</button>\n <button class=\"act\" data-atool=\"arrow\" title=\"An arrow, from where you press to where you let go\">Arrow</button>\n <button class=\"act\" data-atool=\"text\" title=\"Click where the text goes\">Text</button>\n <button class=\"act\" data-atool=\"move\" title=\"Drag a mark to move it (its points keep their anchors); drag one end of a line or an arrow to move only that end\">Move</button>\n <button class=\"act\" data-atool=\"erase\" title=\"Click or drag over marks to erase them\">Erase</button>\n </span>\n <input id=\"annot-text\" placeholder=\"text for Text\" spellcheck=\"true\" aria-label=\"Text of the next text mark\">\n <label class=\"annot-l\">layer <input id=\"annot-layer\" list=\"annot-layers\" spellcheck=\"false\" aria-label=\"Layer\"></label>\n <datalist id=\"annot-layers\"></datalist>\n <button class=\"act\" id=\"annot-z\" title=\"Over or under the boxes\">over</button>\n <label class=\"annot-l\"><input type=\"checkbox\" id=\"annot-show-patch\"> patch</label>\n <label class=\"annot-l\"><input type=\"checkbox\" id=\"annot-show-present\"> presentation</label>\n <span class=\"spacer\"></span>\n <button class=\"act\" id=\"annot-done\">Done</button>\n </div>\n <div class=\"canvas-wrap\" id=\"canvas-wrap\">\n <svg id=\"canvas\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <pattern id=\"grid\" width=\"20\" height=\"20\" patternUnits=\"userSpaceOnUse\">\n <circle cx=\"1\" cy=\"1\" r=\"1\" fill=\"var(--grid)\"></circle>\n </pattern>\n </defs>\n <rect class=\"bg\" x=\"0\" y=\"0\" width=\"100%\" height=\"100%\"></rect>\n <g id=\"layers-under\"></g>\n <g id=\"scene\"></g>\n <g id=\"cursors\"></g>\n <g id=\"layers-over\"></g>\n </svg>\n </div>\n </section>\n\n <div class=\"splitter\" id=\"side-split\" role=\"separator\" aria-orientation=\"vertical\" aria-controls=\"side-pane\" title=\"Drag to resize the panel · double-click to hide or show it\">\n <button class=\"side-toggle\" id=\"side-toggle\" type=\"button\" aria-expanded=\"true\" title=\"Hide the panel\">›</button>\n </div>\n\n <section class=\"pane side-pane\" id=\"side-pane\" aria-label=\"Projections\">\n <div class=\"pane-head\">\n <div class=\"tabs\" role=\"tablist\">\n <button class=\"tab\" role=\"tab\" id=\"tab-code\" data-tab=\"code\" aria-selected=\"true\">Code</button>\n <button class=\"tab\" role=\"tab\" id=\"tab-comp\" data-tab=\"comp\" aria-selected=\"false\">Components</button>\n <button class=\"tab\" role=\"tab\" id=\"tab-claude\" data-tab=\"claude\" aria-selected=\"false\" hidden>Claude</button>\n <button class=\"tab\" role=\"tab\" id=\"tab-help\" data-tab=\"help\" aria-selected=\"false\" title=\"How each component works, and tutorials (? on a selected box)\">Help</button>\n <button class=\"tab\" role=\"tab\" id=\"tab-talk\" data-tab=\"talk\" aria-selected=\"false\" title=\"Talk with the people in this room: write, hold to talk, voice notes, camera\">Room</button>\n <button class=\"tab\" role=\"tab\" id=\"tab-feedback\" data-tab=\"feedback\" aria-selected=\"false\" title=\"Report a bug, propose an idea or ask a question (on GitHub)\">Feedback</button>\n </div>\n <button class=\"side-hide\" id=\"side-hide\" type=\"button\" title=\"Hide the panel (it comes back with ‹, with help, or with (side-panel true))\">»</button>\n </div>\n <div class=\"panel\" id=\"panel-code\">\n <textarea id=\"code\" spellcheck=\"false\" aria-label=\"Patch code\"></textarea>\n <pre class=\"view\" id=\"edn\" aria-label=\"The work as data (EDN)\" hidden></pre>\n <div class=\"code-bar\">\n <span class=\"code-views\" role=\"group\" aria-label=\"Show the work as\">\n <button class=\"act\" type=\"button\" id=\"view-calls\" aria-pressed=\"true\" title=\"The work as calls (box, connect, …): edit it and run it\">Calls</button><button class=\"act\" type=\"button\" id=\"view-data\" aria-pressed=\"false\" title=\"The work as data (EDN): the state the history produces, to read\">Data</button>\n </span>\n <span class=\"state\" id=\"code-state\">in sync with the patch</span>\n <span class=\"spacer\"></span>\n <button class=\"act\" id=\"code-revert\" disabled>Discard changes</button>\n <button class=\"act primary\" id=\"code-run\" disabled>Run · Ctrl+Enter</button>\n </div>\n </div>\n <div class=\"panel\" id=\"panel-comp\" hidden>\n <div class=\"comp-list\" id=\"comp-list\"></div>\n </div>\n <div class=\"panel\" id=\"panel-feedback\" hidden>\n <div class=\"fb\">\n <p class=\"ask-note\">Kairotic is in <b>alpha</b>: tell us what fails and what you miss. This writes a GitHub issue for you (with what you choose to add below); it is published only when you press the button on GitHub, under your own account. Nothing is sent from here, and never your API key.</p>\n <div class=\"fb-kind\" role=\"radiogroup\" aria-label=\"Kind\">\n <label><input type=\"radio\" name=\"fb-kind\" value=\"bug\" checked> Something fails</label>\n <label><input type=\"radio\" name=\"fb-kind\" value=\"idea\"> An idea for the next version</label>\n <label><input type=\"radio\" name=\"fb-kind\" value=\"question\"> A question</label>\n </div>\n <input id=\"fb-title\" spellcheck=\"true\" placeholder=\"A short title\">\n <textarea id=\"fb-text\" spellcheck=\"true\"></textarea>\n <div class=\"fb-opts\">\n <label><input type=\"checkbox\" id=\"fb-patch\" checked> the patch on screen (as a link)</label>\n <label><input type=\"checkbox\" id=\"fb-errors\" checked> recent errors <span id=\"fb-errn\"></span></label>\n <label><input type=\"checkbox\" id=\"fb-env\" checked> version and browser</label>\n </div>\n <div class=\"ask-bar\">\n <span class=\"spacer\"></span>\n <button class=\"act\" id=\"fb-copy\" title=\"The text, to paste wherever you like\">Copy</button>\n <button class=\"act primary\" id=\"fb-go\">Write it on GitHub…</button>\n </div>\n <details class=\"fb-prev\"><summary>What will be written</summary><pre id=\"fb-preview\"></pre></details>\n <h4>Open issues</h4>\n <p class=\"ask-note\">Before writing, see if it is already here: a 👍 or a comment there helps as much.</p>\n <ol class=\"fb-list\" id=\"fb-list\"><li class=\"soft\">…</li></ol>\n </div>\n </div>\n <div class=\"panel\" id=\"panel-talk\" hidden>\n <div class=\"talk\">\n <p class=\"ask-note\" id=\"talk-off\"></p>\n <div class=\"talk-on\" id=\"talk-on\" hidden>\n <div class=\"talk-head\">\n <input id=\"talk-name\" spellcheck=\"false\" aria-label=\"Your name in the room\" maxlength=\"60\">\n <span class=\"talk-state\" id=\"talk-state\"></span>\n </div>\n <div class=\"talk-peers\" id=\"talk-peers\"></div>\n <div class=\"talk-asks\" id=\"talk-asks\" hidden></div>\n <div class=\"talk-chat\" id=\"talk-chat\" aria-live=\"polite\"></div>\n <div class=\"talk-say\">\n <input id=\"talk-say\" spellcheck=\"true\" maxlength=\"2000\" aria-label=\"Message\" placeholder=\"say something — @b3 #12 ^33 anchor it\">\n <button class=\"act\" id=\"talk-send\">Send</button>\n </div>\n <div class=\"talk-bar\">\n <button class=\"act\" id=\"talk-mic\" title=\"Ask for the microphone: then hold to talk, or to record a voice note\">Microphone</button>\n <button class=\"talk-hold\" id=\"talk-ptt\" disabled aria-pressed=\"false\" title=\"Your voice goes to the room only while you hold\">Hold to talk</button>\n <button class=\"talk-hold\" id=\"talk-note\" disabled aria-pressed=\"false\" title=\"Hold to record, let go to send\">● Note</button>\n <button class=\"act\" id=\"talk-cam\" aria-pressed=\"false\" title=\"Your camera, small and silent, to the room\">Camera</button>\n </div>\n <div class=\"talk-bar\" title=\"One tempo for the whole room: the same beat on every page (pulse boxes follow it)\">\n <span class=\"label\">Tempo</span>\n <input id=\"net-bpm\" type=\"number\" min=\"20\" max=\"400\" value=\"96\" aria-label=\"Beats per minute\">\n <button class=\"act small\" id=\"net-start\">Start for everyone</button>\n <button class=\"act small\" id=\"net-stop\">Stop</button>\n <label class=\"net-metro\"><input type=\"checkbox\" id=\"net-metro\"> metronome</label>\n <span class=\"net-beat\" id=\"net-beat\" aria-live=\"off\">·</span>\n <span class=\"talk-state\" id=\"net-clock\"></span>\n </div>\n <div class=\"talk-tiles\" id=\"talk-tiles\"></div>\n </div>\n </div>\n </div>\n <div class=\"panel\" id=\"panel-help\" hidden>\n <div class=\"help-view\" id=\"help-view\"></div>\n </div>\n <div class=\"panel\" id=\"panel-claude\" hidden>\n <div class=\"ask\">\n <div class=\"ask-what\" role=\"radiogroup\" aria-label=\"What Claude makes\">\n <label><input type=\"radio\" name=\"ask-what\" value=\"patch\" checked> A patch</label>\n <label><input type=\"radio\" name=\"ask-what\" value=\"component\"> A component</label>\n </div>\n <p class=\"ask-note\" id=\"ask-note\">Describe a patch and Claude makes it — or changes the open one — checks it and loads it as one event of the history. It uses <b>your own</b> Claude account: the first time, Claude asks you to allow this page.</p>\n <div class=\"ask-key\" id=\"ask-key\" hidden>\n <input type=\"password\" id=\"ask-key-in\" autocomplete=\"off\" spellcheck=\"false\" placeholder=\"Your Anthropic API key (sk-ant-…)\" aria-label=\"Anthropic API key\">\n <button class=\"act\" id=\"ask-key-save\">Save</button>\n <button class=\"act\" id=\"ask-key-forget\">Forget</button>\n <span class=\"ask-key-state\" id=\"ask-key-state\"></span>\n </div>\n <textarea id=\"ask-text\" spellcheck=\"true\" placeholder=\"A stereo chorus in Faust with rate and depth knobs on its panel… · a resonant filter whose cutoff follows an envelope… · a Markov chain of pitch classes…\"></textarea>\n <div class=\"ask-bar\">\n <select id=\"ask-tier\" aria-label=\"Model\"><option value=\"default\">Balanced</option><option value=\"complex\">Most capable</option><option value=\"quick\">Quick</option></select>\n <label class=\"opt\" id=\"ask-change-l\"><input type=\"checkbox\" id=\"ask-change\" checked> <span id=\"ask-change-t\">change the open patch</span></label>\n <span class=\"spacer\"></span>\n <button class=\"act\" id=\"ask-stop\" disabled>Stop</button>\n <button class=\"act primary\" id=\"ask-go\">Make it</button>\n </div>\n <ol class=\"ask-log\" id=\"ask-log\"></ol>\n <details class=\"ask-hist\" id=\"ask-hist\">\n <summary>Your requests to Claude <span id=\"ask-hist-n\"></span></summary>\n <p class=\"ask-note\">Kept only in this browser: what you asked, what Claude answered, and whether it worked. Nothing leaves it unless you share an entry (in the <a href=\"https://github.com/bonuoq/kairotic/discussions/categories/gallery\" target=\"_blank\" rel=\"noopener\">Gallery</a> on GitHub, under your own account) or export them. <button class=\"act\" id=\"ask-hist-export\">Export (.jsonl)</button> <button class=\"act\" id=\"ask-hist-clear\">Clear</button></p>\n <ol class=\"ask-hist-list\" id=\"ask-hist-list\"></ol>\n </details>\n <pre class=\"ask-out\" id=\"ask-out\"></pre>\n </div>\n </div>\n </section>\n </div>\n\n <section class=\"pane\" aria-label=\"History\">\n <div class=\"pane-head\">\n <span class=\"label\">History</span>\n <div class=\"hist-nav\">\n <button class=\"act\" id=\"nav-back\" title=\"Back one event (Ctrl+Z)\">◀</button>\n <button class=\"act\" id=\"nav-fwd\" title=\"Forward one event\">▶</button>\n <button class=\"act\" id=\"nav-tip\" title=\"Go to the tip of this branch\">⇥</button>\n </div>\n <button class=\"act\" id=\"snap-btn\" title=\"Snapshot: a keyframe in the history with the work as it is now (also in Perform)\">◆ Snapshot</button>\n <label class=\"opt\" title=\"Move forward automatically with anyone's gestures\"><input type=\"checkbox\" id=\"auto\" checked> Follow the front</label>\n <label class=\"opt\" title=\"Two gestures closer than this interval are considered parallel and branch\">Simultaneity <input type=\"number\" id=\"simul\" min=\"0\" max=\"10000\" step=\"100\" value=\"1500\"> ms</label>\n <button class=\"act\" id=\"merge-btn\" title=\"Bring here the events of another compatible branch\">Merge…</button>\n <button class=\"act\" id=\"release-btn\" title=\"Release: a new work with a compact history (only the keyframes, and the work as it is), ready to share\">Release…</button>\n <button class=\"act\" id=\"forget-btn\" title=\"Forget the points chosen with ⇧+click (solo and local works)\" hidden>Forget…</button>\n <div class=\"peers\" id=\"peers\"></div>\n <span class=\"hint\" id=\"hist-hint\">Click a point to travel to that moment · ⇧+click to choose it to forget</span>\n </div>\n <div class=\"hist-wrap\" id=\"hist-wrap\">\n <svg id=\"tree\" xmlns=\"http://www.w3.org/2000/svg\" width=\"320\" height=\"80\"></svg>\n <div class=\"empty-hist\" id=\"hist-empty\" hidden>\n <span>The history is empty: the first gesture creates its root.</span>\n <button class=\"act primary\" id=\"start-example\">Start with the example work</button>\n </div>\n </div>\n <div class=\"hist-foot\" id=\"hist-foot\"></div>\n </section>\n\n <section class=\"pane repl\" aria-label=\"REPL\">\n <div class=\"pane-head\"><span class=\"label\">REPL</span><span class=\"hint\">ClojureScript (Scittle) · ↑ ↓ history</span></div>\n <div id=\"repl-out\" aria-live=\"polite\"></div>\n <div class=\"repl-line\">\n <label for=\"repl-in\">λ</label>\n <input id=\"repl-in\" autocomplete=\"off\" spellcheck=\"false\" placeholder='(add-package! \"@kairotic/controls\") · (publish :b5) · (help \"knob\")'>\n </div>\n <div class=\"help\">\n <span><code>(stroke :b1 [[t hz] …])</code> · <code>(note :b1 t \"c4\" dur)</code> · <code>(degree :b1 t n dur)</code> · <code>(melody :b1 \"c4/1 e4/.5\")</code></span>\n <span><code>(move-stroke :b1 :t1 dt cents)</code> · <code>(stretch :b1 :t1 2)</code> · <code>(erase-stroke :b1 :t1)</code> · <code>(clear :b1)</code></span>\n <span><code>(grid-x :b1 0.25 \"3+3+2\")</code> · <code>(tuning :b1 \"31-tet\" 261.63)</code> · <code>(tunings)</code> · <code>(read-at :b1 2)</code></span>\n <span><code>(play)</code> · <code>(stop)</code> · <code>(send! :b5 2.5)</code></span>\n <span><code>(components)</code> · <code>(help \"ramp\")</code> · <code>(code :b6 \"process = …;\")</code> · <code>(source :b6)</code> · <code>(compilation :b6)</code> · <code>(trust-scripts true)</code></span>\n <span>code boxes: <code>faust~</code> (Faust, AudioWorklet) · <code>script [inlets] [outlets]</code> (ClojureScript: <code>(fn [m] {:out [[0 …]]})</code>) · <code>component</code> (defines a class: <code>{:class \"x\" :io [1 1] :receive (fn [m] …)}</code>)</span>\n <span><code>(import! \"kairotic/packages/controls.mjs\")</code> · <code>(import! \"npm:package@1.0.0/comp.mjs\")</code> · <code>(publish :b5)</code> · <code>(library)</code> · <code>(use! \"my-class\")</code></span>\n <span>sub-patches: <code>patch [name]</code> (double-click to open, ⌥ double-click to rename) · inside: <code>inlet</code> <code>outlet</code> <code>inlet~</code> <code>outlet~</code> · <code>(enter :b5)</code> · <code>(up)</code> · <code>(top)</code> · <code>(inside :b5 (box …) (connect …))</code> · <code>(abstract :b5 \"voice\")</code> · abstractions take <code>$1 $2</code></span>\n <span>canvas (any data): <code>(axis :b6 :y -1 1)</code> · <code>(axis :b6 :x 20 20000 :log)</code> · <code>(grid-y :b6 0.25)</code> · <code>reader y</code> reads along Y · <code>(read-at :b6 :y 0.5)</code> · freqt: frequency over time, with tunings · audio: <code>dac~ 1 2</code> (one inlet per channel) · <code>pan~ [pos]</code> · <code>space~ [x y]</code></span>\n <span>signal: <code>phasor~ [hz]</code> · <code>reader~ [x|y|path] [voices] [gate]</code> (position signal 0…1 on the left, buffer on the right; a voice keeps its last value where nothing passes; <code>gate</code> adds one outlet per voice, 1 where it sounds, 0 where not) · <code>sig~ [value]</code> · <code>osc~</code> and <code>gain~</code> take a signal on their frequency / factor · trajectories: <code>reader path [stroke]</code> (0…1 along a stroke → [x y])</span>\n <span>Claude: the <b>Claude</b> tab, or <code>(ask-component \"a slow LFO with its waveform drawn\")</code> · with a component chosen in the Components tab, “change the selected component” · it uses your own Claude account</span>\n <span>packages: writing a class of an official package brings the package into the work, as one component box pinned to its version · <code>@kairotic/synth</code>: <code>adsr~ [a d s r]</code>, <code>synth~</code> · <code>@kairotic/spatial</code>: <code>pan~ [pos]</code>, <code>space~ [x y]</code> · <code>@kairotic/analysis</code>: <code>pitch~</code>, <code>onset~</code>, <code>chroma~</code>, <code>features~</code>, <code>spectrum~</code> · <code>(packages)</code> · <code>(add-package! \"@kairotic/synth\")</code> · a component uses the core through <code>api/…</code> (<code>api/clamp</code>, <code>api/worklet-node</code>…)</span>\n <span>annotations (Annotate, above the patch): <code>(mark :notes {:kind :arrow :pts [[:b1 120 10] [:b4 -6 10]]})</code> · <code>(mark :notes {:kind :text :at [:patch 300 40] :txt \"…\"})</code> (points anchored to a box, <code>[:bN dx dy]</code>, or to the paper) · <code>(move-mark :a1 20 0)</code> · <code>(unmark :a1)</code> · <code>(layer :notes {:z :under :show #{:present}})</code> · <code>(project :b9 :viz [40 40 800 480])</code> · <code>(annotate :arrow)</code> · drawing: <code>draw [w h]</code> (shapes from messages: <code>msg circle 40 40 10 accent hit sun</code>) · theory: <code>pcclock</code> <code>fourier</code> <code>tonnetz</code> <code>euclid</code> (<code>@kairotic/theory</code>) · data: <code>fetch</code> (a URL, kept in the work) <code>edn</code> (any value as a tree) (<code>@kairotic/data</code>)</span>\n <span>presentation: <code>(present :b4 x y)</code> · <code>(present :b4)</code> · <code>(present-in-place :b3 :b4)</code> · <code>(resize :b3 640 300)</code> · <code>(side-panel false)</code> · <code>(release)</code> · <code>(forget-points [[\"id\" 3]])</code> · <code>(store-presets! :b18)</code> · <code>(unpresent :b4)</code> · <code>(presentation true)</code> · a sub-patch with presented boxes is a panel of them · <code>(send-to! :b7.b4 0.5)</code></span>\n <span><code>(box \"text\" x y)</code></span>\n <span><code>(connect :b1 0 :b2 0)</code></span>\n <span><code>(disconnect :b1 0 :b2 0)</code></span>\n <span><code>(move :b1 x y)</code></span>\n <span><code>(text! :b1 \"text\")</code></span>\n <span><code>(delete :b1)</code></span>\n <span><code>(rewind)</code> · <code>(rewind n)</code></span>\n <span><code>(forward)</code></span>\n <span><code>(tip)</code></span>\n <span><code>(goto \"id\" n)</code></span>\n <span><code>(here)</code></span>\n <span><code>(branches)</code></span>\n <span><code>(front true)</code></span>\n <span><code>(simultaneity 1500)</code></span>\n <span><code>(merge-from \"id\" n)</code></span>\n </div>\n </section>\n</div>\n\n<script src=\"https://cdn.jsdelivr.net/npm/scittle@0.7.30/dist/scittle.js\" type=\"application/javascript\"></script>\n<script>\n// If the ClojureScript fails to load, the error is shown in the header instead of getting lost in the console.\nwindow.addEventListener(\"error\", function (e) {\n var st = document.getElementById(\"status\");\n var msg = \"Error: \" + (e.message || e.error);\n if (st) { st.textContent = msg; st.style.color = \"var(--error)\"; }\n var mb = document.getElementById(\"mgr-body\");\n if (mb && /Loading/.test(mb.textContent)) { mb.textContent = msg; mb.style.color = \"var(--error)\"; }\n});\n</script>\n<script>\n// Links that carry a patch (Study 22): its code, deflated (when the browser can) and in base64url.\n// \"z…\" is deflate-raw, \"t…\" plain text.\n(function () {\n function toB64(bytes) {\n var bin = \"\";\n for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);\n return btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n }\n function fromB64(s) {\n var b = s.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (b.length % 4) b += \"=\";\n var bin = atob(b), bytes = new Uint8Array(bin.length);\n for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);\n return bytes;\n }\n function through(bytes, stream) {\n return new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer().then(function (b) { return new Uint8Array(b); });\n }\n window.kairoticPack = function (text) {\n var bytes = new TextEncoder().encode(text);\n if (!window.CompressionStream) return Promise.resolve(\"t\" + toB64(bytes));\n return through(bytes, new CompressionStream(\"deflate-raw\")).then(function (z) { return \"z\" + toB64(z); });\n };\n window.kairoticUnpack = function (s) {\n return Promise.resolve().then(function () {\n var bytes = fromB64(String(s).slice(1));\n if (s[0] === \"t\") return bytes;\n if (s[0] !== \"z\") throw new Error(\"this link does not carry a patch\");\n if (!window.DecompressionStream) throw new Error(\"this browser cannot open compressed links\");\n return through(bytes, new DecompressionStream(\"deflate-raw\"));\n }).then(function (bytes) { return new TextDecoder().decode(bytes); });\n };\n})();\n</script>\n<script>\n// Verovio (notation) is downloaded after the page is painted; the toolkit is kept in a promise.\nwindow.kairoticVerovio = new Promise(function (resolve, reject) {\n var s = document.createElement(\"script\");\n s.src = \"https://cdn.jsdelivr.net/npm/verovio@5.7.0/dist/verovio-toolkit-wasm.js\";\n s.onload = function () {\n try {\n var m = verovio.module;\n if (m.calledRun) { resolve(new verovio.toolkit()); }\n else { m.onRuntimeInitialized = function () { resolve(new verovio.toolkit()); }; }\n } catch (e) { reject(e); }\n };\n s.onerror = function () { reject(new Error(\"Could not download Verovio\")); };\n document.head.appendChild(s);\n});\n</script>\n<script>\n// The ClojureScript is evaluated here (and not with Scittle's automatic tags) so that an error\n// arrives with its message: first the modules, then the page's program.\n// Faust (a WebAssembly compiler, about 8 MB) is only downloaded when a faust~ box asks for it.\n// A published component is a JavaScript module that exports {class, version, author, license, doc, source}:\n// inside claude.ai only npm modules via jsDelivr (or files of this page) can be loaded.\nwindow.kairoticImport = function (url) {\n return import(new URL(url, document.baseURI).href).then(function (m) { return m.default; });\n};\nwindow.kairoticLoadFaust = function () {\n return import(\"https://cdn.jsdelivr.net/npm/@grame/faustwasm@0.18.5/dist/esm-bundle/index.js\")\n .then(function (F) {\n return F.instantiateFaustModule().then(function (mod) {\n return { F: F, compiler: new F.FaustCompiler(new F.LibFaust(mod)) };\n });\n });\n};\nwindow.addEventListener(\"DOMContentLoaded\", function () {\n function show(e) {\n var msg = \"Error: \" + ((e && e.message) || e);\n var st = document.getElementById(\"status\");\n if (st) { st.textContent = msg; st.style.color = \"var(--error)\"; }\n var mb = document.getElementById(\"mgr-body\");\n if (mb && /Loading/.test(mb.textContent)) { mb.textContent = msg; mb.style.color = \"var(--error)\"; }\n console.error(e);\n }\n // dependency order: shapes has no dependencies; components needs canvas; code, faust and library need components\n var mods = [\"kairotic/score.cljs\", \"kairotic/canvas.cljs\", \"kairotic/spell.cljs\", \"kairotic/mt.cljs\", \"kairotic/tempo.cljs\", \"kairotic/structure.cljs\", \"kairotic/quantize.cljs\", \"kairotic/treecanvas.cljs\", \"kairotic/shapes.cljs\", \"kairotic/span.cljs\", \"kairotic/components.cljs\",\n \"kairotic/code.cljs\", \"kairotic/patterns.cljs\", \"kairotic/api.cljs\", \"kairotic/corefns.cljs\", \"kairotic/mtboxes.cljs\", \"kairotic/hiccup.cljs\", \"kairotic/faust.cljs\", \"kairotic/library.cljs\", \"kairotic/help.cljs\", \"kairotic/assistant.cljs\", \"kairotic/engine.cljs\",\n \"kairotic/sounds.cljs\", \"kairotic/talk.cljs\", \"kairotic/ringaudio.cljs\", \"kairotic/signal.cljs\", \"kairotic/input.cljs\", \"kairotic/record.cljs\", \"kairotic/ring.cljs\", \"kairotic/links.cljs\", \"kairotic/release.cljs\", \"kairotic/presets.cljs\"];\n var page = [\"page/00-work.cljs\", \"page/01-commands.cljs\", \"page/02-patch-view.cljs\", \"page/03-history-view.cljs\", \"page/04-panels.cljs\", \"page/05-gestures.cljs\", \"page/19-html.cljs\", \"page/06-connection.cljs\", \"page/07-claude.cljs\", \"page/08-sessions.cljs\", \"page/09-learn.cljs\", \"page/10-embed.cljs\", \"page/11-startup.cljs\", \"page/12-feedback.cljs\", \"page/13-perform.cljs\", \"page/14-editor.cljs\", \"page/15-presets.cljs\", \"page/16-release.cljs\", \"page/17-sounds.cljs\", \"page/18-lines.cljs\", \"page/19-files.cljs\", \"page/20-talk.cljs\", \"page/21-net.cljs\", \"page/22-learn.cljs\", \"page/23-ids.cljs\", \"page/24-clipboard.cljs\", \"page/25-tidy.cljs\", \"page/26-probes.cljs\"];\n Promise.all(mods.map(function (m) {\n return fetch(m, { cache: \"no-cache\" }).then(function (r) { if (!r.ok) throw new Error(\"could not read \" + m + \" (\" + r.status + \")\"); return r.text(); });\n }))\n .then(function (srcs) {\n srcs.forEach(function (src, i) {\n try { scittle.core.eval_string(src); } catch (e) { throw new Error(mods[i] + \": \" + (e.message || e)); }\n });\n // then the page itself, its parts in order (app/page)\n return Promise.all(page.map(function (m) {\n return fetch(m, { cache: \"no-cache\" }).then(function (r) { if (!r.ok) throw new Error(\"could not read \" + m + \" (\" + r.status + \")\"); return r.text(); });\n })).then(function (parts) {\n parts.forEach(function (src, i) {\n try { scittle.core.eval_string(src); } catch (e) { throw new Error(page[i] + \": \" + (e.message || e)); }\n });\n });\n })\n .catch(show);\n});\n</script>\n\n","kairotic/api.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · api\n;; What a component that does not live in the core may use. Packages (@kairotic/synth, …) and\n;; components written in a work use these functions instead of the core's own modules, so the core\n;; can change inside without breaking them. Inside a component source this namespace is `api`.\n;;\n;; The API has a version: a package declares the one it was written for ({:api 1}). A change that\n;; breaks a function here raises the major version; adding functions does not.\n\n(ns kairotic.api\n (:require [clojure.string :as str]\n [clojure.edn :as edn]\n [kairotic.components :as comp]\n [kairotic.canvas :as cv]\n [kairotic.code :as code]\n [kairotic.patterns :as pat]\n [kairotic.structure :as st]))\n\n(def version 1)\n\n;; ───────── numbers ─────────\n\n(defn clamp \"x between a and b (in either order).\" [x a b] (comp/clamp x a b))\n(defn nice \"A value rounded to a sensible precision for display and sending.\" [v] (comp/nice v))\n(defn num-of \"A number from a message: the number itself, or the first of a list (else nil).\" [v] (comp/num-of v))\n(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?))\n(defn from-unit \"0…1 back to lo…hi (logarithmic with log?).\" [u lo hi log?] (comp/from-unit u lo hi log?))\n\n(defn padded\n \"The numbers written in a box text, the missing ones taken from defaults: (padded [20] [10 100]) → [20 100].\"\n [args defaults]\n (let [ns (filterv number? args)] (vec (take (count defaults) (concat ns (drop (count ns) defaults))))))\n\n;; ───────── audio ─────────\n\n(defn stereo-outlets\n \"Two outlets (left, right) from a stereo AudioNode: [[splitter 0] [splitter 1]].\"\n [ac node]\n (let [sp (.createChannelSplitter ac 2)] (.connect node sp) [[sp 0] [sp 1]]))\n\n(defonce worklet-modules (atom {})) ; [AudioContext name] → Promise\n\n(defn worklet-ready\n \"Promise that resolves when the AudioWorklet code `source` is loaded in `ac` under `name` (once per\n context, whoever asks first). `source` is JavaScript that calls registerProcessor(name, …).\"\n [ac name source]\n (let [k [ac name]]\n (or (get @worklet-modules k)\n (let [url (js/URL.createObjectURL (js/Blob. #js [source] #js {:type \"application/javascript\"}))\n p (.addModule (.-audioWorklet ac) url)]\n (swap! worklet-modules assoc k p)\n p))))\n\n(defn worklet-node\n \"Promise of an AudioWorkletNode of processor `name` (defined in `source`) with these options.\"\n [ac name source opts]\n (.then (worklet-ready ac name source)\n (fn [_] (js/AudioWorkletNode. ac name (clj->js opts)))))\n\n(defn param \"The AudioParam `k` of an AudioWorkletNode.\" [w k] (.get (.-parameters w) k))\n\n;; ───────── from the sound back to the messages ─────────\n;; An audio node cannot send messages itself: it reports what it finds to its own box, whose :receive\n;; gets it on inlet :audio and decides what to send (:out), show (:show) or keep (:state).\n\n(defn report!\n \"From an audio node: gives box `id` (the :id of the box its :create got) a value found in the sound.\n It arrives at the box's :receive as {:inlet :audio :value value :at at}, at instant `at` (an\n AudioContext time; now if nil). Only while the engine runs.\"\n [id value at]\n (when-let [f @comp/audio-report] (f id value at)))\n\n(defn effect!\n \"From an audio node: an effect of box `id` for the page, such as [:sample [:set d]] (keep a recording\n as the data of the box). Unlike report!, it also works when the engine has just stopped.\"\n [id e]\n (when-let [f @comp/audio-effect] (f id e)))\n\n(def tap-source\n \"class KairoticTap extends AudioWorkletProcessor {\n // Listens to its input and hands it to the page every `hop` samples, in one of three forms:\n // frames — the last `size` samples of each channel, oldest first\n // summary — for each channel its last sample, its level (rms) and its peak over the last `size`\n // trace — for each channel `columns` pairs [min, max] over `size` samples, starting at the first\n // rising zero crossing of the older half of a ring of 2 × size (a steady picture of a\n // periodic wave; where there is none, the newest `size` samples)\n // with the AudioContext time of the last sample. No output: the input connected to it keeps it\n // running. A message {size, hop, columns} changes them; {active: false} stops handing (true starts again,\n // from the next hop: frames with size = hop then hold only samples heard since); {flush: true} hands at\n // once the samples heard since the last hand-over (frames only), marked last.\n constructor(o) {\n super();\n const p = (o && o.processorOptions) || {};\n this.C = Math.max(1, p.channels | 0 || 1);\n this.mode = p.mode || 'frames';\n this.active = p.active !== false;\n this.columns = Math.max(2, p.columns | 0 || 128);\n this.resize(p.size | 0 || 2048, p.hop | 0 || 1024);\n this.port.onmessage = (e) => {\n const d = e.data || {};\n if (d.columns) this.columns = Math.max(2, Math.min(2000, d.columns | 0));\n if (d.size || d.hop) this.resize(d.size | 0 || this.size, d.hop | 0 || this.hop);\n if (d.flush) {\n const data = [];\n for (let c = 0; c < this.C; c++) data.push(this.ordered(c).slice(this.R - Math.min(this.count, this.R)));\n this.port.postMessage({ data, at: currentTime, sr: sampleRate, last: true }, data.map((x) => x.buffer));\n this.count = 0;\n }\n if (d.active !== undefined) { if (d.active && !this.active) this.count = 0; this.active = !!d.active; }\n };\n }\n resize(size, hop) {\n this.size = Math.max(16, Math.min(1 << 17, size)); this.hop = Math.max(16, Math.min(1 << 17, hop));\n this.R = this.mode === 'trace' ? 2 * this.size : this.size;\n this.rings = []; for (let c = 0; c < this.C; c++) this.rings.push(new Float32Array(this.R));\n this.w = 0; this.count = 0;\n }\n ordered(c) {\n const r = this.rings[c], f = new Float32Array(this.R);\n f.set(r.subarray(this.w)); f.set(r.subarray(0, this.w), this.R - this.w);\n return f;\n }\n block() {\n const out = [];\n for (let c = 0; c < this.C; c++) {\n if (this.mode === 'summary') {\n const r = this.rings[c], N = this.R; let s = 0, pk = 0;\n 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; }\n out.push([r[(this.w + N - 1) % N], Math.sqrt(s / N), pk]);\n } else if (this.mode === 'trace') {\n const f = this.ordered(c), S = this.size, K = this.columns;\n let t = S;\n for (let i = 1; i < S; i++) if (f[i - 1] <= 0 && f[i] > 0) { t = i; break; }\n const col = new Float32Array(2 * K);\n for (let k = 0; k < K; k++) {\n const a = t + Math.floor(k * S / K), b = Math.max(a + 1, t + Math.floor((k + 1) * S / K));\n let lo = Infinity, hi = -Infinity;\n for (let i = a; i < b && i < f.length; i++) { const x = f[i]; if (x < lo) lo = x; if (x > hi) hi = x; }\n col[2 * k] = lo === Infinity ? 0 : lo; col[2 * k + 1] = hi === -Infinity ? 0 : hi;\n }\n out.push(col);\n } else out.push(this.ordered(c));\n }\n return out;\n }\n process(inputs) {\n const inp = inputs[0] || [];\n const n = inp[0] ? inp[0].length : 128;\n for (let i = 0; i < n; i++) {\n for (let c = 0; c < this.C; c++) { const ch = inp[c] || inp[0]; this.rings[c][this.w] = ch ? ch[i] : 0; }\n this.w = (this.w + 1) % this.R;\n if (++this.count >= this.hop) {\n this.count = 0;\n if (!this.active) continue;\n const data = this.block();\n this.port.postMessage({ data, at: currentTime + (i + 1) / sampleRate, sr: sampleRate, last: false },\n data.filter((d) => d instanceof Float32Array).map((d) => d.buffer));\n }\n }\n return true;\n }\n}\nregisterProcessor('kairotic-tap', KairoticTap);\n\")\n\n(defn tap\n \"Promise of an AudioWorkletNode that listens to a signal and gives it to the page in blocks; connect\n the signal to it. Every `hop` samples, (on-block data at sr) gets the AudioContext time of the last\n sample, the sample rate and, one entry per channel, according to :mode\n :frames (default) a Float32Array of the last `size` samples, oldest first\n :summary [last rms peak] over the last `size` samples\n :trace a Float32Array of `columns` pairs min, max over `size` samples, from a rising zero\n crossing (a steady oscilloscope picture)\n The loops over samples run in the worklet, so the page only handles small arrays (except :frames).\n (retap w {:size n :hop n :columns n}) changes the sizes while it runs; {:active false} stops handing\n blocks (:active true in the options starts it so) and {:flush true} hands at once, as :frames, what\n was heard since the last block. on-block also gets a fourth argument, {:last true} for that block.\"\n [ac {:keys [channels size hop mode columns active]} on-block]\n (.then (worklet-node ac \"kairotic-tap\" tap-source\n {:numberOfInputs 1 :numberOfOutputs 0\n :channelCount (or channels 1) :channelCountMode \"explicit\" :channelInterpretation \"discrete\"\n :processorOptions {:channels (or channels 1) :size (or size 2048) :hop (or hop 1024)\n :mode (name (or mode :frames)) :columns (or columns 128)\n :active (not (false? active))}})\n (fn [w]\n (set! (.. w -port -onmessage)\n (fn [e] (let [d (.-data e)]\n (try (on-block (vec (array-seq (.-data d))) (.-at d) (.-sr d) {:last (true? (.-last d))})\n (catch :default ex (js/console.error ex))))))\n w)))\n\n(defn untap\n \"A tap is done with (the box is gone, or the engine stopped): it stops handing blocks and is disconnected.\n Without it, a tap whose input was disconnected goes on handing silence to its box.\"\n [w]\n (when w\n (try (set! (.. w -port -onmessage) nil) (.postMessage (.-port w) #js {:active false}) (.disconnect w)\n (catch :default _ nil))))\n\n(defn retap \"A tap while it runs: new sizes {:size n :hop n :columns n}, {:active bool}, {:flush true}.\" [w sizes]\n (.postMessage (.-port w) (clj->js sizes)))\n\n(defn db \"A level (0…1) in decibels, -100 for silence.\" [x]\n (if (> x 1e-5) (* 20 (/ (js/Math.log x) js/Math.LN10)) -100))\n\n;; ───────── pitch ─────────\n\n(defn hz->midi \"A frequency as a MIDI pitch (fractional: 440 → 69).\" [hz] (cv/hz->midi hz))\n(defn midi->hz \"A MIDI pitch as a frequency (69 → 440).\" [m] (cv/midi->hz m))\n(defn midi-name \"The name of a whole MIDI pitch: 60 → \\\"C4\\\", 61 → \\\"C#4\\\".\" [m] (cv/midi-name m))\n(defn pitch-class \"The pitch class of a MIDI pitch as a keyword: 61 → :c#.\" [m]\n (keyword (str/lower-case (nth cv/note-names (mod (js/Math.round m) 12)))))\n\n;; ───────── libraries ─────────\n\n(defonce scripts (atom {})) ; url → Promise\n\n(defn load-script\n \"Promise that resolves when the classic script at `url` has run, once per page whoever asks first.\n npm:package@version/path is served by jsDelivr (the only place a page inside claude.ai can load\n code from). For libraries that put a global on window, such as Meyda: (.-Meyda js/window).\"\n [url]\n (let [u (if (str/starts-with? url \"npm:\") (str \"https://cdn.jsdelivr.net/npm/\" (subs url 4)) url)]\n (or (get @scripts u)\n (let [p (js/Promise.\n (fn [ok fail]\n (let [s (.createElement js/document \"script\")]\n (set! (.-src s) u)\n (set! (.-async s) true)\n (set! (.-onload s) (fn [_] (ok true)))\n (set! (.-onerror s) (fn [_] (swap! scripts dissoc u) (fail (js/Error. (str \"could not load \" u)))))\n (.appendChild (.-head js/document) s))))]\n (swap! scripts assoc u p)\n p))))\n\n(defonce modules (atom {})) ; [origin …] → Promise\n\n(defn import-module\n \"Promise of the default export of an ES module, once per page whoever asks first. `origins` is one\n place or a list of them, tried in order until one answers: npm:package@version/path (jsDelivr) or a\n path of this page (kairotic/packages/…, the page's own copy of a package's files). For modules a\n package carries beside its components, such as a WebAssembly wrapped in JavaScript.\"\n [origins]\n (let [os (if (string? origins) [origins] (vec origins))]\n (or (get @modules os)\n (let [imp (.-kairoticImport js/window)\n go (fn go [[o & more] errors]\n (if-not o\n (js/Promise.reject (js/Error. (str \"could not load \" (str/join \" nor \" os) \" (\" (str/join \"; \" errors) \")\")))\n (.catch (imp (if (str/starts-with? o \"npm:\") (str \"https://cdn.jsdelivr.net/npm/\" (subs o 4)) o))\n (fn [e] (go more (conj errors (str (or (.-message e) e))))))))\n p (.catch (go os [])\n (fn [e] (swap! modules dissoc os) (throw e)))]\n (swap! modules assoc os p)\n p))))\n\n;; ───────── the network (for :tasks) ─────────\n;; A component never fetches from its :receive: it asks for a task (:tasks), and these help the task.\n\n(defn url-of\n \"A URL from a message: a string, or a word as a msg box sends it (msg https://… arrives as a name).\n github:owner/repo@ref/path is served by jsDelivr (@main without @ref), the one site a page inside\n claude.ai can read. nil if it is not a URL.\"\n [v]\n (let [s (cond (string? v) v (symbol? v) (str v) (keyword? v) (subs (str v) 1) :else nil)\n s (some-> s str/trim (str/replace #\"^\\\"|\\\"$\" \"\"))\n gh (when s (re-matches #\"github:([^/\\s]+)/([^/@\\s]+)(@[^/\\s]+)?/(\\S+)\" s))]\n (cond (nil? s) nil\n (re-matches #\"https?://\\S+\" s) s\n gh (let [[_ owner repo ref path] gh]\n (str \"https://cdn.jsdelivr.net/gh/\" owner \"/\" repo (or ref \"@main\") \"/\" path))\n :else nil)))\n\n(defn- readable-key\n \"A key of a JSON object as EDN: a keyword when it can be written and read back as one, else the string.\"\n [k]\n (if (and (string? k) (re-matches #\"[A-Za-z*+!_?<>=][A-Za-z0-9*+!_?<>=.\\-]*\" k)) (keyword k) k))\n\n(defn json->edn\n \"Parsed JSON (js->clj) as EDN that can be written and read back: the keys of objects become keywords\n where they can (\\\"name\\\" → :name; \\\"2024\\\" and \\\"a b\\\" stay strings).\"\n [x]\n (cond (map? x) (into {} (map (fn [[k v]] [(readable-key k) (json->edn v)])) x)\n (vector? x) (mapv json->edn x)\n :else x))\n\n(defn http-get\n \"Promise of what is at `url` (https://…, or github:owner/repo@ref/path): with {:as :json} (the default)\n parsed into EDN (json->edn), :text as a string, :edn read as EDN. It fails with a reason in words when\n the site refuses this page (CORS) or cannot be reached, answers an error, takes longer than :timeout\n seconds (20) or sends more than :max characters (1000000).\"\n ([url] (http-get url {}))\n ([url {:keys [as timeout max] :or {as :json timeout 20 max 1000000}}]\n (if-let [u (url-of url)]\n (let [ctl (js/AbortController.)\n timer (js/setTimeout (fn [] (.abort ctl)) (* 1000 timeout))]\n (-> (js/fetch u #js {:signal (.-signal ctl)})\n (.then (fn [r]\n (if (.-ok r)\n (.text r)\n (throw (js/Error. (str \"the site answered \" (.-status r) (when (= 404 (.-status r)) \" (not found)\")))))))\n (.then (fn [text]\n (when (> (count text) max)\n (throw (js/Error. (str \"too long: \" (count text) \" characters (\" max \" at most)\"))))\n (case as\n :text text\n :edn (edn/read-string text)\n (json->edn (js->clj (js/JSON.parse text))))))\n (.catch (fn [e]\n (throw (cond (= \"AbortError\" (.-name e)) (js/Error. (str \"no answer in \" timeout \" s\"))\n ;; fetch itself fails (a TypeError) when the site refuses the page or cannot be reached\n (instance? js/TypeError e) (js/Error. \"the site does not let this page read it (CORS), or cannot be reached\")\n (instance? js/SyntaxError e) (js/Error. (str \"not \" (name as) \": \" (.-message e)))\n :else e))))\n (.finally (fn [] (js/clearTimeout timer)))))\n (js/Promise.reject (js/Error. (str (pr-str url) \" is not a URL (https://… or github:owner/repo/path)\"))))))\n\n;; ───────── code boxes ─────────\n;; A component whose data is a source text in some language (:display :code :language \"…\" :model\n;; api/code-model): each tab compiles the source with the compiler registered for that language.\n\n(def code-model \"The model of a code box: its data is {:source \\\"…\\\"}, with its own history.\" code/model)\n\n(defn compiled\n \"The compilation of a source in a language: {:status :ok :value x :info {…}}, {:status :compiling},\n {:status :error :error \\\"…\\\"} or {:status :empty}. Asked again when it is done (the page is told).\"\n [language source]\n (code/compiled language source))\n\n;; ───────── patterns (kairotic.patterns, for @kairotic/patterns) ─────────\n;; A pattern value is a factory of streams: lazy seqs of event maps ({:degree 2 :dur 1/2}). It travels\n;; along lines; the sequences are made in each tab, from a source and a seed.\n\n(defn pattern? \"Is x a pattern value?\" [x] (pat/pattern? x))\n(defn pattern-events \"A new stream of a pattern: a lazy, perhaps endless, seq of event maps.\" [p] (pat/events p))\n(defn pbind-pattern \"The pattern of a pbind map, with {:seed n :repeat n|:inf}.\" [m opts] (pat/pbind-pattern m opts))\n(defn code-pattern \"The pattern of a compiled \\\"pattern\\\" source, with {:seed :repeat :source}.\" [f opts] (pat/code-pattern f opts))\n(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))\n(defn pbind-problems \"What is wrong with a pbind map: a list of reasons, empty if nothing.\" [m] (pat/problems m))\n(defn pbind-source \"A pbind map written back as the text of its box.\" [m] (pat/spec->source m))\n(defn event-dur \"The length of an event in beats (:dur, 1 if none).\" [e] (pat/dur-of e))\n(defn event-sustain \"How long the notes of an event sound, in beats (:sustain, or :dur × :legato 0.8).\" [e] (pat/sustain e))\n(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))\n(defn rest-event? \"Is the event a silence?\" [e] (pat/rest? e))\n(defn render-tree\n \"A stretch of a pattern as a musical tree, through time maps ({:from :to}, or {:maps [[[x y] …] …]}: x the\n beats of the result, y those of the pattern), :tex / :tone the keys drawn as texture and colour.\"\n [p opts] (pat/render-tree p opts))\n(defn canvas-maps\n \"The strokes of a canvas, in order, as time maps for render-tree: [[[x y] …] …].\"\n [d] (mapv (fn [[_ s]] (:pts s)) (cv/sorted-strokes d)))\n\n;; ───────── form: how alike the moments are (kairotic.structure, issue #120) ─────────\n\n(defn ssm \"The self-similarity matrix of frames (vectors of one length): {:n :data}, the cosine of every two.\" [vs] (st/ssm vs))\n(defn ssm-at \"The similarity of frames i and j in a matrix of ssm.\" [S i j] (st/at S i j))\n(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))\n(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))\n(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))\n(defn periods \"The peaks of a beat spectrum, strongest first: [[lag value] …].\" [bs] (st/periods bs))\n(defn boundaries \"Where segments begin, from a novelty curve: {:shortest 8 :longest 64 :k 0.5} (frames).\" [nov opts] (st/boundaries nov opts))\n(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))\n","kairotic/assistant.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · assistant\n;; Writing components with Claude, inside the work. The page asks Claude (claude.ai's `sample`\n;; capability, on the viewer's own Claude account) with a prompt built here: the component contract,\n;; the Kairotic API, real components as examples and the classes the work already has. While it\n;; writes, Claude can call the page's tools defined here to check what it wrote — evaluate and\n;; validate it, send it messages, draw its view — so what arrives in the work has been tried.\n;; The result is an ordinary component box, created as gestures, in the history like any other.\n;;\n;; Study 16: Claude can also write Faust (checked by compiling it), abstractions — components that are\n;; a patch, with faust~ boxes, controls and a panel of presented boxes (a bpatcher) — and packages of\n;; several components. Real examples come from a catalog (examples/catalog.mjs) that Claude sees as a\n;; list and reads one by one with a tool, so it can grow without the prompt growing.\n\n(ns kairotic.assistant\n (:require [clojure.string :as str]\n [clojure.walk :as walk]\n [kairotic.corefns :as cf]\n [kairotic.components :as comp]\n [kairotic.shapes :as shp]\n [kairotic.code :as code]\n [kairotic.library :as lib]))\n\n;; ───────── evaluating a source ─────────\n\n(defn evaluate\n \"{:ok definition-or-package} or {:error reason} for a component source (one expression).\"\n [source]\n (try\n (let [m (js/scittle.core.eval_string (str \"(do \" source \"\\n)\"))]\n (if-let [reason (lib/validate m)] {:error reason} {:ok m}))\n (catch :default e {:error (str \"does not evaluate: \" (or (.-message e) e))})))\n\n(defn definition\n \"{:ok definition} for class `cls` of a source (a component, or one of a package's), or {:error}.\"\n [source cls]\n (let [{:keys [ok error]} (evaluate source)]\n (if error\n {:error error}\n (let [defs (lib/definitions ok)\n d (if (seq (str cls)) (first (filter #(= (str cls) (:class %)) defs)) (first defs))]\n (if d {:ok d} {:error (str \"no class \" cls \" in this source (\" (str/join \", \" (map :class defs)) \")\")})))))\n\n(defn read-edn\n \"A value written as EDN by Claude (messages, a shown value).\"\n [s]\n (when (and (string? s) (seq (str/trim s)))\n (js/scittle.core.eval_string (str \"(quote \" s \")\"))))\n\n(defn cut [s n] (let [s (str s)] (if (> (count s) n) (str (subs s 0 n) \" …\") s)))\n\n(defn box-text [m args-text]\n (str (:class m) (when (seq (str/trim (str args-text))) (str \" \" (str/trim args-text)))))\n\n;; ───────── the tools ─────────\n\n(defn describe\n \"What one definition is, for Claude.\"\n [m]\n (let [io (:io m)]\n (cond-> {:class (:class m)\n :kind (if (:patch m) \"abstraction\" \"component\")\n :io (if (fn? io) \"computed\" io)\n :core-class-clash (= :core (:origin (comp/lookup (:class m))))}\n (sequential? (:args m)) (assoc :args (pr-str (:args m)))\n (not (:patch m)) (assoc :view (cond (:view m) \"view template\" (:draw m) \"draw function\" :else \"text box\")\n :gesture (boolean (:gesture m)) :persist (boolean (:persist m))\n :audio (when (map? (:audio m)) (vec (map name (keys (:audio m)))))))))\n\n(defn check\n \"What a source defines, or why it does not work (synchronous: no Faust inside is compiled).\"\n [source]\n (let [{:keys [ok error]} (evaluate source)]\n (if error\n {:ok false :error error}\n (let [defs (lib/definitions ok)]\n (assoc (describe (first defs)) :ok true\n :classes (mapv :class defs)\n :package (:package ok))))))\n\n;; ───────── Faust ─────────\n\n(defn compile-faust\n \"Promise of {:ok true :ins :outs :params} or {:ok false :error} for a Faust source, compiled with the\n page's own compiler (the result stays in the cache, so the box that uses it starts at once).\"\n [source]\n (if-let [f (get @code/compilers \"faust\")]\n (-> (js/Promise.resolve nil)\n (.then (fn [_] (f (str source))))\n (.then (fn [r]\n (swap! code/cache assoc [\"faust\" (str source)] (assoc r :status :ok :n (swap! code/counter inc)))\n (let [i (:info r)]\n {:ok true :ins (:ins i) :outs (:outs i)\n :params (mapv (fn [p] (select-keys p [:label :type :min :max :init])) (:params i))})))\n (.catch (fn [e] {:ok false :error (cut (or (.-message e) (str e)) 1500)})))\n (js/Promise.resolve {:ok false :error \"no Faust compiler in this page\"})))\n\n;; ───────── abstractions ─────────\n\n(defn available?\n \"Whether class k can be used in a patch: known now, defined next to it, or brought from an official\n package when it is used.\"\n [k siblings]\n (boolean (or (comp/lookup k) (contains? siblings k) (lib/package-of k))))\n\n(defn check-patch\n \"Errors of the :patch of an abstraction (boxes, classes, ports), and what it offers.\"\n [m siblings]\n (let [p (:patch m) bs (:boxes p) lines (:lines p)\n k-of (fn [b] (comp/klass (str/replace (str (:text b)) #\"\\$\\d\" \"0\")))\n box-errs (for [[id b] bs\n :let [k (k-of b)]\n err [(when-not (keyword? id) (str id \": box ids are keywords like :b1\"))\n (when-not (string? (:text b)) (str id \": a box has :text\"))\n (when-not (and (number? (:x b)) (number? (:y b))) (str id \": a box has :x and :y\"))\n (when (and (string? (:text b)) (not (available? k siblings))) (str id \": no class «\" k \"»\"))\n (when (and (= k \"faust~\") (str/blank? (str (get-in b [:data :source])))) (str id \": a faust~ needs :data {:source \\\"…\\\"}\"))]\n :when err] err)\n io-of (fn [id] (let [b (get bs id)] (when (and b (comp/lookup (k-of b)) (not (comp/dynamic? b)))\n (comp/io (update b :text #(str/replace (str %) #\"\\$\\d\" \"0\"))))))\n line-errs (for [l lines\n :let [[a o b i] (when (and (vector? l) (= 4 (count l))) l)\n [_ outs] (io-of a) [ins _] (io-of b)]\n err [(when-not a (str (pr-str l) \": a line is [from outlet to inlet]\"))\n (when (and a (not (get bs a))) (str (pr-str l) \": no box \" a))\n (when (and b (not (get bs b))) (str (pr-str l) \": no box \" b))\n (when (and outs (>= o outs)) (str (pr-str l) \": \" a \" has \" outs \" outlets\"))\n (when (and ins (>= i ins)) (str (pr-str l) \": \" b \" has \" ins \" inlets\"))]\n :when err] err)\n ports (fn [ks] (count (filter (fn [[_ b]] (ks (k-of b))) bs)))]\n {:errors (vec (concat box-errs line-errs))\n :inlets (ports #{\"inlet\" \"inlet~\"}) :outlets (ports #{\"outlet\" \"outlet~\"})\n :presented (vec (for [[id b] bs :when (:present b)] (str (name id) \" \" (:text b))))\n :faust (vec (for [[id b] bs :when (= \"faust~\" (k-of b))] [id (get-in b [:data :source])]))}))\n\n(defn check-full\n \"Promise of the whole check of a source, for Claude and before a result enters the work: it\n evaluates and validates every definition, checks the patch of abstractions and compiles every\n Faust source inside them.\"\n [source]\n (let [{:keys [ok error]} (evaluate source)]\n (if error\n (js/Promise.resolve {:ok false :error error})\n (let [defs (vec (lib/definitions ok))\n siblings (set (map :class defs))\n patches (into {} (for [d defs :when (map? (:patch d))] [(:class d) (check-patch d siblings)]))\n fausts (for [[cls r] patches [id src] (:faust r)] [cls id src])]\n (-> (js/Promise.all (clj->js (for [[_ _ src] fausts] (compile-faust src))))\n (.then (fn [results]\n (let [faust-errs (vec (keep (fn [[[cls id _] r]] (when-not (:ok r) (str cls \" \" (name id) \": Faust: \" (:error r))))\n (map vector fausts (js->clj results :keywordize-keys true))))\n errs (vec (concat (mapcat (fn [[cls r]] (map #(str cls \" \" %) (:errors r))) patches) faust-errs))]\n {:ok (empty? errs)\n :package (:package ok)\n :definitions (mapv (fn [d] (merge (describe d)\n (when-let [r (get patches (:class d))]\n (select-keys r [:inlets :outlets :presented]))))\n defs)\n :errors errs}))))))))\n\n(defn used-classes\n \"The classes that the abstractions of a source use (to bring the official ones into the work).\"\n [source]\n (let [{:keys [ok]} (evaluate source)]\n (when ok\n (distinct (for [d (lib/definitions ok) :when (map? (:patch d)) [_ b] (:boxes (:patch d))]\n (comp/klass (str/replace (str (:text b)) #\"\\$\\d\" \"0\")))))))\n\n(defn try-receive\n \"Sends messages ([[inlet value] …], as EDN) to the component, one after another, threading its\n state as the engine does. args-text: the words after the class in the box text.\"\n [source cls args-text messages]\n (let [{:keys [ok error]} (definition source cls)]\n (cond\n error {:ok false :error error}\n (not (fn? (:receive ok))) {:ok false :error \"it has no :receive\"}\n :else\n (let [m ok text (box-text m args-text) args (comp/args-for m text)\n msgs (try (read-edn messages) (catch :default e (throw (js/Error. (str \"messages are not EDN: \" (.-message e))))))]\n (when-not (sequential? msgs) (throw (js/Error. \"messages: a vector of [inlet value], e.g. [[0 440] [0 :bang]]\")))\n (loop [state nil [[inlet value] & more] (seq msgs) acc [] t 0]\n (if (nil? inlet)\n {:ok true :box-text text :args (pr-str args) :results acc}\n (let [r (try ((:receive m) {:id :b1 :state state :args args :inlet inlet :value value :at t :data nil})\n (catch :default e {::error (or (.-message e) (str e))}))]\n (if-let [err (::error r)]\n {:ok false :box-text text :results (conj acc {:in (pr-str [inlet value]) :error err})}\n (recur (if (and (map? r) (contains? r :state)) (:state r) state) more\n (conj acc {:in (pr-str [inlet value])\n :result (cut (pr-str (select-keys r [:out :show :effects :later :state])) 600)})\n (+ t 0.1))))))))))\n\n(def shape-kinds #{:rect :circle :line :arc :needle :path :text :curve :group})\n\n(defn holes [template]\n (let [acc (atom #{})]\n (walk/postwalk (fn [x] (when-let [k (shp/hole x)] (swap! acc conj k)) x) template)\n @acc))\n\n(defn try-view\n \"Draws the component's view for a shown value (EDN) and the box text, and checks it: shape kinds,\n holes without a value, numbers. With a gesture, also tries one drag and what it would persist.\"\n [source cls args-text shown]\n (let [{:keys [ok error]} (definition source cls)]\n (cond\n error {:ok false :error error}\n (not (or (:view ok) (:draw ok))) {:ok true :note \"no :view nor :draw: the box is shown as text\"}\n :else\n (let [m ok text (box-text m args-text) args (comp/args-for m text)\n [w h] (let [s (:size m)] (if (vector? s) s [80 40]))\n shown (read-edn shown)\n ctx {:shown shown :state nil :args args :text text :data nil :w w :h h}\n derived (when (:derive m) ((:derive m) ctx))\n vals (merge (when (map? args) args) {:shown shown :w w :h h} derived)\n missing (when (:view m) (vec (remove #(contains? vals %) (holes (:view m)))))\n shapes (vec (remove nil? (if (:view m) (shp/fill (:view m) vals) ((:draw m) ctx))))\n bad (vec (keep (fn [s] (when-not (and (vector? s) (shape-kinds (first s)) (map? (second s)))\n (cut (pr-str s) 120)))\n shapes))\n nan (vec (keep (fn [s] (when (some (fn [[_ v]] (and (number? v) (not (js/isFinite v)))) (second s))\n (cut (pr-str s) 120)))\n (filter #(map? (second %)) shapes)))\n gesture (when (:gesture m)\n (try (let [v ((:gesture m) (assoc ctx :start shown :x (/ w 2) :y (/ h 2) :dx 10 :dy -10 :fine false))]\n {:value (pr-str v)\n :on-release (pr-str ((:gesture m) (assoc ctx :start shown :x (/ w 2) :y (/ h 2) :dx 10 :dy -10 :fine false :up true)))\n :persist (when (:persist m) (comp/args-text m (:class m) (merge (comp/args-for m text) ((:persist m) v))))})\n (catch :default e {:error (or (.-message e) (str e))})))]\n {:ok (and (empty? missing) (empty? bad) (empty? nan) (not (:error gesture)))\n :size [w h] :shapes (count shapes)\n :holes-without-value missing :not-shapes bad :non-finite-numbers nan\n :drawn (cut (pr-str shapes) 1500)\n :gesture gesture}))))\n\n(defn classes\n \"The classes the work knows now: \\\"class [in out] — first sentence of its doc\\\", and the functions of\n clojure.core that are boxes by themselves.\"\n []\n (conj (vec (for [[k d] (sort-by key @comp/registry)\n :let [io (:io d) doc (first (str/split (str (:doc d)) #\"(?<=\\.)\\s\"))]]\n (str k \" \" (if (vector? io) (pr-str io) \"\") \" — \" (cut doc 110) \" (\" (name (or (:origin d) :core)) \")\")))\n (str \"Also, without defining anything, a box named after one of these pure functions is that function: its \"\n \"other words are its EDN arguments, the message goes last (or where % is) and is always the left inlet, the only \"\n \"hot one; one more inlet per other argument, in order (vector % 0 0 is a pack, hash-map :freq % :amp 0.5 makes an \"\n \"event); ^:hot before the class makes every inlet hot; a keyword, set or map written first is a function too, \"\n \"the message first (:freq · #{60 64} · {60 :c}); nil sends nothing; xf/ before a function is its transducer over \"\n \"the stream of messages, with memory (xf/partition-all 4 collects, xf/partition 4 1 slides, xf/dedupe, xf/take 1; \"\n \"flush and clear); functions travel through wires as their EDN form: comp, partial, juxt, complement, fnil, \"\n \"constantly, every-pred and some-fn are boxes that send one on a bang (comp inc (partial * 2)), and a name or \"\n \"such a form in any argument is the function, so sending one into the inlet of inc in map inc changes it live \"\n \"(msg dec does it too). A msg box is read as Clojure: keywords with their colon (msg :stop, msg :rec 4), any \"\n \"other word a name (msg inc; free text such as e4, 6/5, a URL), \\\"strings\\\" and EDN forms ([0 4 7], {:freq 440}); \"\n \"msg stop is a name and does not stop anything: \"\n (str/join \" \" (cf/names)))))\n\n;; ───────── the prompt ─────────\n\n(def rules\n \"You write box classes for Kairotic, a visual patcher of music (like Max/Pd) whose patch and code are\nthe same work, written in ClojureScript and run with Scittle (SCI, interpreted, no compiler) in the\nbrowser. You may write:\n\n1. A component: ONE ClojureScript expression that evaluates to the definition map. It may be\n `(let [helpers …] {…})`. No `ns`, no top-level `def`/`defn`, no requires. Available: clojure.core,\n clojure.string as `str/`, the Kairotic API as `api/` (below), and JavaScript interop (`js/Math`,\n the Web Audio objects you are given). Do NOT use other kairotic namespaces (`comp/`, `cv/`, `eng/`…).\n Never touch the DOM, the network or storage.\n2. An abstraction: a component whose class IS a patch — {:class :doc :usage :patch {:boxes {…} :lines […]}}.\n Boxes: `:b1 {:text \\\"faust~\\\" :x 20 :y 140 :data {:source \\\"…Faust…\\\"}}`; lines: `[:b1 0 :b4 0]`\n (from-box outlet to-box inlet). Its ports are its `inlet`/`outlet` (messages) and `inlet~`/`outlet~`\n (audio) boxes, numbered left to right by :x. `$1 $2` in box texts take the words of each instance.\n `:present [x y]` on a box puts it on the panel every instance shows (a bpatcher); only boxes with\n their own view act there (knob, adsr~, space~, or components with a :view). Inside, use classes that\n exist (`list_classes`); the official ones adsr~ synth~ pan~ space~ knob keyboard are brought into\n the work automatically. For audio DSP prefer a `faust~` box with Faust code: its audio ports are\n those of `process`, and its left inlet takes parameters as messages `[:cutoff 800]` — exactly what\n a named knob sends (`knob 40 12000 1200 log cutoff`); a list of Hz sets freq and gate = 1.\n3. A package, when you need several definitions together (a control of your own and the abstraction\n that uses it): {:package \\\"work/<name>\\\" :version \\\"0.1.0\\\" :components [definition …]}.\n\nWrite in English (names, :doc, comments). Keep it small and readable, in sections like the examples:\nabout (:class :license \\\"MPL-2.0\\\" :doc :usage :io), arguments (:args, :persist), logic (:receive,\n:gesture, called once more with :up true on release: return a release message there if the\ncomponent needs press and release), view (:derive, :view as data, :size), audio (:audio), help (:help {:inlets [\\\"one line per inlet\\\" …]\n:outlets […] :try \\\"something to do with it\\\"}, shown in the Help tab). Prefer :view (a data template with\n$holes) over :draw. A class name is one word; audio classes end in ~. Do not reuse a core class name.\n:receive is pure: it returns data ({:out … :state … :show … :effects … :later …}); side effects on\nsound happen only through :audio :effects. Anything else a box needs from outside (a URL, an API, a file)\nis a task: declare :tasks {:get (fn [x box] promise)} (api/http-get makes the request), ask for it from\n:receive with :effects [[:get x]], and handle its outcome when it arrives on inlet :task as\n{:task :get :arg x :value v} or {:task :get :arg x :error \\\"…\\\"} (compare :arg with what :state waits for:\na late answer to an older request is dropped). To keep the outcome in the work (the history, the same\nfor everyone) return :effects [[:keep d]] with a :model {:empty {} :load (fn [d] d)} whose data is d; to\nuse it only live, keep it in :state. Never call js/fetch, set timers or keep atoms in :receive or :state.\nSee the example data/fetch. The same value arriving again must change nothing that is\ngoing on (data boxes send what they hold again after ■ or when the patch before them changes): a player\ndoes not start over, an accumulator does not count it twice — compare with what :state keeps. Messages are numbers, keywords (:bang), strings or vectors.\nFaust: `import(\\\"stdfaust.lib\\\");`, the standard libraries (os. fi. en. re. ef. si. ba. no. de.),\nhslider/button for parameters, `process = …;`. In ClojureScript source the Faust code is a string:\nescape its double quotes.\nMusical data (notation, composition, CAC) travels as musical trees (kairotic.mt, alias mt/ in sources):\nhiccup vectors such as [:voice [:measure {:meter [4 4]} [:note {:pitch \\\"c4\\\" :dur 1}] \\\"d4/.5 e4\\\"]]\n(tags :piece :voice :section :seq :par :measure :tuplet {:ratio [3 2]} :chord :note :rest :param :dyn\n:text; any extra key is allowed). Proportional rhythm: [:rtm {:shares [1 [1 [1 1 1]] -1 2] :pitches \\\"c4 d4\\\"}]\nfills its measure (or its :dur) with those shares; note values and tuplets follow from the meter.\nGrouped meters: [:measure {:meter \\\"5/8[2+3]\\\"} …] (or :meter [5 8] :groups [2 3]); mt/meter-level and\nmt/indispensability (Barlow) give metric weight, mt/thin keeps the notes on the strongest positions.\nA component that makes or changes music sends a tree from :receive;\nuse mt/events, mt/transpose, mt/pitch-name … rather than your own parsing. See the example notation/walk.\n\nWork method: the catalog below lists real examples; read the ones close to the request with\n`read_example` before writing. Write, then CHECK before answering: `check_faust` for Faust code,\n`check_component` for the whole source (it also compiles the Faust inside abstractions), then\n`try_messages` with representative messages and `try_view` if it has a view. Fix what fails and check\nagain. Keep tool calls few.\n\nYour final answer: one or two sentences saying what it does and how to use it (inlets, outlets,\narguments), then the complete source in ONE ```clojure fenced block. Nothing after it.\")\n\n(defn catalog-text\n \"The catalog as Claude sees it: one line per example.\"\n [examples]\n (str/join \"\\n\" (for [e examples] (str \"- \" (:name e) \" (\" (:category e) \", \" (:kind e) \"): \" (:about e)))))\n\n(defn prompt\n \"The whole input for Claude. `change` is the source of an existing component to modify (or nil);\n `always` are examples given whole; `examples` the catalog (read with read_example).\"\n [{:keys [request change contract api always examples]}]\n (str rules\n \"\\n\\n━━━ The component contract (from kairotic/components.cljs) ━━━\\n\" contract\n \"\\n\\n━━━ The Kairotic API (kairotic/api.cljs), usable as api/… ━━━\\n\" api\n \"\\n\\n━━━ Two examples, whole ━━━\\n\"\n (str/join \"\\n\\n\" (map (fn [e] (str \";; ── example: \" (:name e) \" — \" (:about e) \" ──\\n\" (:source e))) always))\n \"\\n\\n━━━ The catalog of examples (read any with read_example) ━━━\\n\" (catalog-text examples)\n (when change (str \"\\n\\n━━━ The component to change (keep what is not asked to change) ━━━\\n\" change))\n \"\\n\\n━━━ The request ━━━\\n\" request \"\\n\"))\n\n(defn header-of\n \"The leading comment block of a source file, without the ;; marks (what documents it).\"\n [text]\n (->> (str/split-lines (str text))\n (take-while #(str/starts-with? (str/triml %) \";;\"))\n (map #(str/replace % #\"^\\s*;; ?\" \"\"))\n (str/join \"\\n\")))\n\n(defn source-of\n \"The last ```clojure (or plain ```) fenced block of an answer.\"\n [text]\n (let [blocks (re-seq #\"```(?:clojure|clj|cljs|edn)?\\s*\\n([\\s\\S]*?)```\" (str text))]\n (some-> (last blocks) second str/trim)))\n\n;; ───────── patches (Study 23) ─────────\n;; Claude can also make a whole patch from a description, or change the one that is open. It answers\n;; with the patch's code — only the calls a patch is made of, as a link carries it — which the page\n;; checks (classes, ports, Faust compiled, components evaluated) and loads as one event of the history.\n\n(def patch-rules\n \"You make patches for Kairotic, a visual patcher of music (like Max/Pd) whose patch and code are the\nsame work. A patch is written as a list of calls, one per line, with LITERAL arguments only (numbers,\nstrings, keywords, vectors, maps) — no let, def, fn, str, arithmetic or any other form:\n\n (box :b1 \\\"osc~ 440\\\" 40 60) ; a box: id, text (class and arguments), x, y\n (connect :b1 0 :b2 0) ; from :b1 outlet 0 to :b2 inlet 0 (numbered from 0, left to right)\n (code :b3 \\\"…source…\\\") ; the source of a code box (faust~, script, component, tree)\n (present :b4 20 20) ; puts a box on the presentation (the performer's panel), at x y\n (view :b5 :roll) ; shows a tree box as a roll (it is a :score at first; a freqt :canvas or :score), same data\n (tree! :b5 [:voice \\\"c4/1 e4 g4/2\\\"]) ; the musical tree of a tree box\n (stroke :b6 [[0 220] [1 440]]) (axis :b6 :x 0 4) ; drawings of canvas/freqt boxes\n\nRules:\n- Use only classes that exist (`list_classes`; `class_help` gives the inlets and outlets of one).\n Official classes such as knob, keyboard, synth~, adsr~, pan~, space~ come into the work by\n themselves when a box uses them.\n- Messages flow without ▶; ▶ starts sound and time (metro, ramp, loadbang). Audio classes end in ~.\n Send sound to `dac~ 1 2` (both channels: connect to inlets 0 and 1) through a `gain~` of 0.1–0.3:\n never louder.\n- For sound that core classes do not make (FM, filters, effects, physical models…), use a `faust~` box\n with Faust code: `(box :b3 \\\"faust~\\\" x y)` and `(code :b3 \\\"import(\\\\\\\"stdfaust.lib\\\\\\\"); …process = …;\\\")`.\n Its audio ports are those of process; its LEFT inlet takes parameters as messages [:name value],\n which is exactly what a named knob sends: `knob 50 2000 300 log carrier` sends [:carrier v] to an\n hslider(\\\"carrier\\\", …). Write every parameter as hslider with sensible ranges and a smoothing\n (si.smoo). Call `check_faust` on the Faust code before using it.\n For a POLYPHONIC instrument (chords, a keyboard, a tree played in several voices) write one voice\n with `declare options \\\"[nvoices:8]\\\";` and controls named exactly freq, gain and gate (Faust's own\n allocator sets them note by note; gate drives an envelope such as en.adsr), and optionally\n `effect = …;` for one effect on the sum of the voices. Such a faust~ gets Hz on its LEFT inlet and\n voice ids on its RIGHT one (inlet 1), as synth~: keyboard 0→0, 1→1, 3→0 (velocity); mt play 0→0,\n 1→1; reader 0→0, 1→1. Its other parameters [:name v] apply to every voice.\n- Musical trees (tree boxes, notation): to PLAY one, prefer `tree` → `mt play` → `synth~` (mt play\n sends Hz and voice ids at the tree's tempo once ▶ is on; see class_help). To SHOW one as notation,\n send it to a tree box (it is shown as a score): tree → mt → tree. (A `freqt` with `(view :bN :score)` can\n preview one too, but trees go to tree boxes; a freqt is for strokes with no musical form yet.) A freqt's own strokes shown as a score are\n quantized into measures in the meter of its bar grid (`(grid-x :bN 0.5 [1.5 1.5])` → 6/8); `(quantize\n :bN {:meter \\\"3/4\\\"})` gives that measured tree. As a box: `quantize` (the freqt's outlet 1 on its right\n inlet, or a free tree on the left) keeps options sent as messages ([:meter \\\"3/4\\\"], [:divs [1 2 3 4]],\n [:legato 0.25], [:time :track]…) and only on a bang sends the measured tree, for a tree box — e.g.\n adc~ → pitch~ → transcribe → freqt → quantize → tree. Pitches are written with their names (\\\"bb4\\\", \\\"f#3\\\"),\n kept as written; `{:key \\\"eb\\\"}` on a tree, voice or measure gives the score its key; numbers are named\n by the key (mt/spell); `mt transpose M3` moves by an interval keeping the spelling.\n A tree box is also a piano roll ((view :bN :roll)): strokes drawn there, or (stroke :bN pts), become notes\n of the tree; (quantize! :bN) writes its free time in measures; its outlet 1 is a buffer for reader~. A freqt that shows a tree is also a\n buffer: `phasor~` → `reader~ norm` (left) with the freqt's outlet 1 on its right inlet gives the pitch as\n a signal (Hz), e.g. into a faust~ whose process takes a frequency input.\n A tree box sends its tree by itself: it needs no loadbang.\n- Sound from outside: `adc~ 1` is the microphone (asked for at ▶). `snapshot~ 50` turns any signal into\n numbers (`snapshot~ 50 db` its level), `scope~` draws it. Never connect an adc~ to dac~ without a\n `gain~` and a warning about headphones: it feeds back. `sample [seconds]` records what reaches its\n left inlet on `rec` until `stop`; its outlet 1 into the right inlet of `reader~ norm`, with a `phasor~` at\n 1/length Hz on the left, plays it (every reader and reader~ reads positions in its buffer's units — X of a\n canvas, time of a freqt, seconds — unless it says norm: 0…1) (its outlet 0 gives the length in seconds; `!/ 1` turns it into Hz).\n A sample can be a sound from a URL that every browser fetches: `(sample! :bN {:url \\\"https://…\\\"})`.\n Prefer `github:owner/repo@ref/path.wav` (e.g. `github:tidalcycles/Dirt-Samples@master/bd/BT0A0A7.wav`,\n served by jsDelivr) or `freesound:id`: most other sites refuse it (CORS).\n- Listening (package @kairotic/analysis, it comes by itself): `pitch~ [lo hi]` gives Hz (0 when it stops\n hearing a pitch) and clarity; `onset~` a bang per attack; `chroma~` 12 pitch-class values and the\n strongest class (:a …); `features~ [ms] rms centroid …` one outlet per descriptor; `spectrum~` draws.\n To see any stream over time: `monitor [seconds] [name …]`, one inlet (and lane) per name — numbers as\n lines, lists as strips, bangs and words as marks.\n- Music theory as geometry (package @kairotic/theory, it comes by itself): `pcclock` (a pitch-class set on\n the clock, its prime form on the left, interval vector in the middle), `fourier` (six Fourier magnitudes\n on the left), `tonnetz` (triads and the path of the harmony; the triad as :C, :am… on the left); they take\n lists of pitches in Hz (as a keyboard or midiin sends them; MIDI or 0…11 with the word midi: `pcclock midi`),\n notes one by one, or a chroma from `chroma~`; pressing a pitch class sends it (right).\n Counterpoint in the same package: `comes [system] [mode]` (you play the dux, in Hz or with midi; it answers\n with the comes as a canon: the Hz of both voices on 0 after their voice ids on 1, for one synth~ 0→0 1→1; the\n futuribles on 2, where the canon is on 3; :engine plays alone; `live` on a pulse) and `cancrizans` (a crab or\n `table` canon written from both ends; when it closes, patterns on 0 and 1 and the score as a tree on 4, for a\n tree box). The words name a system (diatonic, meantone, septimal31, pentatonic) and one of its modes (dorian…,\n penta-A…), in any order. Orders are keywords: msg :engine, not msg engine.\n Rhythm in the same package: `euclid k n [rotation] [bars]` (a Euclidean rhythm drawn as a necklace: a musical\n tree on 0, for a tree box, with an :rtm whose shares are the intervals between onsets; the :rtm map alone on\n 1; the pulses as 0/1 on 2). Its right inlet (cold) gives the pitches the notes take in turn (a keyboard's\n keys in Hz, a melody string, {:pitches …}, a pattern {:note […]}); [:k 5] [:n 16] [:rotation 2] [:bars 4]\n [:meter \\\"3/4\\\"] change it, a bang sends it.\n- The outside (package @kairotic/io, it comes by itself; listening while ▶ runs): `midiin` (MIDI in: Hz and\n voice ids for synth~ like a keyboard, and every event as a map {:type :note :freq :amp :gate …}),\n `midiout [mpe]` (Hz after voice ids, or events, to a MIDI port; mpe for microtones), `oscout [target]` and\n `oscin [pattern]` (OSC through `npx @kairotic/relay --osc`: events as /kairotic/note id freq amp gate…),\n `motion` (a phone's tilt [x y] and shakes), `gamepad` ([name value] and events), `serial [baud]` (a board's\n lines as numbers; msg :open asks for the port); `control cc 74` · `control pad lx` · `control tilt x` · `control osc\n /addr` picks one controller out of their events (event outlet), into `scale in-lo in-hi out-lo out-hi [log] [ms]`\n (@kairotic/controls) to bring it to a parameter's range — what (learn :bN) makes by itself.\n- The room (package @kairotic/net, it comes by itself): `share [channel]` sends any value to everyone in the\n shared room (and this page), `shared [channel]` gives what anyone shares (value left, who right, while ▶);\n `pulse [division]` counts the room's beat on the audio clock — one tempo for every page; `start [bpm]`,\n `stop`, `bpm n` change it for everyone.\n- Data (package @kairotic/data, it comes by itself): `fetch [json|text|edn] [live]` brings in what is at a\n URL (a msg with the URL, or `github:owner/repo@ref/path`) and keeps it in the work (live: only here); on\n the left what it found, [:get k …] a part of it; `edn [w h]` shows any value as a tree to open and pick\n from (the part on the left, its path on the right). Most sites outside GitHub refuse a page (CORS).\n- Patterns (package @kairotic/patterns, it comes by itself), after SuperCollider's and Overtone's: `pbind\n [seed] [repeat] [loop]` is a code box whose source is an EDN map of constants, vectors (sequences) and\n generators — #pat/choose [..], #pat/shuffle [..], #pat/white [lo hi], #pat/walk [x step lo hi],\n #pat/series [x step n], #pat/hold [beats [..]], #pat/chord [0 4 7] — set with `(code :bN \\\"{:degree [0 2\n 4] :dur 0.5}\\\")`; `pattern [seed]` is the same as Clojure code (pbind, pwhite, pchoose… and seeded rand),\n which needs (trust-scripts true) in a room; both send a pattern to the right inlet of `player [bpm]\n [quant]`, which plays it on `start`/`stop`, one step per bang, or at a position in beats (a number, from a\n ramp, either way: going back, each note starts from its end; seek p jumps). Its outlets: Hz (left) and voice ids (second) for synth~ or a polyphonic faust~, the whole event,\n the beat. Event keys: :freq, :note (MIDI, \\\"c4\\\"), or :degree with :scale :root :octave; :dur in beats,\n :legato; :rest (or nil) is a silence; :amp 0…1 is the loudness of its notes in synth~ and a polyphonic faust~. `render [from] [to]` draws a stretch of a pattern into a freqt (pattern left, freqt after it); a canvas\n on its right inlet is a time map (x: beats of the drawing, y: beats of the pattern; down = backwards, flat =\n hold, several strokes = layers). Write durations as decimals (0.25), not ratios.\n- Pitch shifting (package @kairotic/spectral, it comes by itself): `shift~ [factor …]` transposes the signal\n on its inlet by every factor at once (one interval or a chord), one frame (~21 ms) late. A factor is a\n ratio (1.5, 3/2), semitones with a sign (+7, -12, +0) or cents (386c); a msg with a list of them changes\n the chord; [:semitones 0 4 7], [:cents …], [:transpose st] (all of them at once, for glides), [:formants q t]\n (q ms keeps the formants, 1 for a voice; t shifts them), [:rms 1], [:dry x]. Typical: adc~ → shift~ 1 5/4 3/2 → dac~.\n- `draw [w h]` draws the shapes that reach it (the shapes of a component's view, or as a msg writes them:\n `msg :circle 40 40 10 :accent :hit :sun`, `msg :set :cursor :line 0 0 0 100`); a shape with :hit k sends k.\n- Annotations: `(mark :notes {:kind :text :at [:b3 0 -12] :txt \\\"…\\\"})`, `(mark :notes {:kind :arrow :pts\n [[:b1 120 10] [:b4 -6 10]]})` — points anchored to a box ([:bN dx dy] from its top-left corner) or to the\n paper ([:patch x y]); `(layer :notes {:z :over :show #{:patch :present}})`; `(project :bN :viz [x y w h])`\n draws a box's view large on a layer. Explain a patch with a few marks when it helps.\n To record any stream of numbers (a knob, `snapshot~ 50 rms`, a descriptor) as strokes: `record [lo hi]`\n → a `canvas` inlet, with `rec`/`stop`; a `reader~ norm` reads it back as an automation.\n A canon or a delay of messages: `ring [seconds]` (values on its left) → its RIGHT outlet → the right inlet\n of `reader d 1` (1 s behind; `reader d 2 speed 0.5`: later and slower); a number on a reader's left moves it\n instead. `writer` (left: what to write; middle: the ring's right outlet; right: a position) → the ring's left.\n With sound: `ring~ [seconds]` (sound on its left) → its RIGHT outlet → the right inlet of `reader~ d 1` (a\n delay; `speed 0.5` an octave down) or the middle inlet of `writer~` (sound left, position signal right).\n To write what is played into notation: `pitch~` → `transcribe [bpm] [notes|glide]` (left; `onset~` on its\n right) → a `freqt`'s inlet; `rec`/`stop` messages on transcribe's left.\n- `gain~ 0.2` sets its factor as an argument; a message into its right inlet changes it, a signal\n there replaces it. Do not leave a gain waiting for a message nobody sends.\n- Lay it out top to bottom, following the signal: x from 20 to 900, about 60 px between rows,\n controls on top. Code boxes are about 330 wide and 200 tall: leave them room.\n- Present the controls and displays a performer needs (`present`), in a compact panel.\n- When a patch is given to change, keep its boxes, ids and positions unless the request changes them;\n new boxes take new ids (the next numbers).\n\nWork method: `list_classes` first if unsure; `check_faust` for each Faust source; then `check_patch`\nwith the WHOLE code, fix what it reports and check again. Keep tool calls few.\n\nYour final answer: one or two sentences saying what the patch does and how to play it, then the\nWHOLE patch code in ONE ```clojure fenced block (only the calls above). Nothing after it.\")\n\n(defn patch-prompt\n \"The whole input for Claude when it makes or changes a patch.\"\n [{:keys [request current classes]}]\n (str patch-rules\n \"\\n\\n━━━ The classes this work knows now (more official ones come when used) ━━━\\n\"\n (str/join \"\\n\" classes)\n (when (seq (str/trim (str current)))\n (str \"\\n\\n━━━ The patch to change (keep what is not asked to change) ━━━\\n\" current))\n \"\\n\\n━━━ The request ━━━\\n\" request \"\\n\"))\n","kairotic/backends/gun-backend.js":"// SPDX-License-Identifier: MPL-2.0\n// Kairotic · a backend outside claude.ai (Study 17)\n//\n// Inside claude.ai a Kairotic page gets its database, rooms, user and Claude from the viewer\n// (`window.claude.use(\"db\" | \"room\" | \"user\" | \"sample\")`). Anywhere else — GitHub Pages, a local\n// server — this file gives the page the same four things, with the same shape, so the page does not\n// change:\n//\n// db collection(path) / doc(path) → set · update · delete · get · onSnapshot (GUN)\n// room presence(obj) · onPeers(fn) · join(name) → room · leave() (GUN)\n// user id() · can(what) · profiles(ids) (a local key pair)\n// sample sample(input, {tools, onText, signal, modelTier}) · limits() (Claude API, your own key)\n//\n// Data lives in GUN, a graph that syncs between browsers through relay peers. Everything under\n// data/users/<you>/ (your solo works) is encrypted with a key pair that never leaves this browser;\n// rooms are readable by whoever has their link, as in claude.ai. Each document is stored as JSON in\n// one field (GUN has no arrays). Deleting leaves a tombstone. Claude is called with the Anthropic API\n// key you paste into the page, kept only in this browser's storage and sent only to api.anthropic.com.\n(function () {\n \"use strict\";\n\n const store = {\n get(k) { try { return window.localStorage.getItem(k); } catch (_) { return null; } },\n set(k, v) { try { window.localStorage.setItem(k, v); } catch (_) { /* private mode */ } },\n del(k) { try { window.localStorage.removeItem(k); } catch (_) { /* private mode */ } },\n };\n\n const rid = (n) => {\n const a = new Uint8Array(n || 12);\n crypto.getRandomValues(a);\n return Array.from(a, (b) => \"abcdefghijklmnopqrstuvwxyz0123456789\"[b % 36]).join(\"\");\n };\n\n // ───────── from GUN's localStorage to IndexedDB ─────────\n // The localStorage adapter kept the graph under \"gun/\" as {soul: node}, nodes with their states: the\n // shape GUN takes in an incoming put, so giving it back as one ('in') merges it by those states (what\n // a relay has that is newer stays) and stores it in IndexedDB. Only the souls of this app are taken\n // (other GUN apps of the same origin share that key). When the page opens again a minute later or more,\n // those souls leave \"gun/\" (the key goes if nothing else is left), which frees the space.\n function migrateLocalStorage(gun, app) {\n const KEY = \"gun/\", DONE = \"kairotic.gun-migrated\";\n const ours = (soul) => soul === app || soul.indexOf(app + \"/\") === 0;\n let raw = null, graph = null;\n try { raw = window.localStorage.getItem(KEY); } catch (_) { return; }\n if (!raw) return;\n try { graph = JSON.parse(raw); } catch (_) { return; }\n if (!graph || typeof graph !== \"object\") return;\n const souls = Object.keys(graph).filter(ours);\n const done = Number(store.get(DONE)) || 0;\n if (done) {\n // brought over in an earlier visit (at least a minute ago, so IndexedDB has written it): free the space\n if (Date.now() - done < 60000) return;\n const rest = Object.keys(graph).filter((s) => !ours(s));\n try {\n if (!rest.length) window.localStorage.removeItem(KEY);\n else if (souls.length) {\n const kept = {};\n rest.forEach((s) => { kept[s] = graph[s]; });\n window.localStorage.setItem(KEY, JSON.stringify(kept));\n }\n } catch (_) { /* it stays: it is only read */ }\n return;\n }\n if (!souls.length) { store.set(DONE, String(Date.now())); return; }\n const put = {};\n souls.forEach((s) => { put[s] = graph[s]; });\n try {\n gun._.on(\"in\", { \"#\": rid(9), put: put });\n store.set(DONE, String(Date.now()));\n console.info(\"Kairotic: \" + souls.length + \" nodes moved from localStorage to IndexedDB\");\n } catch (e) { console.warn(\"Kairotic: the data in localStorage could not be moved to IndexedDB\", e); }\n }\n\n function create(opts) {\n opts = opts || {};\n const Gun = window.Gun, SEA = Gun && Gun.SEA;\n if (!Gun || !SEA) throw new Error(\"Kairotic: gun.js and sea.js must be loaded before gun-backend.js\");\n const app = opts.app || \"kairotic-v1\";\n // Where this browser keeps its copy of the graph. GUN's own localStorage adapter keeps everything it\n // has seen (the works, and the rooms that come from a relay) as one JSON of at most 5 MB: once full,\n // every save fails with \"localStorage max!\". With GUN's RAD on IndexedDB (site/vendor/gun/lib/) there\n // is room for much more; what an earlier version left in localStorage is brought over once.\n const rad = !!window.RindexedDB && opts.localStorage !== true;\n const gun = Gun({ peers: opts.peers || [], localStorage: !rad && opts.localStorage !== false,\n file: opts.file || \"kairotic-radata\" });\n if (rad) migrateLocalStorage(gun, app);\n const root = gun.get(app);\n const nodeAt = (path) => String(path).split(\"/\").filter(Boolean).reduce((n, s) => n.get(s), root);\n\n // ───────── identity: a key pair kept in this browser ─────────\n let pairP = null;\n const pair = () => pairP || (pairP = (async () => {\n const saved = store.get(\"kairotic.pair\");\n if (saved) { try { return JSON.parse(saved); } catch (_) { /* make a new one */ } }\n const p = await SEA.pair();\n store.set(\"kairotic.pair\", JSON.stringify(p));\n return p;\n })());\n // ids with no \"/\" or \".\" so they can be path segments\n const uidOf = (p) => p.pub.replace(/[^A-Za-z0-9_-]/g, \"\").slice(0, 32);\n\n // ───────── encoding: JSON, encrypted under data/users/ ─────────\n const privatePath = (path) => /^data\\/users\\//.test(String(path));\n async function encode(path, obj) {\n const json = JSON.stringify(obj);\n return privatePath(path) ? await SEA.encrypt(json, await pair()) : json;\n }\n async function decode(path, raw) {\n if (raw == null) return null;\n try {\n if (privatePath(path)) {\n const json = await SEA.decrypt(raw, await pair());\n return json == null ? null : (typeof json === \"string\" ? JSON.parse(json) : json);\n }\n return JSON.parse(raw);\n } catch (_) { return null; }\n }\n\n // a put resolves when a peer (or local storage) acknowledges it, or after a moment anyway\n const put = (node, value) => new Promise((resolve, reject) => {\n let done = false;\n const t = setTimeout(() => { if (!done) { done = true; resolve(); } }, 1500);\n node.put(value, (ack) => {\n if (done) return;\n done = true; clearTimeout(t);\n if (ack && ack.err) reject(new Error(String(ack.err))); else resolve();\n });\n });\n\n // a document as written (json and del): read from IndexedDB, a large one can arrive in parts\n const whole = (data) => \"json\" in data && \"del\" in data;\n\n function docSnap(id, path, data) {\n return decode(path, data && !data.del ? data.json : null).then((obj) => ({\n id, exists: obj != null, data: () => obj,\n }));\n }\n\n class DocRef {\n constructor(path) { this.path = String(path); this.id = this.path.split(\"/\").filter(Boolean).pop(); }\n async set(obj) { await put(nodeAt(this.path), { json: await encode(this.path, obj), del: false, t: Date.now() }); }\n async update(obj) {\n const cur = await this.get();\n await this.set(Object.assign({}, cur.exists ? cur.data() : {}, obj));\n }\n async delete() { await put(nodeAt(this.path), { json: null, del: true, t: Date.now() }); }\n // one read: the first whole value that arrives (GUN's once is unreliable without local storage), or\n // what has arrived after a moment. A document is whole when it has both json and del: read from\n // IndexedDB (RAD), a large one can arrive in parts, and its first part may not have json yet\n get() {\n return new Promise((resolve) => {\n let done = false, last = null;\n const chain = nodeAt(this.path);\n const finish = (data) => {\n if (done) return;\n done = true;\n try { chain.off(); } catch (_) { /* already off */ }\n resolve(docSnap(this.id, this.path, data));\n };\n chain.on((data) => {\n last = data;\n if (data && whole(data)) finish(data);\n });\n setTimeout(() => finish(last), 1200);\n });\n }\n onSnapshot(cb, err) {\n const chain = nodeAt(this.path);\n let alive = true;\n chain.on((data) => {\n if (data && !whole(data)) return; // a part of it (see get): the rest is coming\n docSnap(this.id, this.path, data).then((s) => { if (alive) cb(s); }).catch((e) => err && err(e));\n });\n return () => { alive = false; chain.off(); };\n }\n }\n\n class CollRef {\n constructor(path) { this.path = String(path); }\n doc(id) { return new DocRef(this.path + \"/\" + (id || rid(16))); }\n // every document of the collection, read as they arrive (GUN has no \"end\"): settles after a quiet moment\n get() {\n return new Promise((resolve) => {\n const seen = {};\n let timer = null;\n const settle = () => {\n Promise.all(Object.keys(seen).map((k) => docSnap(k, this.path + \"/\" + k, seen[k])))\n .then((docs) => resolve({ docs: docs.filter((d) => d.exists) }));\n };\n const poke = () => { clearTimeout(timer); timer = setTimeout(settle, 700); };\n const chain = nodeAt(this.path).map();\n chain.on((data, key) => { seen[key] = data; poke(); });\n poke();\n setTimeout(() => { try { chain.off(); } catch (_) { /* already off */ } }, 5000);\n });\n }\n onSnapshot(cb, err) {\n const docs = {};\n let alive = true, timer = null;\n const emit = () => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n Promise.all(Object.keys(docs).map((k) => docSnap(k, this.path + \"/\" + k, docs[k])))\n .then((snaps) => { if (alive) cb({ docs: snaps }); })\n .catch((e) => err && err(e));\n }, 40);\n };\n const chain = nodeAt(this.path).map();\n chain.on((data, key) => { if (data && !whole(data)) return; docs[key] = data; emit(); });\n emit();\n return () => { alive = false; chain.off(); };\n }\n }\n\n const db = {\n collection: (path) => new CollRef(path),\n doc: (path) => new DocRef(path),\n };\n\n // ───────── rooms: presence in GUN, renewed while the page is open ─────────\n const tab = rid(10);\n const LIVE_MS = 15000, BEAT_MS = 5000;\n\n function makeRoom(name) {\n const where = root.get(\"presence\").get(name);\n let mine = null, beat = null, watching = null, peersTimer = null;\n const entries = {};\n const room = {\n name,\n presence(obj) {\n mine = obj || {};\n const send = async () => put(where.get(tab), { json: JSON.stringify(mine), by: uidOf(await pair()), t: Date.now() });\n clearInterval(beat);\n beat = setInterval(send, BEAT_MS);\n return send();\n },\n onPeers(cb) {\n let last = \"\";\n const report = () => {\n const now = Date.now();\n const peers = Object.keys(entries)\n .filter((k) => entries[k] && entries[k].t > now - LIVE_MS)\n .map((k) => {\n let p = {};\n try { p = JSON.parse(entries[k].json || \"{}\"); } catch (_) { /* ignore */ }\n return { peer: k, by: entries[k].by, isMe: k === tab, sameTab: k === tab, kind: \"human\", presence: p };\n });\n const sig = JSON.stringify(peers);\n if (sig !== last) { last = sig; cb({ peers }); }\n };\n watching = where.map();\n watching.on((data, key) => { entries[key] = data; report(); });\n peersTimer = setInterval(report, 2000);\n report();\n },\n join(sub) { return Promise.resolve(makeRoom(sub)); },\n leave() {\n clearInterval(beat); clearInterval(peersTimer);\n if (watching) watching.off();\n return put(where.get(tab), { json: \"{}\", t: 0 });\n },\n };\n return room;\n }\n\n const room = makeRoom(\"lobby\");\n window.addEventListener(\"beforeunload\", () => { room.leave(); });\n\n // ───────── user ─────────\n const user = {\n id: () => pair().then(uidOf),\n can: () => Promise.resolve(true),\n profiles: () => Promise.resolve({}),\n };\n\n // the relays this page syncs through, and how each one is now: open, connecting or waiting (GUN\n // tries again on its own while one does not answer)\n const relays = () => Object.keys(gun._.opt.peers || {}).map((url) => {\n const w = (gun._.opt.peers[url] || {}).wire;\n return { url, state: !w ? \"waiting\" : w.readyState === 1 ? \"open\" : w.readyState === 0 ? \"connecting\" : \"waiting\" };\n });\n\n return { kind: \"gun\", gun, db, room, user, relays, sample: makeSample(opts) };\n }\n\n // ───────── Claude with your own API key ─────────\n // Same call as claude.ai's sample capability: sample(input, {tools, onText, signal, modelTier}).\n // The tool loop runs here: Claude asks for a tool, the page's execute runs, the result goes back.\n const KEY = \"kairotic.anthropicKey\";\n const MODELS = { quick: \"claude-haiku-5-5\", default: \"claude-sonnet-5-5\", complex: \"claude-opus-5-5\" };\n\n function makeSample(opts) {\n const api = (opts && opts.api) || \"https://api.anthropic.com/v1/messages\";\n const fail = (code, message, text) => Object.assign({ code, message }, text ? { text } : {});\n\n async function sample(input, o) {\n o = o || {};\n const key = store.get(KEY);\n if (!key) throw fail(\"not_granted\", \"No Anthropic API key: paste yours in the Claude tab (it stays in this browser).\");\n const tier = MODELS[o.modelTier] ? o.modelTier : \"default\";\n const model = store.get(\"kairotic.model\") || MODELS[tier];\n const messages = typeof input === \"string\" ? [{ role: \"user\", content: input }]\n : input.map((m) => ({ role: m.role, content: m.content }));\n const tools = (o.tools || []).map((t) => ({\n name: t.name, description: t.description,\n input_schema: t.inputSchema || { type: \"object\", properties: {} },\n }));\n let text = \"\", truncated = false;\n for (let round = 0; round < 10; round++) {\n let res;\n try {\n res = await fetch(api, {\n method: \"POST\", signal: o.signal,\n headers: { \"content-type\": \"application/json\", \"x-api-key\": key, \"anthropic-version\": \"2023-06-01\",\n \"anthropic-dangerous-direct-browser-access\": \"true\" },\n body: JSON.stringify(Object.assign({ model, max_tokens: 16000, messages }, tools.length ? { tools } : {})),\n });\n } catch (e) {\n if (o.signal && o.signal.aborted) throw fail(\"cancelled\", \"stopped\", text || undefined);\n throw fail(\"upstream_error\", String(e && e.message || e), text || undefined);\n }\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n if (res.status === 401 || res.status === 403) throw fail(\"not_granted\", \"The API key was refused: \" + body.slice(0, 200));\n if (res.status === 429) throw fail(\"rate_limited\", \"Too many requests or out of credit: \" + body.slice(0, 200), text || undefined);\n if (res.status === 400 && /prompt is too long/i.test(body)) throw fail(\"prompt_too_large\", body.slice(0, 200));\n if (/credit balance|billing/i.test(body)) throw fail(\"no_credit\", body.slice(0, 300));\n if (res.status === 529 || res.status === 503 || /overloaded/i.test(body)) throw fail(\"overloaded\", res.status + \" \" + body.slice(0, 200), text || undefined);\n if (res.status === 404 && /model/i.test(body)) throw fail(\"no_model\", model + \": \" + body.slice(0, 200));\n throw fail(\"upstream_error\", res.status + \" \" + body.slice(0, 300), text || undefined);\n }\n const msg = await res.json();\n const said = (msg.content || []).filter((b) => b.type === \"text\").map((b) => b.text).join(\"\");\n if (said) {\n const delta = (text ? \"\\n\\n\" : \"\") + said;\n text += delta;\n if (o.onText) try { o.onText({ text, delta }); } catch (_) { /* the page's problem */ }\n }\n const calls = (msg.content || []).filter((b) => b.type === \"tool_use\");\n if (msg.stop_reason !== \"tool_use\" || !calls.length) {\n truncated = msg.stop_reason === \"max_tokens\";\n break;\n }\n messages.push({ role: \"assistant\", content: msg.content });\n const results = await Promise.all(calls.map(async (c) => {\n const tool = (o.tools || []).find((t) => t.name === c.name);\n try {\n if (!tool) throw new Error(\"no tool \" + c.name);\n const out = await tool.execute(c.input || {}, { signal: o.signal });\n const s = typeof out === \"string\" ? out : JSON.stringify(out);\n return { type: \"tool_result\", tool_use_id: c.id, content: s.slice(0, 32768) };\n } catch (e) {\n return { type: \"tool_result\", tool_use_id: c.id, content: \"Error: \" + (e && e.message || e), is_error: true };\n }\n }));\n messages.push({ role: \"user\", content: results });\n if (o.signal && o.signal.aborted) throw fail(\"cancelled\", \"stopped\", text || undefined);\n }\n if (!text.trim()) throw fail(\"empty_completion\", \"Claude wrote nothing\");\n return { text, truncated, modelTierApplied: tier };\n }\n sample.limits = () => Promise.resolve({ maxPromptBytes: 262144, tools: { maxCount: 16 } });\n sample.byok = true;\n sample.hasKey = () => !!store.get(KEY);\n sample.setKey = (k) => { if (k) store.set(KEY, String(k).trim()); else store.del(KEY); };\n return sample;\n }\n\n // an embed has no database nor rooms, but Claude (with the viewer's key) can still make its patch\n window.KairoticGun = { create, sample: makeSample };\n})();\n","kairotic/canvas.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · canvas\n;; A graphic buffer: strokes in a plane. It neither sounds nor advances by itself; it is only a\n;; representation that other components read (kairotic.engine, box `reader`), along X or along Y.\n;;\n;; Two kinds of box share this model:\n;; · canvas — generic: any numeric data. Its axes have a range and a scale (linear or log), strokes\n;; go in any direction, and reading at x (or y) gives every crossing of every stroke.\n;; {:strokes {:t1 {:pts [[x y] ...]}}\n;; :ax {:x {:lo 0 :hi 8 :log false} :y {:lo 0 :hi 1 :log false}}\n;; :gx {:step 0.5 :cycles [4]} :gy {:step 0.1}} ; grids (optional)\n;; (a tree's roll may add :bars [{:s :L :groups}] to :gx: bars of different meters, one by one)\n;; · freqt — frequency over time: no :ax; time goes from 0, frequency is on a log scale, strokes go\n;; forward in time, and :gy can be a tuning {:name \"12-tet\" :cents [100 ... 1200] :ref 261.63}.\n;; It may keep how its score is quantized: :quant {:meter \"6/8\" :divs [1 2 3 4] :fix {2 3} …}\n;; (kairotic.quantize reads it; [:quantize opts] sets it, nil removes it).\n;; Between two points the value is interpolated on the scale of its axis (log → geometric, as pitch).\n\n(ns kairotic.canvas\n (:refer-clojure :exclude [empty cycle])\n (:require [clojure.string :as str]\n [clojure.edn :as edn]))\n\n(def empty {:strokes {} :gx nil :gy nil})\n\n(def default-ax {:x {:lo 0 :hi 8 :log false} :y {:lo 0 :hi 1 :log false}})\n(def generic-empty (assoc empty :ax default-ax))\n\n(defn generic? \"A generic canvas (with axes), not a freqt.\" [d] (map? (:ax d)))\n\n(defn num? [x] (and (number? x) (not (js/isNaN x)) (js/isFinite x)))\n(defn round-to [x d] (let [k (js/Math.pow 10 d)] (/ (js/Math.round (* x k)) k)))\n(defn log2 [x] (/ (js/Math.log x) (js/Math.log 2)))\n\n(defn hz->cents [hz ref] (* 1200 (log2 (/ hz ref))))\n(defn cents->hz [c ref] (* ref (js/Math.pow 2 (/ c 1200))))\n(defn midi->hz [m] (* 440 (js/Math.pow 2 (/ (- m 69) 12))))\n(defn hz->midi [hz] (+ 69 (* 12 (log2 (/ hz 440)))))\n\n(def note-names [\"C\" \"C#\" \"D\" \"D#\" \"E\" \"F\" \"F#\" \"G\" \"G#\" \"A\" \"A#\" \"B\"])\n(defn midi-name [m] (str (nth note-names (mod m 12)) (dec (js/Math.floor (/ m 12)))))\n\n(defn fmt\n \"A short number for code: no trailing zeros.\"\n [x] (let [r (round-to x 3)] (if (= r (js/Math.round r)) (str (js/Math.round r)) (str r))))\n\n;; ───────── tunings (Y grid) ─────────\n;; As in Scala: the degrees in cents above the reference, without the 1/1; the last one is the period.\n\n(defn ratio->cents [s]\n (let [[a b] (str/split (str/trim s) #\"/\")\n a (js/parseFloat a) b (if b (js/parseFloat b) 1)]\n (* 1200 (log2 (/ a b)))))\n\n(defn edo [n period] (vec (for [k (range 1 (inc n))] (round-to (* k (/ period n)) 4))))\n\n(def tunings\n {\"12-tet\" {:name \"12-tet\" :cents (edo 12 1200)}\n \"24-tet\" {:name \"24-tet\" :cents (edo 24 1200)}\n \"19-tet\" {:name \"19-tet\" :cents (edo 19 1200)}\n \"31-tet\" {:name \"31-tet\" :cents (edo 31 1200)}\n \"just-5\" {:name \"just-5\"\n :cents (mapv (fn [r] (round-to (ratio->cents r) 4))\n [\"16/15\" \"9/8\" \"6/5\" \"5/4\" \"4/3\" \"45/32\" \"3/2\" \"8/5\" \"5/3\" \"9/5\" \"15/8\" \"2/1\"])}\n \"pythagorean\" {:name \"pythagorean\"\n :cents (mapv (fn [r] (round-to (ratio->cents r) 4))\n [\"256/243\" \"9/8\" \"32/27\" \"81/64\" \"4/3\" \"729/512\" \"3/2\" \"128/81\" \"27/16\" \"16/9\" \"243/128\" \"2/1\"])}\n \"bohlen-pierce\" {:name \"bohlen-pierce\" :cents (edo 13 1901.955)}})\n\n(def default-ref 261.6256)\n\n(defn parse-scl\n \"Text of a Scala .scl file → {:name :cents}. Lines starting with ! are comments;\n the first useful line is the description, the second the number of degrees; a value with a dot\n is in cents and one without a dot is a ratio (3/2) or an integer (2).\"\n [txt]\n (let [ls (remove (fn [l] (str/starts-with? (str/trim l) \"!\")) (str/split-lines (str txt)))\n [desc nl & more] ls\n n (js/parseInt (str/trim (str nl)) 10)\n vals (take n (keep (fn [l] (let [w (first (str/split (str/trim l) #\"\\s+\"))] (when (seq w) w))) more))\n cents (mapv (fn [v] (if (str/includes? v \".\") (js/parseFloat v) (ratio->cents v))) vals)]\n (when (or (js/isNaN n) (zero? n) (not= n (count cents)) (some (fn [c] (not (num? c))) cents) (not (pos? (peek cents))))\n (throw (js/Error. \"Not a valid .scl: it needs a description, the number of degrees and the degrees (the last one is the period).\")))\n {:name (if (str/blank? desc) \"scala\" (str/trim desc)) :cents (mapv (fn [c] (round-to c 4)) cents)}))\n\n(defn degrees [gy] (vec (cons 0 (butlast (:cents gy)))))\n(defn period [gy] (peek (:cents gy)))\n\n(defn hz->degree\n \"Index of the nearest degree (0 = the reference; it may be negative or go beyond the period).\"\n [gy hz]\n (let [gs (degrees gy) m (count gs) P (period gy)\n c (hz->cents hz (:ref gy))\n k (js/Math.floor (/ c P))\n r (- c (* k P))\n cands (conj gs P)\n i (apply min-key (fn [i] (js/Math.abs (- (nth cands i) r))) (range (count cands)))]\n (+ (* k m) i)))\n\n(defn degree->hz [gy n]\n (let [gs (degrees gy) m (count gs)\n k (js/Math.floor (/ n m))\n i (- n (* k m))]\n (cents->hz (+ (* k (period gy)) (nth gs i)) (:ref gy))))\n\n(defn quantize-f\n \"A value on the Y grid: the nearest degree of a tuning, or the nearest multiple of a regular step.\"\n [gy v]\n (cond (nil? gy) v\n (:cents gy) (degree->hz gy (hz->degree gy v))\n (:step gy) (round-to (* (:step gy) (js/Math.round (/ v (:step gy)))) 6)\n :else v))\n\n;; ───────── X grid ─────────\n\n(defn cycle [gx] (reduce + (or (seq (:cycles gx)) [4])))\n(defn step-x [gx] (or (:step gx) 0.25))\n(defn quantize-t [gx t] (if gx (let [p (:step gx)] (round-to (* p (js/Math.round (/ t p))) 6)) t))\n\n(defn parse-cycles\n \"[4], 4, \\\"3+3+2\\\" or [3 3 2] → vector of group durations (in time units).\"\n [x]\n (cond (num? x) [x]\n (string? x) (vec (keep (fn [s] (let [n (js/parseFloat s)] (when (num? n) n))) (str/split x #\"\\+\")))\n (sequential? x) (vec (filter num? x))\n :else []))\n\n;; ───────── model ─────────\n\n(defn sane-pts [pts]\n (when (sequential? pts)\n (let [ps (->> pts\n (filter (fn [p] (and (sequential? p) (= 2 (count p)) (num? (first p)) (num? (second p))\n (>= (first p) 0) (< 1 (second p) 30000))))\n (map (fn [[t f]] [(round-to t 4) (round-to f 3)]))\n (sort-by first)\n vec)]\n (when (and (>= (count ps) 2) (> (first (peek ps)) (first (first ps)))) ps))))\n\n(defn sane-gx [gx]\n (when (map? gx)\n (let [p (:step gx) cs (filter (fn [c] (and (num? c) (pos? c))) (parse-cycles (:cycles gx)))]\n (when (and (num? p) (> p 0.001))\n {:step p :cycles (vec cs)}))))\n\n(defn sane-gy [gy]\n (when (map? gy)\n (if (and (nil? (:cents gy)) (num? (:step gy)) (pos? (:step gy)))\n {:step (:step gy)}\n (let [cs (:cents gy) ref (:ref gy)]\n (when (and (sequential? cs) (seq cs) (every? num? cs) (pos? (peek (vec cs))) (< (count cs) 400))\n {:name (str (or (:name gy) \"scale\")) :cents (vec cs) :ref (if (and (num? ref) (< 1 ref 20000)) ref default-ref)})))))\n\n(def quant-keys [:meter :groups :key :divs :merge :nest :grace :legato :chord :voices :overlap :tempo :w :fix :spell :time :meters])\n\n(defn sane-quant\n \"How a freqt's score is quantized, as kept in its buffer: only the keys kairotic.quantize reads (their\n values are checked there), nil when there are none.\"\n [q]\n (when (map? q) (not-empty (into {} (filter (fn [[k v]] (some? v)) (select-keys q quant-keys))))))\n\n(defn sane-axis [a dflt]\n (let [a (if (map? a) a {}) lo (:lo a) hi (:hi a) log? (boolean (:log a))]\n (if (and (num? lo) (num? hi) (< lo hi) (or (not log?) (pos? lo)))\n {:lo lo :hi hi :log log?}\n dflt)))\n\n(defn sane-ax [ax]\n (when (map? ax)\n {:x (sane-axis (:x ax) (:x default-ax)) :y (sane-axis (:y ax) (:y default-ax))}))\n\n(defn x-log? [d] (and (generic? d) (boolean (get-in d [:ax :x :log]))))\n(defn y-log? [d] (if (generic? d) (boolean (get-in d [:ax :y :log])) true))\n\n(defn sane-free-pts\n \"Points of a stroke of a generic canvas: any direction, at least two different points.\"\n [d pts]\n (when (sequential? pts)\n (let [ps (->> pts\n (filter (fn [p] (and (sequential? p) (= 2 (count p)) (num? (first p)) (num? (second p))\n (or (not (x-log? d)) (pos? (first p)))\n (or (not (y-log? d)) (pos? (second p))))))\n (map (fn [[x y]] [(round-to x 4) (round-to y 4)]))\n dedupe\n vec)]\n (when (>= (count ps) 2) ps))))\n\n(defn sane-pts-for \"The right points check for this canvas.\" [d pts]\n (if (generic? d) (sane-free-pts d pts) (sane-pts pts)))\n\n;; How a stroke looks, beyond its points (what a render of a pattern draws, discussion #93):\n;; {:w 1.5} its weight, times the usual (0.25…4): an event's :amp\n;; {:pan -0.6} a vertical gradient across it, from its colour to the paper (−1…1): an event's :pan\n;; {:tex :dash} :dash or :dot, a texture {:tone :kairos} :kairos, :ink or :soft, a colour\n;; Plain data, kept in the history and in links like the points; a stroke without it looks as always.\n(def look-texes #{:dash :dot})\n(def look-tones #{:kairos :ink :soft})\n\n(defn sane-look\n \"The look of a stroke, with only what can be drawn; nil when there is nothing to draw differently.\"\n [l]\n (when (map? l)\n (let [w (:w l) pan (:pan l)\n r (cond-> {}\n (and (num? w) (not (== w 1))) (assoc :w (round-to (max 0.25 (min 4 w)) 3))\n (and (num? pan) (not (zero? pan))) (assoc :pan (round-to (max -1 (min 1 pan)) 3))\n (look-texes (:tex l)) (assoc :tex (:tex l))\n (look-tones (:tone l)) (assoc :tone (:tone l)))]\n (when (seq r) r))))\n\n(defn with-look \"A stroke {:pts …} with look l, if it has one.\" [s l] (if-let [l (sane-look l)] (assoc s :look l) s))\n\n(defn shift-y\n \"A value moved by dy: in cents on a log axis, added on a linear one.\"\n [d v dy] (if (y-log? d) (* v (js/Math.pow 2 (/ dy 1200))) (+ v dy)))\n\n(defn delta-y\n \"How far b is from a, in the units of shift-y.\"\n [d b a] (if (y-log? d) (hz->cents b a) (- b a)))\n\n(defn transform [d pts f] (sane-pts-for d (mapv f pts)))\n\n(defn step\n \"Data + event → data. Every change to a canvas goes through here.\"\n [d [op & args]]\n (let [d (or d empty)]\n (case op\n :stroke (let [[id pts look] args ps (sane-pts-for d pts)]\n (if (and (keyword? id) ps) (assoc-in d [:strokes id] (with-look {:pts ps} look)) d))\n ;; [:move id dx dy]: dy in cents on a log axis (freqt), in units on a linear one\n :move (let [[id dt dc] args pts (get-in d [:strokes id :pts])]\n (if (and pts (num? dt) (num? dc))\n (let [dt (if (generic? d) dt (max dt (- (ffirst pts))))]\n (if-let [ps (transform d pts (fn [[t f]] [(+ t dt) (shift-y d f dc)]))] (assoc-in d [:strokes id :pts] ps) d))\n d))\n :stretch (let [[id k] args pts (get-in d [:strokes id :pts])]\n (if (and pts (num? k) (pos? k))\n (let [t0 (ffirst pts)]\n (if-let [ps (transform d pts (fn [[t f]] [(+ t0 (* k (- t t0))) f]))] (assoc-in d [:strokes id :pts] ps) d))\n d))\n :erase (update d :strokes dissoc (first args))\n ;; several edits as one event (what a message on the inlet of a canvas makes, issue #26)\n :batch (reduce step d (filter vector? (first args)))\n :clear (assoc d :strokes {})\n :grid-x (assoc d :gx (sane-gx (first args)))\n :tuning (assoc d :gy (sane-gy (first args)))\n :grid-y (assoc d :gy (sane-gy (first args)))\n :quantize (if-let [q (sane-quant (first args))] (assoc d :quant q) (dissoc d :quant))\n :axis (if (generic? d) (assoc d :ax (sane-ax (first args))) d)\n :load (let [[x] args]\n (if (map? x)\n (let [base (cond-> {:gx (sane-gx (:gx x)) :gy (sane-gy (:gy x))}\n (or (generic? d) (map? (:ax x))) (assoc :ax (or (sane-ax (:ax x)) default-ax))\n (sane-quant (:quant x)) (assoc :quant (sane-quant (:quant x))))]\n (assoc base :strokes (into {} (for [[k s] (:strokes x)\n :let [ps (and (keyword? k) (map? s) (sane-pts-for base (:pts s)))] :when ps]\n [k (with-look {:pts ps} (:look s))]))))\n d))\n d)))\n\n(defn id-num [k] (let [m (re-matches #\"t(\\d+)\" (name k))] (if m (js/parseInt (second m) 10) 1e9)))\n\n(defn next-id [d]\n (let [ns-ids (keep (fn [k] (let [n (id-num k)] (when (< n 1e9) n))) (keys (:strokes d)))]\n (keyword (str \"t\" (inc (if (seq ns-ids) (apply max ns-ids) 0))))))\n\n(defn sorted-strokes [d] (sort-by (fn [[id s]] [(ffirst (:pts s)) (id-num id)]) (:strokes d)))\n\n(defn clip-out\n \"The pieces of polyline pts that lie outside the open window t1 < x < t2 (t2 nil: no end), each a vector\n of points, in order. A segment that crosses an edge is cut there, its value interpolated on the scale\n of the Y axis (geometric when ylog, as pitch).\"\n [pts t1 t2 ylog]\n (let [inside? (fn [x] (and (> x t1) (or (nil? t2) (< x t2))))\n at (fn [[xa ya] [xb yb] u]\n [(+ xa (* u (- xb xa)))\n (if (and ylog (pos? ya) (pos? yb)) (* ya (js/Math.pow (/ yb ya) u)) (+ ya (* u (- yb ya))))])\n ;; the params (0…1) where segment a→b crosses x = t1 or x = t2\n cuts (fn [[xa :as a] [xb :as b]]\n (if (= xa xb)\n []\n (sort (filter (fn [u] (< 0 u 1)) (map (fn [t] (/ (- t xa) (- xb xa))) (remove nil? [t1 t2]))))))\n close (fn [acc cur] (if (>= (count cur) 2) (conj acc cur) acc))]\n (loop [[a b & more] pts acc [] cur (if (and (seq pts) (not (inside? (ffirst pts)))) [(first pts)] [])]\n (if (nil? b)\n (close acc cur)\n (let [us (concat [0] (cuts a b) [1])\n ;; each piece of the segment, with whether its middle is outside the window\n [acc cur] (reduce (fn [[acc cur] [u0 u1]]\n (let [p0 (at a b u0) p1 (at a b u1)\n out (not (inside? (first (at a b (/ (+ u0 u1) 2)))))]\n (if out\n [acc (conj (if (seq cur) cur [p0]) p1)]\n [(close acc cur) []])))\n [acc cur] (partition 2 1 us))]\n (recur (cons b more) acc cur))))))\n\n(defn cut-events\n \"The events that remove what buffer d holds between times (x) t1 and t2 (t2 nil: to the end): strokes\n inside are erased, those that cross an edge end or begin there, and one that spans the window is split\n in two (the part after it is a new stroke). What a take that records over a buffer writes (rec t, ovr).\"\n ([d t] (cut-events d t nil))\n ([d t1 t2]\n (let [ylog (y-log? d)\n valid (fn [ps] (and (>= (count ps) 2) (or (generic? d) (> (first (peek ps)) (first (first ps))))))]\n (first\n (reduce (fn [[evs d] [id s]]\n (let [pts (:pts s)\n touched (some (fn [[x]] (and (> x t1) (or (nil? t2) (< x t2)))) pts)\n crosses (some (fn [[[xa] [xb]]] (< (min xa xb) t1 (max xa xb))) (partition 2 1 pts))\n crosses2 (and t2 (some (fn [[[xa] [xb]]] (< (min xa xb) t2 (max xa xb))) (partition 2 1 pts)))]\n (if-not (or touched crosses crosses2)\n [evs d]\n (let [pieces (filter valid (map (fn [ps] (mapv (fn [[x y]] [(round-to x 4) (round-to y 4)]) ps))\n (clip-out pts t1 t2 ylog)))\n es (if (empty? pieces)\n [[:erase id]]\n (into [[:stroke id (first pieces)]]\n (second (reduce (fn [[d es] ps] (let [nid (next-id d) e [:stroke nid ps]] [(step d e) (conj es e)]))\n [(step d [:stroke id (first pieces)]) []] (rest pieces)))))]\n [(into evs es) (reduce step d es)]))))\n [[] d] (sorted-strokes d))))))\n\n(defn end-t [d] (reduce max 0 (map (fn [s] (apply max (map first (:pts s)))) (vals (:strokes d)))))\n\n;; ───────── reading ─────────\n;; Reading at x = v (or y = v) gives, for each stroke, the other coordinate wherever the stroke\n;; crosses that line. A segment counts from its start up to, not including, its end, so a stroke\n;; going forward has an open end (as before) and a turning point is counted once.\n\n(defn axis-u [log? v] (if log? (log2 v) v))\n(defn axis-v [log? u] (if log? (js/Math.pow 2 u) u))\n\n(defn crossings\n \"Values of the other coordinate where the polyline pts crosses coordinate k (0 = x, 1 = y) = v.\"\n [pts k v logs]\n (let [o (- 1 k) lk (nth logs k) lo (nth logs o)\n uv (axis-u lk v)]\n (vec (keep (fn [[a b]]\n (let [ca (axis-u lk (nth a k)) cb (axis-u lk (nth b k))]\n (when (or (and (< ca cb) (<= ca uv) (< uv cb))\n (and (> ca cb) (< cb uv) (<= uv ca)))\n (let [r (/ (- uv ca) (- cb ca))\n oa (axis-u lo (nth a o)) ob (axis-u lo (nth b o))]\n (axis-v lo (+ oa (* r (- ob oa))))))))\n (partition 2 1 pts)))))\n\n(defn read-along\n \"Everything a canvas holds at x = v (axis :x) or y = v (axis :y): [[id value] ...] in stroke order.\n A stroke that crosses more than once gives :t1, :t1-2, :t1-3 …\"\n [d axis v]\n (let [logs [(x-log? d) (y-log? d)] k (if (= axis :y) 1 0)]\n (vec (mapcat (fn [[id s]]\n (map-indexed (fn [i val] [(if (zero? i) id (keyword (str (name id) \"-\" (inc i)))) val])\n (crossings (:pts s) k v logs)))\n (sorted-strokes d)))))\n\n(defn read-at \"Everything that sounds at time t (reading along X).\" [d t] (read-along d :x t))\n\n;; ───────── trajectories ─────────\n;; A stroke can also be read as a path: position u from 0 to 1 along it, in the order it was drawn,\n;; proportionally to its length as it is seen (each axis on its own scale, both of the same size).\n\n(declare ranges)\n\n(defn stroke-for\n \"The points of stroke `sid` (a keyword), or of the first stroke if sid is nil or not there.\"\n [d sid]\n (or (when sid (get-in d [:strokes sid :pts]))\n (:pts (second (first (sorted-strokes d))))))\n\n(defn point-along\n \"The point [x y] at fraction u (0…1) of the length of a path.\"\n [d pts u]\n (when (>= (count pts) 2)\n (let [{:keys [xa xb ya yb xlog ylog]} (ranges d)\n nx (fn [x] (/ (- (axis-u xlog x) (axis-u xlog xa)) (- (axis-u xlog xb) (axis-u xlog xa))))\n ny (fn [y] (/ (- (axis-u ylog y) (axis-u ylog ya)) (- (axis-u ylog yb) (axis-u ylog ya))))\n segs (map (fn [[a b]] [a b (js/Math.hypot (- (nx (first b)) (nx (first a))) (- (ny (second b)) (ny (second a))))])\n (partition 2 1 pts))\n total (reduce + (map #(nth % 2) segs))\n target (* (max 0 (min 1 u)) total)]\n (if (zero? total)\n (first pts)\n (loop [[[a b len] & more] segs acc 0]\n (if (or (empty? more) (<= target (+ acc len)))\n (let [r (if (pos? len) (max 0 (min 1 (/ (- target acc) len))) 0)\n lerp (fn [log? p q] (axis-v log? (+ (axis-u log? p) (* r (- (axis-u log? q) (axis-u log? p))))))]\n [(lerp xlog (first a) (first b)) (lerp ylog (second a) (second b))])\n (recur more (+ acc len))))))))\n\n(defn x-range\n \"The span read along X by a position from 0 to 1: the X axis of a canvas, or 0 … end of a freqt.\"\n [d]\n (if (generic? d)\n (let [{:keys [lo hi log]} (get-in d [:ax :x])] [lo hi (boolean log)])\n [0 (max 1e-6 (end-t d)) false]))\n\n(defn y-range\n \"The span read along Y: the Y axis of a canvas, or the lowest … highest frequency of a freqt.\"\n [d]\n (if (generic? d)\n (let [{:keys [lo hi log]} (get-in d [:ax :y])] [lo hi (boolean log)])\n (let [fs (map second (mapcat :pts (vals (:strokes d))))]\n (if (seq fs) [(apply min fs) (max (+ (apply min fs) 1e-6) (apply max fs)) true] [100 1000 true]))))\n\n(defn at-unit\n \"The value at fraction u of a span [lo hi log?].\"\n [[lo hi log?] u] (axis-v log? (+ (axis-u log? lo) (* u (- (axis-u log? hi) (axis-u log? lo))))))\n\n(defn value-at\n \"Value of a stroke at x = t, or nil if it does not pass there (the end is open).\"\n [pts t] (first (crossings pts 0 t [false true])))\n\n;; ───────── geometry and drawing ─────────\n\n(def W 420)\n(def H 200)\n(def x0 40)\n\n(defn f-range [d]\n (let [ps (mapcat :pts (vals (:strokes d)))\n L (cycle (:gx d))\n T0 (if (seq ps) (apply max (map first ps)) 0)\n T (* L (max 2 (inc (js/Math.ceil (/ T0 L)))))\n fs (map second ps)\n [lo hi] (if (seq fs) [(apply min fs) (apply max fs)] [220 880])\n clo (- (log2 lo) 0.3) chi (+ (log2 hi) 0.3)\n span (max 1.6 (- chi clo)) mid (/ (+ clo chi) 2)]\n {:T T :lf0 (- mid (/ span 2)) :lf1 (+ mid (/ span 2))}))\n\n(defn ranges\n \"What the box shows: x from xa to xb and y from ya to yb, each on its scale.\"\n [d]\n (if (generic? d)\n (let [{:keys [x y]} (:ax d)]\n {:xa (:lo x) :xb (:hi x) :xlog (:log x) :ya (:lo y) :yb (:hi y) :ylog (:log y) :T (:hi x)})\n (let [{:keys [T lf0 lf1]} (f-range d)]\n {:xa 0 :xb T :xlog false :ya (js/Math.pow 2 lf0) :yb (js/Math.pow 2 lf1) :ylog true :T T :lf0 lf0 :lf1 lf1})))\n\n(defn geom\n \"Where a canvas box draws its data: in a box of W × H, or of the size it was given (issue #40).\"\n ([d hdr] (geom d hdr nil))\n ([d hdr [bw bh]]\n (let [y0 (+ hdr 3) bw (or bw W) bh (or bh H)]\n (merge (ranges d) {:x0 x0 :y0 y0 :w (- bw x0 6) :h (- bh y0 6)}))))\n\n(defn t->x [g t]\n (let [a (axis-u (:xlog g) (:xa g)) b (axis-u (:xlog g) (:xb g))]\n (+ (:x0 g) (* (/ (- (axis-u (:xlog g) t) a) (- b a)) (:w g)))))\n(defn x->t [g x]\n (let [a (axis-u (:xlog g) (:xa g)) b (axis-u (:xlog g) (:xb g))]\n (axis-v (:xlog g) (+ a (* (/ (- x (:x0 g)) (:w g)) (- b a))))))\n(defn f->y [g f]\n (let [a (axis-u (:ylog g) (:ya g)) b (axis-u (:ylog g) (:yb g))]\n (+ (:y0 g) (* (/ (- b (axis-u (:ylog g) f)) (- b a)) (:h g)))))\n(defn y->f [g y]\n (let [a (axis-u (:ylog g) (:ya g)) b (axis-u (:ylog g) (:yb g))]\n (axis-v (:ylog g) (- b (* (/ (- y (:y0 g)) (:h g)) (- b a))))))\n\n(defn nice-step\n \"A round step (1, 2 or 5 × 10^k) that cuts span into about n parts.\"\n [span n]\n (let [raw (/ span (max 1 n)) k (js/Math.pow 10 (js/Math.floor (/ (js/Math.log raw) (js/Math.log 10))))\n m (/ raw k)]\n (* k (cond (< m 1.5) 1 (< m 3.5) 2 (< m 7.5) 5 :else 10))))\n\n(defn ticks\n \"[[v level label]] every nice step between a and b.\"\n [a b n]\n (let [p (nice-step (- b a) n)]\n (for [k (range (js/Math.ceil (/ a p)) (inc (js/Math.floor (/ b p))))\n :let [v (round-to (* k p) 6)]]\n [v (if (zero? v) 1 0) (fmt v)])))\n\n(defn bar-lines\n \"[[t level label]] of bars given one by one (a tree whose measures change meter): [{:s start :L length\n :groups [lengths]}]. Past the last one, it goes on in its meter.\"\n [bars a T]\n (let [lst (last bars)\n more (when (pos? (:L lst))\n (map (fn [i] (assoc lst :s (+ (:s lst) (* (:L lst) i))))\n (range 1 (inc (max 0 (js/Math.ceil (/ (- T (:s lst)) (:L lst))))))))]\n (for [[i {:keys [s L groups]}] (map-indexed vector (concat bars more))\n :when (<= (- a L) s T)\n [b level] (cons [0 2] (map (fn [b] [b 1]) (butlast (rest (reductions + 0 (or (seq groups) [L]))))))\n :let [t (+ s b)] :when (<= a t T)]\n [t level (when (= level 2) (inc i))])))\n\n(defn lines-x\n \"[[t level label]]: level 0 = step, 1 = group, 2 = start of cycle.\"\n [gx g]\n (let [a (:xa g) T (:xb g) px-per-unit (/ (:w g) (- T a))]\n (cond\n (and (not gx) (or (:xlog g) (not= a 0) (not (:lf0 g))))\n (if (:xlog g)\n (for [k (range (js/Math.ceil (log2 a)) (inc (js/Math.floor (log2 T)))) :let [v (js/Math.pow 2 k)]] [v 1 (fmt v)])\n (ticks a T 8))\n (not gx)\n (for [t (range 0 (inc T))] [t (if (zero? (mod t 4)) 1 0) nil])\n :else\n (let [p (:step gx) cs (or (seq (:cycles gx)) [4]) L (reduce + cs)\n bounds (butlast (reductions + 0 cs))\n steps (when (>= (* p px-per-unit) 5)\n (for [k (range (js/Math.ceil (/ a p)) (inc (js/Math.floor (/ T p))))] [(* k p) 0 nil]))]\n (concat steps\n (if-let [bars (seq (:bars gx))]\n (bar-lines bars a T)\n (for [c (range (js/Math.floor (/ a L)) (inc (js/Math.floor (/ T L)))) b bounds\n :let [t (+ (* c L) b)] :when (<= a t T)]\n [t (if (zero? b) 2 1) (when (zero? b) (inc c))])))))))\n\n(defn lines-y\n \"[[hz level label]] within the visible range.\"\n [gy g]\n (let [f0 (:ya g) f1 (:yb g)]\n (cond\n (and (:step gy) (not (:cents gy)))\n (let [p (:step gy) n (/ (- f1 f0) p) every (max 1 (js/Math.ceil (/ n (/ (:h g) 14))))]\n (for [k (range (js/Math.ceil (/ f0 p)) (inc (js/Math.floor (/ f1 p))))\n :let [v (round-to (* k p) 6)]]\n [v (if (zero? (mod k every)) 1 0) (when (zero? (mod k every)) (fmt v))]))\n (and (not gy) (not (:ylog g)))\n (ticks f0 f1 6)\n (not gy)\n (for [k (range (js/Math.ceil (log2 (/ f0 55))) (inc (js/Math.floor (log2 (/ f1 55)))))\n :let [f (* 55 (js/Math.pow 2 k))]]\n [f 1 (str (round-to f 1))])\n :else\n (let [m (count (degrees gy)) a (hz->degree gy f0) b (hz->degree gy f1)\n dense? (> (/ (- b a) (max 1 (/ (:h g) 3.5))) 1)\n tet12? (= (:cents gy) (:cents (get tunings \"12-tet\")))]\n (for [n (range (dec a) (+ b 2))\n :let [f (degree->hz gy n) start? (zero? (mod n m))]\n :when (and (<= f0 f f1) (or start? (not dense?)))]\n [f (if start? 1 0)\n (when start?\n (if (and tet12? (< (js/Math.abs (- (:ref gy) default-ref)) 0.01))\n (midi-name (js/Math.round (hz->midi f)))\n (str (round-to f 1))))])))))\n\n(defn path-d [g pts]\n (str/join \" \" (map-indexed (fn [i [t f]] (str (if (zero? i) \"M\" \"L\") (round-to (t->x g t) 2) \" \" (round-to (f->y g f) 2))) pts)))\n\n(defn look-path\n \"The drawn path of a stroke, with its look (weight, gradient, texture, colour; discussion #93).\"\n [idn ids g pts dd look sel?]\n (let [{:keys [w pan tex tone]} look\n width (* 3 (or w 1))\n colour (if sel? \"var(--kairos)\" (case tone :kairos \"var(--kairos)\" :ink \"var(--ink)\" :soft \"var(--ink-soft)\" \"var(--accent)\"))\n gid (str \"lk-\" idn \"-\" ids)\n grad (when (and pan (not sel?))\n (let [ys (map (fn [[_ f]] (f->y g f)) pts)\n y0 (- (apply min ys) (/ width 2)) y1 (+ (apply max ys) (/ width 2))\n faded (str \"color-mix(in srgb, \" colour \", var(--paper) \" (js/Math.round (* 75 (js/Math.abs pan))) \"%)\")\n [top bottom] (if (neg? pan) [colour faded] [faded colour])]\n (str \"<defs><linearGradient id=\\\"\" gid \"\\\" gradientUnits=\\\"userSpaceOnUse\\\" x1=\\\"0\\\" x2=\\\"0\\\" y1=\\\"\" (round-to y0 2)\n \"\\\" y2=\\\"\" (round-to (+ y1 0.01) 2) \"\\\"><stop offset=\\\"0\\\" style=\\\"stop-color:\" top \"\\\"></stop>\"\n \"<stop offset=\\\"1\\\" style=\\\"stop-color:\" bottom \"\\\"></stop></linearGradient></defs>\")))\n style (str (when (or w (:w look)) (str \"stroke-width:\" (round-to (if sel? (+ width 0.5) width) 2) \";\"))\n (cond grad (str \"stroke:url(#\" gid \");\")\n (and tone (not sel?)) (str \"stroke:\" colour \";\"))\n (case tex :dash (str \"stroke-dasharray:\" (round-to (* 2 width) 1) \" \" (round-to (* 1.4 width) 1) \";\")\n :dot (str \"stroke-dasharray:0.1 \" (round-to (* 2 width) 1) \";\") nil))]\n (str grad \"<path class=\\\"stroke\" (when sel? \" sel\") \"\\\" d=\\\"\" dd \"\\\"\" (when (seq style) (str \" style=\\\"\" style \"\\\"\")) \"></path>\")))\n\n(defn svg\n \"SVG of the contents of a canvas box. `idn` is the box id (text), `sel` the selected stroke,\n `previews` {id pts} to draw a drag in progress and `new-pts` the points of a stroke being drawn.\"\n [idn d g sel previews new-pts]\n (let [{:keys [x0 y0 w h]} g]\n (str \"<rect class=\\\"lbg mus-body\\\" data-box=\\\"\" idn \"\\\" x=\\\"\" x0 \"\\\" y=\\\"\" y0 \"\\\" width=\\\"\" w \"\\\" height=\\\"\" h \"\\\"></rect>\"\n \"<svg x=\\\"0\\\" y=\\\"\" y0 \"\\\" width=\\\"\" (+ x0 w) \"\\\" height=\\\"\" h \"\\\" overflow=\\\"hidden\\\" pointer-events=\\\"none\\\">\"\n \"<g transform=\\\"translate(0,\" (- y0) \")\\\">\"\n (apply str (for [[f level label] (lines-y (:gy d) g) :let [y (round-to (f->y g f) 2)]]\n (str \"<line class=\\\"lgy\" level \"\\\" x1=\\\"\" x0 \"\\\" x2=\\\"\" (+ x0 w) \"\\\" y1=\\\"\" y \"\\\" y2=\\\"\" y \"\\\"></line>\"\n (when label (str \"<text class=\\\"rlabel\\\" x=\\\"4\\\" y=\\\"\" (+ y 3) \"\\\">\" label \"</text>\")))))\n (apply str (for [[t level label] (lines-x (:gx d) g) :let [x (round-to (t->x g t) 2)]]\n (str \"<line class=\\\"lgx\" level \"\\\" x1=\\\"\" x \"\\\" x2=\\\"\" x \"\\\" y1=\\\"\" y0 \"\\\" y2=\\\"\" (+ y0 h) \"\\\"></line>\"\n (when label (str \"<text class=\\\"rlabel\\\" x=\\\"\" (+ x 3) \"\\\" y=\\\"\" (+ y0 9) \"\\\">\" label \"</text>\")))))\n \"</g></svg>\"\n (apply str (for [[id s] (:strokes d)\n :let [pts (or (get previews id) (:pts s)) dd (path-d g pts) ids (name id)]]\n (str (look-path idn ids g pts dd (:look s) (= sel id))\n \"<path class=\\\"stroke-hit\\\" data-box=\\\"\" idn \"\\\" data-stroke=\\\"\" ids \"\\\" d=\\\"\" dd \"\\\"><title>\"\n ids \" · \" (fmt (ffirst pts)) \"→\" (fmt (first (peek pts))) \" · \" (fmt (second (first pts)))\n (when-not (generic? d) \" Hz\") \"</title></path>\")))\n (when (and new-pts (>= (count new-pts) 2))\n (str \"<path class=\\\"stroke new\\\" d=\\\"\" (path-d g new-pts) \"\\\"></path>\")))))\n\n(defn summary [d]\n (if (generic? d)\n (let [{:keys [x y]} (:ax d) rng (fn [a] (str (fmt (:lo a)) \"…\" (fmt (:hi a)) (when (:log a) \" log\")))]\n (str \"x \" (rng x) \" · y \" (rng y) \" · \" (count (:strokes d)) \" strokes\"))\n (str (if-let [gy (:gy d)] (:name gy) \"continuous Hz\")\n \" · \" (if-let [gx (:gx d)] (str \"step \" (fmt (:step gx)) \" · cycle \" (str/join \"+\" (map fmt (or (seq (:cycles gx)) [4])))) \"free time\")\n \" · \" (count (:strokes d)) \" strokes\")))\n\n;; ───────── projections ─────────\n\n(defn ->code\n \"Lines of code that rebuild the canvas of box `id`.\"\n [id d]\n (concat\n (when (and (generic? d) (not= (:ax d) default-ax))\n (for [k [:x :y] :let [a (get-in d [:ax k])] :when (not= a (get default-ax k))]\n (str \"(axis \" id \" \" k \" \" (fmt (:lo a)) \" \" (fmt (:hi a)) (when (:log a) \" :log\") \")\")))\n (when-let [gy (and (:step (:gy d)) (not (:cents (:gy d))) (:gy d))]\n [(str \"(grid-y \" id \" \" (fmt (:step gy)) \")\")])\n (when-let [gy (and (:cents (:gy d)) (:gy d))]\n (let [preset (some (fn [[k v]] (when (= (:cents v) (:cents gy)) k)) tunings)]\n [(str \"(tuning \" id \" \" (if preset (pr-str preset) (pr-str {:name (:name gy) :cents (:cents gy)})) \" \" (fmt (:ref gy)) \")\")]))\n (when-let [gx (:gx d)]\n [(str \"(grid-x \" id \" \" (fmt (:step gx)) \" \" (pr-str (mapv (fn [c] (js/parseFloat (fmt c))) (:cycles gx))) \")\")])\n (for [[sid s] (sorted-strokes d)]\n (str \"(stroke \" id \" \" sid \" [\" (str/join \" \" (map (fn [[t f]] (str \"[\" (fmt t) \" \" (fmt f) \"]\")) (:pts s))) \"]\"\n (when (:look s) (str \" \" (pr-str (:look s)))) \")\"))))\n\n;; ───────── the buffer as text (discussion #30) ─────────\n;; Any buffer can be read and edited as EDN, in the same code window as a code box: ->source writes it,\n;; read-source takes the text back (checking it), and diff turns the change into the events of the\n;; buffer, so applying the text is one event of the history made of what really changed.\n;; {:gx {:step 0.25 :cycles [4]}\n;; :gy {:name \"12-tet\" :ref 261.6256} ; a tuning by name: its cents come from `tunings`\n;; :strokes {:t1 [[0 440] [1 440]]\n;; :t2 [[1 330] [2 330]]}}\n;; A generic canvas also has :ax {:x {:lo 0 :hi 8 :log false} :y {…}}.\n\n(defn- num-src [x] (if (== x (js/Math.round x)) (str (js/Math.round x)) (str x)))\n\n(defn- pts-src [pts] (str \"[\" (str/join \" \" (map (fn [[a b]] (str \"[\" (num-src a) \" \" (num-src b) \"]\")) pts)) \"]\"))\n\n(defn- preset-of [gy] (some (fn [[k v]] (when (= (:cents v) (:cents gy)) k)) tunings))\n\n(defn- gy-src [gy]\n (cond (nil? gy) \"nil\"\n (:step gy) (str \"{:step \" (num-src (:step gy)) \"}\")\n (preset-of gy) (str \"{:name \" (pr-str (preset-of gy)) \" :ref \" (num-src (:ref gy)) \"}\")\n :else (str \"{:name \" (pr-str (:name gy)) \" :ref \" (num-src (:ref gy))\n \" :cents [\" (str/join \" \" (map num-src (:cents gy))) \"]}\")))\n\n(defn- gx-src [gx]\n (if (nil? gx) \"nil\" (str \"{:step \" (num-src (:step gx)) \" :cycles [\" (str/join \" \" (map num-src (:cycles gx))) \"]}\")))\n\n(defn- ax-src [ax]\n (let [a (fn [{:keys [lo hi log]}] (str \"{:lo \" (num-src lo) \" :hi \" (num-src hi) \" :log \" (boolean log) \"}\"))]\n (str \"{:x \" (a (:x ax)) \"\\n :y \" (a (:y ax)) \"}\")))\n\n(defn ->source\n \"The buffer as EDN text, one stroke per line (read-source reads it back).\"\n [d]\n (let [d (or d empty)\n ss (sorted-strokes d)]\n (str \"{\" (when (generic? d) (str \":ax \" (ax-src (:ax d)) \"\\n \"))\n \":gx \" (gx-src (:gx d)) \"\\n\"\n \" :gy \" (gy-src (:gy d)) \"\\n\"\n (when (:quant d) (str \" :quant \" (pr-str (:quant d)) \"\\n\"))\n \" :strokes {\" (str/join \"\\n \" (map (fn [[id s]] (str id \" \" (if (:look s)\n (str \"{:pts \" (pts-src (:pts s)) \" :look \" (pr-str (:look s)) \"}\")\n (pts-src (:pts s)))))\n ss)) \"}}\")))\n\n(defn- bad [msg] (throw (js/Error. msg)))\n\n(defn read-source\n \"EDN text → a buffer of the kind of `d` (a generic canvas or a freqt). Nothing is evaluated. Throws,\n saying what is wrong, rather than dropping what it cannot read.\"\n [d text]\n (let [forms (try (edn/read-string (str \"[\" text \"\\n]\")) (catch :default e (bad (str \"That is not EDN: \" (.-message e)))))\n _ (when (not= 1 (count forms))\n (bad (if (empty? forms) \"The text is empty: a buffer is a map {:strokes {…} :gx nil :gy nil}\"\n (str \"One map only: there is more after it (\" (pr-str (second forms)) \")\"))))\n x (first forms)\n gen (generic? (or d empty))]\n (when-not (map? x) (bad \"A buffer is a map: {:strokes {:t1 [[0 440] [1 440]]} :gx nil :gy nil}\"))\n (when-let [k (first (remove #{:strokes :gx :gy :ax :quant} (keys x)))]\n (bad (str \"Unknown key \" (pr-str k) \": a buffer has :strokes, :gx, :gy\" (if gen \" and :ax\" \" and :quant\"))))\n (when (and gen (some? (:quant x))) (bad \"A canvas has no :quant: only a freqt is quantized into a score\"))\n (when (and (some? (:quant x)) (not (map? (:quant x)))) (bad \":quant is a map of options: {:meter \\\"6/8\\\" :divs [1 2 3 4]}\"))\n (when (and (not gen) (some? (:ax x))) (bad \"A freqt has no :ax: its axes are time and frequency\"))\n (let [ax (when gen (if (some? (:ax x))\n (let [a (sane-ax (:ax x))]\n (when-not (and a (every? (fn [k] (let [i (get-in x [:ax k])]\n (or (nil? i) (= (get a k) {:lo (:lo i) :hi (:hi i) :log (boolean (:log i))}))))\n [:x :y]))\n (bad \":ax is {:x {:lo 0 :hi 8 :log false} :y {:lo 0 :hi 1 :log false}} (lo < hi; both positive if :log)\"))\n a)\n default-ax))\n base (cond-> {:strokes {}} gen (assoc :ax ax))\n gx (when (some? (:gx x)) (or (sane-gx (:gx x)) (bad \":gx is {:step 0.25 :cycles [4]} (or nil)\")))\n gy0 (:gy x)\n gy0 (if-let [t (and (map? gy0) (nil? (:cents gy0)) (nil? (:step gy0)) (string? (:name gy0))\n (get tunings (str/lower-case (:name gy0))))]\n (assoc t :ref (:ref gy0))\n gy0)\n gy (when (some? gy0) (or (sane-gy gy0) (bad (str \":gy is a tuning {:name \\\"12-tet\\\" :ref 261.63} (a name from \"\n (str/join \", \" (sort (keys tunings))) \", or with :cents), a grid {:step 0.1}, or nil\"))))\n ss (:strokes x)]\n (when-not (or (nil? ss) (map? ss)) (bad \":strokes is a map: {:t1 [[0 440] [1 440]] :t2 …}\"))\n (assoc (cond-> base (sane-quant (:quant x)) (assoc :quant (sane-quant (:quant x)))) :gx gx :gy gy\n :strokes (into {} (for [[k s] ss]\n (let [pts (if (map? s) (:pts s) s)]\n (when-not (keyword? k) (bad (str \"A stroke id is a keyword such as :t1, not \" (pr-str k))))\n [k (with-look {:pts (or (let [r (sane-pts-for base pts)]\n ;; a freqt drops points it cannot hold: here that is an error\n (when (and r (or gen (= (count r) (count pts)))) r))\n (bad (str \"Stroke \" k \": \"\n (if gen \"at least two different points [x y]\"\n \"at least two points [t hz], times from 0 and growing, hz between 1 and 30000\"))))}\n (when (map? s) (:look s)))])))))))\n\n(defn diff\n \"The events that turn buffer a into buffer b: (reduce step a (diff a b)) is b.\"\n [a b]\n (let [a (or a empty)]\n (vec (concat\n (when (and (generic? b) (not= (:ax a) (:ax b))) [[:axis (:ax b)]])\n (when (not= (:gx a) (:gx b)) [[:grid-x (:gx b)]])\n (when (not= (:gy a) (:gy b)) [[:tuning (:gy b)]])\n (when (not= (:quant a) (:quant b)) [[:quantize (:quant b)]])\n (for [[id _] (sorted-strokes a) :when (not (contains? (:strokes b) id))] [:erase id])\n (for [[id s] (sorted-strokes b) :when (not= s (get-in a [:strokes id]))]\n (if (:look s) [:stroke id (:pts s) (:look s)] [:stroke id (:pts s)]))))))\n\n(defn ->voice\n \"Approximation of the canvas as a kairotic.score voice: each stroke is a note on the\n semitone nearest to its first point; the deviation in cents and glissandi are annotated.\"\n [d]\n (let [L (cycle (:gx d))\n snap (fn [x] (/ (js/Math.round (* x 4)) 4))]\n {:tempo 90 :meter [(max 1 (js/Math.round L)) 4]\n :events (into {} (for [[id s] (:strokes d)\n :let [pts (:pts s) [t0 f0] (first pts) [t1 f1] (peek pts)\n m (hz->midi f0) mr (js/Math.round m) dv (js/Math.round (* 100 (- m mr)))\n gl (let [c (* 1200 (log2 (/ f1 f0)))] (cond (> c 30) \"↗\" (< c -30) \"↘\" :else nil))\n txt (str (when (>= (js/Math.abs dv) 5) (str (when (pos? dv) \"+\") dv)) gl)]]\n [id (cond-> {:t (snap t0) :pitch (max 0 (min 127 mr)) :dur (max 0.25 (snap (- t1 t0)))}\n (seq txt) (assoc :txt txt))]))}))\n\n(defn simplify\n \"Ramer–Douglas–Peucker over [x y] points (in pixels): keeps those that deviate more than `eps`.\"\n [ps eps]\n (if (< (count ps) 3)\n (vec ps)\n (let [[ax ay] (first ps) [bx by] (peek ps)\n dx (- bx ax) dy (- by ay) L (max 1e-9 (js/Math.hypot dx dy))\n dist (fn [[x y]] (/ (js/Math.abs (- (* dy (- x ax)) (* dx (- y ay)))) L))\n [i dmax] (reduce (fn [[bi bd] i] (let [dd (dist (nth ps i))] (if (> dd bd) [i dd] [bi bd]))) [0 0] (range 1 (dec (count ps))))]\n (if (> dmax eps)\n (vec (concat (butlast (simplify (subvec ps 0 (inc i)) eps)) (simplify (subvec ps i) eps)))\n [(first ps) (peek ps)]))))\n","kairotic/code.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · code boxes\n;; The base of any programmable component: a box whose data is a source text in some\n;; language. The text is part of the work (it travels through the history and the rooms); each tab\n;; compiles it locally with the compiler registered for its language, and keeps the result in\n;; a cache keyed by source. Faust and ClojureScript are the first two languages; others (JavaScript,\n;; GLSL, a rule language…) only have to register their compiler and their component.\n\n(ns kairotic.code\n (:refer-clojure :exclude [empty])\n (:require [clojure.string :as str]\n [kairotic.components :as comp]))\n\n;; ───────── data (with history) ─────────\n\n(def empty {:source \"\"})\n;; a code box may hold a whole package (a component box with every component of @kairotic/analysis is\n;; about 26 000 characters): longer sources are cut, and cut code does not read\n(def max-source 100000)\n\n(defn step [d [op & args]]\n (let [d (or d empty)]\n (case op\n :source (let [[s] args] (if (string? s) (assoc d :source (subs s 0 (min (count s) max-source))) d))\n :load (let [[x] args] (if (and (map? x) (string? (:source x))) {:source (subs (:source x) 0 (min (count (:source x)) max-source))} d))\n d)))\n\n(defn ->code [id d]\n (when (seq (str/trim (str (:source d))))\n [(str \"(code \" id \" \" (pr-str (:source d)) \")\")]))\n\n(def model {:empty empty :step step :load (fn [x] (step empty [:load x])) :code ->code})\n\n;; ───────── compilation ─────────\n;; compilers: language → (fn [source] promise of {:value x :info {…}})\n\n(defonce compilers (atom {}))\n(defonce cache (atom {})) ; [language source] → {:status :compiling|:ok|:error :error :value :info :n}\n(defonce listeners (atom {})) ; key → (fn []) to notify when a compilation finishes\n(defonce counter (atom 0))\n\n(defn notify! [] (doseq [[_ f] @listeners] (try (f) (catch :default e (js/console.error e)))))\n\n(defn register-language! [language f] (swap! compilers assoc language f) language)\n\n(defn prune! []\n (when (> (count @cache) 60)\n (swap! cache (fn [c] (into {} (take-last 40 (sort-by (fn [[_ v]] (:n v)) c)))))))\n\n(defn compiled\n \"Compilation status of a source; if it has not been requested yet, requests it (and notifies when done).\"\n [language source]\n (let [source (str source) k [language source]]\n (cond\n (str/blank? source) {:status :empty}\n (get @cache k) (get @cache k)\n :else\n (if-let [f (get @compilers language)]\n (let [n (swap! counter inc)]\n (swap! cache assoc k {:status :compiling :n n})\n (prune!)\n (-> (js/Promise.resolve nil)\n (.then (fn [_] (f source)))\n (.then (fn [r] (swap! cache assoc k (assoc r :status :ok :n n)) (notify!)))\n (.catch (fn [e] (swap! cache assoc k {:status :error :n n :error (or (.-message e) (str e))}) (notify!))))\n (get @cache k))\n {:status :error :error (str \"No compiler for \" language)}))))\n\n(defn forget-language! [language]\n (swap! cache (fn [c] (into {} (remove (fn [[[l _] _]] (= l language)) c)))))\n\n;; ───────── script: ClojureScript inside the patch ─────────\n;; The source is a function (fn [m] …) with the same contract as any component: it receives\n;; {:inlet :value :state :args :at} and returns {:state :out [[o v]] :later … :effects …}.\n;; A script runs its writer's code inside this page, so in a shared room\n;; it is not evaluated until this tab allows it: (trust-scripts true).\n\n(defonce trust (atom false))\n;; sources this page brought itself from the official library (Study 22): they run without asking\n(defonce trusted (atom #{}))\n(defn allowed? [source] (or @trust (contains? @trusted source)))\n\n(register-language! \"clojurescript\"\n (fn [source]\n (js/Promise.\n (fn [res rej]\n (if-not (allowed? source)\n (rej (js/Error. \"not run: this work is shared; (trust-scripts true) to evaluate its scripts\"))\n (try\n (let [f (js/scittle.core.eval_string (str \"(do \" source \"\\n)\"))]\n (if (fn? f) (res {:value f :info {:summary \"ready\"}}) (rej (js/Error. \"a script is a function (fn [m] …)\"))))\n (catch :default e (rej e))))))))\n\n(defn whole [x d] (if (number? x) (max 0 (js/Math.round x)) d))\n\n(comp/define! \"script\"\n {:doc \"ClojureScript code box: its source is a function (fn [m] …) that receives and returns messages like any component.\"\n :usage \"script [inlets] [outlets]\"\n :display :code :language \"clojurescript\" :model model\n :io (fn [c] (let [[i o] (:args c)] [(max 1 (whole i 1)) (whole o 1)]))\n :template \"(fn [{:keys [inlet value state]}]\\n ;; return {:out [[outlet value]] :state …}\\n {:out [[0 value]]})\"\n :receive (fn [m]\n (let [r (compiled \"clojurescript\" (get-in m [:data :source]))]\n (if (= :ok (:status r))\n (try\n (let [x ((:value r) m)] (if (map? x) x {}))\n (catch :default e {:effects [[:print (str \"script: \" (or (.-message e) e))]]}))\n {})))})\n","kairotic/components.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · components\n;; Every box class is a component: a map of data and functions, registered by name.\n;; The patch, the engine and the projection to code only consult this registry, so adding\n;; a class (from the core, from a library or written by whoever uses the system) touches nothing else.\n;;\n;; {:class \"ramp\" the first word of the box text\n;; :doc \"…\" :usage \"ramp from to seconds [loop]\"\n;; :license \"MPL-2.0\" SPDX id\n;; :args [[:min 0] [:max 1] [:initial :min] [:log false] [:name nil]]\n;; declared arguments, in order. The kind of the default decides how\n;; the words of the box text fill them: a number (or the key of an\n;; earlier argument) takes the next number; true/false is a flag that is\n;; on when its own name is written (\"log\"); anything else (nil, a\n;; string) takes the next free word, as a keyword. With :args, the m\n;; of :receive, :derive, :draw and :gesture gets :args as that map\n;; (without it, :args is the raw vector of words and numbers).\n;; :io [2 1] | (fn [box] [inlets outlets]) box = {:text :args :data}\n;; :dynamic-io true its ports depend on something computed (lines are not pruned)\n;; :receive (fn [m] result) messages; pure. m = {:id :state :args :inlet :value :at :data\n;; :buffer :buffer-id}\n;; result = {:state :out [[o v]] :later [[at i v]] :effects [[k x]] :show v}\n;; The same value again must change nothing that is going on: data\n;; boxes send what they hold again after ■, when a line or a box\n;; before it is new, or in a room. A player does not start over, a\n;; learner does not learn it twice (compare with what :state keeps).\n;; What its audio node finds in the sound (api/report!) arrives here\n;; too, with :inlet :audio: a level, a block of samples, an error.\n;; What one of its :tasks found arrives with :inlet :task:\n;; {:task k :arg x :value v} or {:task k :arg x :error \"…\"}.\n;; :tasks {k (fn [x box] promise)} what the box asks of the world (the network, a file…), outside\n;; its pure logic: :receive returns the effect [k x], the engine\n;; runs the task, with or without ▶, and its outcome comes back on\n;; inlet :task. box = {:text :args :data :id :state}. The effect\n;; [:keep d] then writes d as the data of the box (its :model :load\n;; reads it), as a gesture: in the history, the same for everyone.\n;; :audio {:create (fn [ac box env] node) box = {:text :args (raw) :data :id :state}, env = {:master …}\n;; node = {:inlets [[AudioNode i]] :outlets [[AudioNode o]] …}\n;; (an inlet can be an AudioParam: a signal is added to it)\n;; :effects {k (fn [node x at])}\n;; :key (fn [box] x) if it changes, the node is rebuilt\n;; :update (fn [node box at]) with it, a new text does not rebuild the node: it gets the\n;; new box (:text :args …) instead (and its state is forgotten)\n;; :wired (fn [node inlets]) after wiring: the set of inlets that receive a signal\n;; :feed (fn [node data]) the buffer at its right inlet, whenever it changes (:reads-buffer)\n;; :dispose (fn [node])}\n;; :sends (fn [box] value) a data box: the page sends this value out of its outlet 0 whenever\n;; the text or data of the box changes (and again toward a new line or\n;; a box after it that changed), as a tree box sends its tree. box =\n;; {:id :text :args :data}; nil while the value is not ready yet\n;; :model {:empty x :step (fn [d ev]) :load (fn [x]) :code (fn [id d] lines)} box data with its own history\n;; With :source (fn [d] text), :read (fn [d text] d2) and :diff (fn [d d2] events) its data can\n;; also be read and edited as text, in the code window (discussion #30): read throws on bad\n;; text, and what diff returns is applied as one [:batch events] of the history.\n;; :display :text | :canvas | :score | :code | :number | :msg | :bang how the patch shows built-in boxes\n;; :views [:code :score] the displays a box of this class can switch between, the first\n;; one its default: each box keeps its choice, (view :bN :score),\n;; and its data stays the same (discussion #30)\n;; :view-as {:roll :canvas} a view drawn as another display (a tree's roll is drawn as a canvas)\n;; :view-aliases {:canvas :roll} older names of its views, still read (in works and in (view …))\n;; :language \"edn\" with a :display that is not :code: its [:data :source] is still\n;; its text, opened in the code window from { } (a tree box)\n;; :size [width height] | (fn [box] [w h]) a box with its own view (drawing and gestures), handle not counted\n;; :view shapes a shapes template (kairotic.shapes) whose values can be holes,\n;; keywords starting with $ (:$angle). Plain data: preferred over :draw\n;; :derive (fn [m] {key value}) pure; the values for the holes of :view. Same m as :draw.\n;; Holes can also name an argument (:$min) or :shown, :w, :h\n;; :draw (fn [m] shapes) escape hatch; pure; m = {:shown :state :args :text :data :w :h};\n;; :shown is the last thing the box returned as :show\n;; :gesture (fn [m] value) dragging over the box; m = the one of :draw plus {:start :x :y :dx :dy :fine :hit}\n;; (:start = what was shown on press; x, y local; dx, dy since the press;\n;; :fine with ⇧; :hit = the :hit of the shape pressed, kairotic.shapes). The value reaches inlet 0 of the box itself while\n;; dragging. On release it is called once more with :up true, and\n;; what it returns stays in the history as (send :bN value) (a\n;; :gesture that ignores :up repeats its last value: knob, sliders)\n;; :persist (fn [value] {arg value}) with :args: what a gesture leaves in the box text. On release, instead of\n;; (send! :bN value) the patch writes (text! :bN \"class …\") with these\n;; arguments, so the change stays in the work\n;; :parse (fn [text] args) instead of :args: reads the arguments from the whole box text (the\n;; functions of clojure.core as boxes read theirs as EDN)\n;; :language \"faust\" for code boxes\n;; :template \"…\" initial source of a code box\n;; :params … parameters\n;; :reads-buffer true receives in m the canvas connected to its right inlet\n;; :patch {:boxes … :lines …} an abstraction: the class is a patch. Its inlet/inlet~ and\n;; outlet/outlet~ boxes, ordered left to right, are its ports, and\n;; $1 $2 … in the texts of its boxes take the words of the box text.\n;; The engine expands it in place (kairotic.engine/flatten-patch)\n;; :origin :core | :work | :user\n;; :from :bN} the box that defines a work class\n\n(ns kairotic.components\n (:require [clojure.string :as str]\n [clojure.edn :as edn]\n [kairotic.score :as sc]\n [kairotic.canvas :as cv]\n [kairotic.span :as span]))\n\n(defonce registry (atom {}))\n;; how a musical tree becomes a buffer of strokes (set by kairotic.mtboxes; kairotic.mt is not required here)\n(defonce tree-buffer (atom nil))\n;; how an audio node gives its own box something found in the sound: (fn [id value at]) (set by\n;; kairotic.engine, which is loaded after this; components reach it through kairotic.api/report!)\n(defonce audio-report (atom nil))\n;; how an audio node asks the page for an effect of its box ([:sample …]): (fn [id effect]) (kairotic.engine)\n(defonce audio-effect (atom nil))\n;; what runs after the audio nodes are fitted and fed, every tick (kairotic.ringaudio folds faust~ loops there)\n(defonce after-feed (atom nil))\n\n(declare patch-io)\n\n(defn define!\n \"Registers (or replaces) a component. Returns its name. An abstraction (:patch) gets its ports\n from its inlet and outlet boxes.\"\n [klass-name d]\n (let [d (if (map? (:patch d))\n (assoc d :io (fn [_] (patch-io (:patch d))) :dynamic-io true :abstraction true)\n d)]\n (swap! registry assoc klass-name (merge {:display :text :origin :core :io [1 1]} d {:class klass-name})))\n klass-name)\n\n;; classes that are not registered but can be made when a box asks for them (kairotic.corefns: the\n;; functions of clojure.core): each is (fn [class-name] definition-or-nil). A registered class comes first.\n(defonce fallbacks (atom []))\n\n(defn lookup [klass-name]\n (or (get @registry klass-name)\n (some (fn [f] (f klass-name)) @fallbacks)))\n\n;; ───────── text of a box ─────────\n\n;; A box can start with flags written as Clojure metadata, before its class: ^:hot vector % 0 0\n;; (the hot mode of Clojure boxes). They are not part of the class nor of its arguments.\n(def ^:private meta-re #\"^(?:\\^:[^\\s\\^]+\\s+)+\")\n\n(defn meta-flags\n \"The flags written before the class (^:hot → #{:hot}).\"\n [text]\n (let [m (re-find meta-re (str/trim (str text)))]\n (if m (set (map (fn [[_ k]] (keyword k)) (re-seq #\"\\^:([^\\s\\^]+)\" m))) #{})))\n\n(defn strip-meta \"The text without the flags written before the class.\" [text]\n (str/replace (str/trim (str text)) meta-re \"\"))\n\n(defn- form-end\n \"Where the bracketed form at the start of s ends (its length), strings and escapes skipped; the\n whole length when it never closes.\"\n [s]\n (loop [i 0 depth 0 in-str false]\n (if (>= i (count s))\n (count s)\n (let [c (.charAt s i)]\n (cond\n in-str (cond (= c \"\\\\\") (recur (+ i 2) depth true)\n (= c \"\\\"\") (recur (inc i) depth false)\n :else (recur (inc i) depth true))\n (= c \"\\\"\") (recur (inc i) depth true)\n (#{\"{\" \"[\" \"(\"} c) (recur (inc i) (inc depth) false)\n (#{\"}\" \"]\" \")\"} c) (if (= depth 1) (inc i) (recur (inc i) (dec depth) false))\n :else (recur (inc i) depth false))))))\n\n(defn klass\n \"The class of a box: its first word, after any ^:flags. A map or a set written first ({60 :c 64 :e},\n #{60 64 67}) is the class as a whole, as a function in Clojure.\"\n [text]\n (let [t (strip-meta text)]\n (if (re-find #\"^#?\\{\" t)\n (subs t 0 (form-end t))\n (first (str/split t #\"\\s+\")))))\n\n(defn token [s]\n (if (re-matches #\"-?(\\d+\\.?\\d*|\\.\\d+)(e-?\\d+)?\" s) (js/parseFloat s) (keyword s)))\n\n(defn args-of [text]\n (let [t (strip-meta text)]\n (mapv token (remove str/blank? (str/split (str/trim (subs t (count (klass t)))) #\"\\s+\")))))\n\n(defn box-info [b] {:text (:text b) :args (args-of (:text b)) :data (:data b)})\n\n(defn io\n \"Inlets and outlets of a box (a map with :text and, if it has it, :data).\"\n [b]\n (let [d (lookup (klass (:text b))) x (:io d)]\n (cond (fn? x) (x (box-info b)) (vector? x) x :else [1 1])))\n\n(defn dynamic?\n \"Ports that must not be pruned: computed ones (a compilation) and those of classes defined by the\n work itself or that do not exist yet, because they depend on when their definition is evaluated.\"\n [b]\n (let [d (lookup (klass (:text b)))]\n (boolean (or (nil? d) (:dynamic-io d) (= :work (:origin d))))))\n\n(defn model-of [b] (:model (lookup (klass (:text b)))))\n\n;; classes that became a view of another one: a box written with the old name is read as the new\n;; class, in that view (discussion #30: a score box is a freqt shown as a score)\n(def renamed {\"score\" [\"freqt\" :score]})\n\n(defn upgrade-box\n \"A box of a renamed class, as its new class in the matching view (its arguments kept); others unchanged.\"\n [b]\n (let [t (str/trim (str (:text b))) k (klass t)]\n (if-let [[nk v] (get renamed k)]\n (let [b (assoc b :text (str nk (subs t (count k))))]\n ;; the view it showed: its old default becomes v; another view it could show stays, if the new\n ;; class has it and it is not that class's default\n (if (or (nil? (:view b)) (= (:view b) v))\n (assoc b :view v)\n (let [vs (:views (lookup nk))]\n (if (and (some #{(:view b)} vs) (not= (:view b) (first vs))) b (dissoc b :view)))))\n b)))\n\n(defn views-of \"The displays a box can switch between (none, or one, if its class has no :views).\" [b]\n (:views (lookup (klass (:text b)))))\n\n(defn view-name\n \"A view as its class names it now: an older name ((:view-aliases of the class) becomes the current one.\"\n [b v] (get (:view-aliases (lookup (klass (:text b)))) v v))\n\n(defn shown-as\n \"The view a box is shown in: the view it chose, if its class offers it (by its current name or an older\n one), or the :display of its class.\"\n [b]\n (let [d (lookup (klass (:text b))) v (view-name b (:view b))]\n (if (and (keyword? v) (some #{v} (:views d))) v (or (:display d) :text))))\n\n(defn drawn-as\n \"How a box is drawn: the display of the view it is shown in (a tree's :roll is drawn as a :canvas).\"\n [b]\n (let [v (shown-as b)] (get (:view-as (lookup (klass (:text b)))) v v)))\n\n(defn source-of\n \"The data of a box as text, to edit (a code box's source, or what its model's :source writes), or nil.\"\n [b]\n (let [m (model-of b)]\n (cond (fn? (:source m)) ((:source m) (or (:data b) (:empty m)))\n (let [d (lookup (klass (:text b)))] (or (= :code (:display d)) (string? (:language d))))\n (str (get-in b [:data :source]))\n :else nil)))\n\n(defn own-view?\n \"Does the box have its own view (a :draw or a :view)?\"\n [b]\n (let [d (lookup (klass (:text b)))]\n (boolean (or (fn? (:draw d)) (some? (:view d))))))\n\n(defn size-of\n \"Size of a box's own view, bounded to something reasonable.\"\n [b]\n (let [s (:size (lookup (klass (:text b))))\n s (if (fn? s) (try (s (box-info b)) (catch :default _ nil)) s)]\n (if (and (sequential? s) (= 2 (count s)) (every? number? s))\n [(max 24 (min 480 (first s))) (max 16 (min 480 (second s)))]\n [64 64])))\n\n;; ───────── patches inside patches ─────────\n;; A sub-patch (an embedded `patch` box, or an instance of an abstraction) talks to the outside\n;; through its inlet/outlet boxes: message ones (inlet, outlet) and audio ones (inlet~, outlet~)\n;; share the numbering, ordered by their position from left to right, as in Max.\n\n(def inlet-classes #{\"inlet\" \"inlet~\"})\n(def outlet-classes #{\"outlet\" \"outlet~\"})\n\n(defn patch-ports\n \"The ids of a patch's inlet and outlet boxes, in port order: {:inlets [...] :outlets [...]}.\"\n [p]\n (let [of (fn [classes]\n (->> (:boxes p)\n (filter (fn [[_ b]] (contains? classes (klass (:text b)))))\n (sort-by (fn [[id b]] [(or (:x b) 0) (or (:y b) 0) (name id)]))\n (mapv first)))]\n {:inlets (of inlet-classes) :outlets (of outlet-classes)}))\n\n(defn patch-io [p] (let [{:keys [inlets outlets]} (patch-ports p)] [(count inlets) (count outlets)]))\n\n(defn subpatch?\n \"Is the box a sub-patch (embedded or an abstraction)?\"\n [b]\n (let [k (klass (:text b))]\n (or (= k \"patch\") (map? (:patch (lookup k))))))\n\n;; ───────── utilities for writing components ─────────\n\n(defn parse-args\n \"Fills a declared :args spec from the raw words and numbers of a box text (see the header).\"\n [spec raw]\n (let [words (filter keyword? raw)\n flag-names (set (keep (fn [[k d]] (when (boolean? d) (name k))) spec))\n written (set (map name words))]\n (loop [[[k d :as item] & more] spec\n nums (filter number? raw)\n free (remove (fn [w] (flag-names (name w))) words)\n acc {}]\n (if-not item\n acc\n (cond\n (boolean? d) (recur more nums free (assoc acc k (if (contains? written (name k)) true d)))\n (or (number? d) (and (keyword? d) (contains? acc d)))\n (recur more (rest nums) free (assoc acc k (cond (seq nums) (first nums) (keyword? d) (get acc d) :else d)))\n :else (recur more nums (rest free) (assoc acc k (if (seq free) (first free) d))))))))\n\n(defn num-text [x] (if (== x (js/Math.round x)) (str (js/Math.round x)) (str (/ (js/Math.round (* x 10000)) 10000))))\n\n(defn args-text\n \"The text of a box of class k whose arguments are `vals` (a map), written in the order of the :args\n spec of d: the numbers (those still at their default at the end are left out), then flags and words.\"\n [d k vals]\n (let [spec (:args d)\n dflt (fn [x] (if (keyword? x) (get vals x) x))\n nums (for [[a v] spec :when (or (number? v) (and (keyword? v) (not (boolean? v))))]\n [(get vals a (dflt v)) (dflt v)])\n nums (reverse (drop-while (fn [[v d0]] (= v d0)) (reverse nums)))\n flags (for [[a v] spec :when (and (boolean? v) (get vals a))] (name a))\n words (for [[a v] spec :when (not (or (number? v) (keyword? v) (boolean? v)))\n :let [w (get vals a)] :when w] (if (keyword? w) (name w) (str w)))]\n (str/join \" \" (concat [k] (map (comp num-text first) nums) flags words))))\n\n(defn args-for\n \"The :args a component receives: the parsed map if it declares :args, else the raw vector.\"\n [d text]\n (let [raw (args-of text) spec (:args d)]\n (cond\n (fn? (:parse d)) ((:parse d) text)\n (and (sequential? spec) (every? (fn [x] (and (vector? x) (keyword? (first x)))) spec)) (parse-args spec raw)\n :else raw)))\n\n(defn clamp\n \"x between a and b (in either order).\"\n [x a b] (max (min a b) (min (max a b) x)))\n\n(defn nice\n \"A value rounded to a sensible precision for display and sending.\"\n [v]\n (let [a (js/Math.abs v)\n e (cond (>= a 100) 1 (>= a 10) 10 (>= a 1) 100 :else 1000)]\n (/ (js/Math.round (* v e)) e)))\n\n(defn to-unit\n \"Where v lies between lo and hi, as 0…1 (logarithmically if log? and both are positive).\"\n [v lo hi log?]\n (let [u (cond (= lo hi) 0\n (and log? (pos? lo) (pos? hi) (pos? v)) (/ (js/Math.log (/ v lo)) (js/Math.log (/ hi lo)))\n :else (/ (- v lo) (- hi lo)))]\n (if (js/isFinite u) (clamp u 0 1) 0)))\n\n(defn from-unit\n \"The value at u (0…1) between lo and hi, rounded with `nice`.\"\n [u lo hi log?]\n (let [u (clamp u 0 1)]\n (nice (if (and log? (pos? lo) (pos? hi)) (* lo (js/Math.pow (/ hi lo) u)) (+ lo (* u (- hi lo)))))))\n\n(defn num-of [v] (cond (number? v) v (and (sequential? v) (number? (first v))) (first v) :else nil))\n(defn map-num [f v] (cond (number? v) (f v) (sequential? v) (mapv (fn [x] (if (number? x) (f x) x)) v) :else v))\n(defn r6 [x] (/ (js/Math.round (* x 1e6)) 1e6))\n(defn tick? [v g] (and (vector? v) (= :tick (first v)) (or (nil? g) (= g (second v)))))\n(def grain 0.01)\n\n;; ───────── core: messages ─────────\n\n(defn arit [op]\n (fn [{:keys [state args inlet value]}]\n (let [b (if (some? state) state (or (num-of (first args)) 0))]\n (cond (= inlet 1) {:state (or (num-of value) b)}\n (or (number? value) (sequential? value)) {:state b :out [[0 (map-num (fn [x] (op x b)) value)]]}\n :else {:state b}))))\n\n(defn ramp [{:keys [state args inlet value at]}]\n (let [[a b s lp] args\n st (or state {:gen 0 :a (or (num-of a) 0) :b (or (num-of b) 1) :s (max 0.01 (or (num-of s) 1))\n :loop (= lp :loop) :on false})\n start (fn [st a b s]\n (let [g (inc (:gen st))]\n {:state (assoc st :gen g :a a :b b :s s :t0 at :on true)\n :out [[0 a]] :show a :later [[(+ at grain) 0 [:tick g]]]}))]\n (cond\n (tick? value nil)\n (if (and (:on st) (tick? value (:gen st)))\n (let [u (/ (- at (:t0 st)) (:s st))]\n (cond\n (and (>= u 1) (:loop st)) (start st (:a st) (:b st) (:s st))\n (>= u 1) {:state (assoc st :on false) :out [[0 (:b st)]] :show (:b st)}\n :else (let [v (r6 (+ (:a st) (* u (- (:b st) (:a st)))))]\n {:state st :out [[0 v]] :show v :later [[(+ at grain) 0 [:tick (:gen st)]]]})))\n {:state st})\n (= inlet 1) {:state (assoc st :loop (boolean (and (num-of value) (not (zero? (num-of value))))))}\n (= value :bang) (start st (:a st) (:b st) (:s st))\n (= value :stop) {:state (assoc st :on false :gen (inc (:gen st)))}\n (and (sequential? value) (= 3 (count value)) (every? number? value))\n (let [[a b s] value] (start st a b (max 0.01 s)))\n (number? value) {:state (assoc st :on false :gen (inc (:gen st))) :out [[0 value]] :show value}\n :else {:state st})))\n\n(defn metro [{:keys [state args inlet value at]}]\n (let [st (or state {:on false :ms (max 5 (or (num-of (first args)) 500)) :gen 0})\n next-tick (fn [st] [[(+ at (/ (:ms st) 1000)) 0 [:tick (:gen st)]]])]\n (cond\n (tick? value nil) (if (and (:on st) (tick? value (:gen st)))\n {:state st :out [[0 :bang]] :show :bang :later (next-tick st)}\n {:state st})\n (= inlet 1) {:state (assoc st :ms (max 5 (or (num-of value) (:ms st))))}\n (or (= value 0) (= value :stop)) {:state (assoc st :on false :gen (inc (:gen st)))}\n (or (= value :bang) (number? value) (= value :start))\n (let [st (assoc st :on true :gen (inc (:gen st)))]\n {:state st :out [[0 :bang]] :show :bang :later (next-tick st)})\n :else {:state st})))\n\n(defn counter [{:keys [state args inlet value]}]\n (let [[step mx mn] args\n step (or (num-of step) 1) mn (or (num-of mn) 0) mx (num-of mx)\n v (if (some? state) state mn)]\n (cond\n (= inlet 1) {:state (or (num-of value) v)}\n (= value :reset) {:state mn}\n (or (= value :bang) (number? value))\n (let [nv (r6 (+ v step)) nv (if (and mx (>= nv mx)) mn nv)]\n {:state nv :out [[0 v]] :show v})\n :else {:state v})))\n\n(defn number-box [{:keys [state args value]}]\n (let [init (if (map? args) (:initial args) (num-of (first args)))\n cur (if (some? state) state (or (num-of init) 0))]\n (cond (= value :bang) {:state cur :out [[0 cur]] :show cur}\n (num-of value) (let [v (num-of value)] {:state v :out [[0 v]] :show v})\n :else {:state cur})))\n\n;; ───── a reader on a ring (kairotic.span): two ways, as a head of Study 47 ─────\n;; · it follows: d behind the ring's head, then its speed (msg :d 1, msg :speed 0.5, or reader d 1 [speed 0.5]),\n;; moving on its own: every tick it looks a tick ahead and sends what it will cross, each at the instant it meets\n;; it (so a d shorter than a tick may miss what is written meanwhile); it starts when the ring's time does\n;; (:start on its buffer wire) or when it gets a d; :stop stops it\n;; · it is moved: a number on the left is a position of the ring (seconds, or 0…1 with norm), from any source; it\n;; sends what it crosses since the last one, either way; a move larger than its jump is a seek\n;; What it sends: each value as it was written, on the left.\n\n(def ring-tick 0.05)\n\n(defn- word-num [args k] (let [x (second (drop-while #(not= k %) args))] (when (number? x) x)))\n\n(defn reader-on-ring [{:keys [inlet value buffer state args at]}]\n (let [r buffer st (or state {})\n speed0 (or (word-num args :speed) 1)\n jump (or (:jump st) (word-num args :jump) 0.5)\n drift (fn [st T] (+ (or (:drift0 st) 0) (* (- 1 (:speed st)) (- T (:since st)))))\n follow (fn [st d]\n (let [g (inc (:gen st 0))]\n {:state (assoc st :mode :follow :d d :speed (or (:speed st) speed0) :drift0 0 :since at :gen g)\n :later [[at 0 [:tick g]]]}))\n cmd (fn [k] (when (and (vector? value) (= k (first value)) (number? (second value))) (second value)))]\n (cond\n ;; the ring's time starts: a reader given a d begins to follow\n (= inlet 1)\n (let [d (or (:d st) (word-num args :d))]\n (if (and (= value :start) d (not= :pos (:mode st))) (follow st d) {}))\n (cmd :d) (follow st (cmd :d))\n (cmd :speed)\n (let [s (cmd :speed)]\n {:state (if (= :follow (:mode st)) (assoc st :drift0 (drift st at) :since at :speed s) (assoc st :speed s))})\n (cmd :jump) {:state (assoc st :jump (cmd :jump))}\n (= value :stop) {:state (-> st (dissoc :mode) (update :gen (fnil inc 0)))}\n ;; what it meets, at the instant it meets it\n (and (vector? value) (= :reader/at (first value))) {:out [[0 (second value)]]}\n (tick? value nil)\n (if (and (= :follow (:mode st)) (= (second value) (:gen st)))\n (let [now-p (span/follow-at r st at)\n next-tick [(+ at ring-tick) 0 [:tick (:gen st)]]]\n (if (nil? now-p)\n {:state (dissoc st :p) :later [next-tick]} ; the ring has not started (or was cleared)\n (let [end-p (span/follow-at r st (+ at ring-tick))\n from (let [p (:p st)] (if (or (nil? p) (> (js/Math.abs (- now-p p)) jump)) now-p p))]\n {:state (assoc st :p end-p) :show {:ring true :p (span/wrap r now-p)}\n :later (conj (mapv (fn [[x e]] [(span/when-met now-p at (:speed st) x) 0 [:reader/at (:v e)]])\n (span/crossings r at from end-p))\n next-tick)})))\n {})\n (num-of value)\n (let [u (num-of value) l (:dur r)\n q (if (some #{:norm} args) (* u l) u)\n prev (when (= :pos (:mode st)) (:p st))\n p (if prev (+ prev (span/shortest l (span/wrap r prev) q)) q)\n seek (or (nil? prev) (> (js/Math.abs (- p prev)) jump))]\n {:state (-> st (assoc :mode :pos :p p) (update :gen (fnil inc 0)))\n :show {:ring true :p (span/wrap r p)}\n :out (if seek [] (mapv (fn [[_ e]] [0 (:v e)]) (span/crossings r at prev p)))})\n :else {})))\n\n(defn reader [{:keys [inlet value buffer buffer-id args] :as m}]\n (cond\n (span/ring? buffer) (reader-on-ring m)\n ;; reader path [stroke]: a position from 0 to 1 along a stroke, in the order it was drawn → [x y]\n (and (zero? inlet) (num-of value) (some #{:path} args))\n (let [sid (first (remove #{:path :norm :d :speed :jump} (filter keyword? args)))\n u (clamp (num-of value) 0 1)\n pts (when buffer (cv/stroke-for buffer sid))\n pt (when pts (cv/point-along buffer pts u))]\n (if pt\n {:out [[0 pt]] :show {:t u :from buffer-id :axis :path :pt pt}}\n {}))\n (and (zero? inlet) (num-of value))\n (let [axis (if (some #{:y} args) :y :x)\n ;; with norm, 0…1 covers the axis (as a reader~ reads it): its range, along a log axis too\n t (if (and buffer (some #{:norm} args))\n (let [[lo hi log] (if (= axis :y) (cv/y-range buffer) (cv/x-range buffer)) u (num-of value)]\n (if (and log (pos? lo) (pos? hi)) (* lo (js/Math.pow (/ hi lo) u)) (+ lo (* u (- hi lo)))))\n (num-of value))\n r (if buffer (cv/read-along buffer axis t) [])]\n ;; as in Max, first the right outlet (ids) and then the left one (values)\n {:out [[1 (mapv first r)] [0 (mapv second r)]] :show {:t t :from buffer-id :n (count r) :axis axis}})\n :else\n {}))\n\n;; ───── what a canvas, freqt or score takes on its left inlet (issue #26) ─────\n;; · a number: comes out on the left and moves the cursor (as a click does)\n;; · a musical tree ([:voice …]): shown live over the buffer; (keep! :bN) writes it in, with its recipe\n;; · an edit: changes the buffer, as one event of the history (the same as the commands of the REPL)\n;; [:stroke [[x y] …]] · [:stroke :t3 [[x y] …]] · [:note t pitch dur] (pitch: MIDI or \"c4\")\n;; [:move :t1 dx dy] · [:stretch :t1 k] · [:erase :t1] · [:clear] · [:cut t] (everything from t on)\n;; · [:cut t1 t2] (what is between t1 and t2)\n;; [:axis :x lo hi] · [:axis :y lo hi :log] · [:grid-x step cycles] · [:grid-y step] · [:tuning \"19-tet\" ref]\n;; [:quantize {:meter \"6/8\" …}] (a freqt: how its score is quantized; nil: the defaults)\n;; [:batch [edit …]]: several at once, one event\n;; · a question: the answer comes out on the left, nothing changes\n;; [:read x] (or [:read :y v]) → [[stroke value] …] · [:strokes] → [:t1 …] · [:get :t1] → its points\n;; [:count] · [:end] (where the last stroke ends) · [:range] / [:range :y] → [lo hi] · [:data] → the buffer\n\n(def canvas-edits #{:stroke :note :move :stretch :erase :clear :cut :axis :grid-x :grid-y :tuning :quantize :batch})\n(def canvas-questions #{:read :strokes :get :count :end :range :data})\n\n(defn canvas-edit?\n \"An edit for a canvas (and not a musical tree: [:note {…}] is a node of a tree, [:note 0 \\\"c4\\\" 1] an edit).\"\n [v]\n (and (vector? v) (contains? canvas-edits (first v))\n (or (not= :note (first v)) (cv/num? (second v)))))\n\n(defn canvas-question? [v] (and (vector? v) (contains? canvas-questions (first v))))\n\n(defn canvas-event\n \"One message as an event of the buffer d (ids given to new strokes), or nil if it does not read.\"\n [d [op & args]]\n (case op\n :stroke (let [[a b c] args [id pts look] (if (keyword? a) [a b c] [(cv/next-id d) a b])]\n (if (cv/sane-look look) [:stroke id pts look] [:stroke id pts]))\n :note (let [[t p dur] args\n hz (cond (cv/num? p) (if (cv/generic? d) p (cv/midi->hz p))\n (string? p) (some-> (sc/pitch p) cv/midi->hz))]\n (when (and (cv/num? t) (cv/num? dur) (pos? dur) hz)\n [:stroke (cv/next-id d) [[t (cv/round-to hz 3)] [(+ t dur) (cv/round-to hz 3)]]]))\n (:move :stretch :erase :clear) (into [op] args)\n :axis (let [[k lo hi lg] args]\n (cond (map? k) [:axis k]\n (#{:x :y} k) [:axis (assoc (or (:ax d) cv/default-ax) k {:lo lo :hi hi :log (= lg :log)})]))\n :grid-x (let [[s cs] args] [:grid-x (if (map? s) s (when (cv/num? s) {:step s :cycles (or cs [])}))])\n :grid-y (let [[s] args] [:grid-y (if (map? s) s (when (cv/num? s) {:step s}))])\n :quantize (let [[q] args] (when (or (nil? q) (map? q)) [:quantize q]))\n :tuning (let [[x ref] args\n base (cond (map? x) x\n (string? x) (or (get cv/tunings (str/lower-case x)) (cv/parse-scl x)))]\n (when base [:tuning (cond-> base (cv/num? ref) (assoc :ref ref) (not (cv/num? ref)) (update :ref #(or % cv/default-ref)))]))\n nil))\n\n(defn canvas-events\n \"The messages (an edit, or [:batch [edits]]) as events of the buffer d, each one applied before the next\n is read (so new strokes get new ids); those that change nothing are left out.\"\n [d msg]\n (let [msgs (if (= :batch (first msg)) (filter vector? (second msg)) [msg])\n ;; [:cut t] removes everything from t on, [:cut t1 t2] what is between t1 and t2 (as the erases,\n ;; shortened and split strokes it takes)\n msgs (mapcat (fn [m] (if (and (= :cut (first m)) (cv/num? (second m)))\n [[:cut-now (second m) (let [t2 (get m 2)] (when (and (cv/num? t2) (> t2 (second m))) t2))]]\n [m]))\n msgs)]\n (first (reduce (fn [[evs d] m]\n (if (= :cut-now (first m))\n (let [es (cv/cut-events d (second m) (get m 2))]\n [(into evs es) (reduce cv/step d es)])\n (let [e (canvas-event d m) d2 (when e (cv/step d e))]\n (if (and e (not= d2 d)) [(conj evs e) d2] [evs d]))))\n [[] d] msgs))))\n\n(defn canvas-answer\n \"The answer to a question about the buffer d.\"\n [d [q & args]]\n (case q\n :read (let [[a b] args] (if (#{:x :y} a) (cv/read-along d a b) (cv/read-along d :x a)))\n :strokes (mapv first (cv/sorted-strokes d))\n :get (get-in d [:strokes (first args) :pts])\n :count (count (:strokes d))\n :end (cv/end-t d)\n :range (vec (take 2 (if (= :y (first args)) (cv/y-range d) (cv/x-range d))))\n :data d\n nil))\n\n(defn canvas-receiver\n \"The left inlet of a canvas (empty: its buffer before anything is drawn).\"\n [empty]\n (fn [{:keys [inlet value state data]}]\n (let [d (or data empty)]\n (cond\n (not (zero? inlet)) {:state state}\n (canvas-edit? value)\n (let [evs (canvas-events d value)]\n (if (seq evs)\n {:state state :effects [[:canvas-edit evs]]}\n {:state state :effects [[:print (str \"canvas: \" (pr-str value) \" changes nothing (an id that is not there, or points it cannot take)\")]]}))\n (canvas-question? value)\n (let [a (canvas-answer d value)] {:state state :out (if (some? a) [[0 a]] [])})\n (and (vector? value) (keyword? (first value)))\n {:state (assoc state :tree value) :show {:tree value}}\n (num-of value)\n {:state state :out [[0 (num-of value)]] :show (cond-> {:t (num-of value)} (:tree state) (assoc :tree (:tree state)))}\n :else {:state state}))))\n\n(def canvas-box (canvas-receiver cv/empty))\n\n(def canvas-model {:empty cv/generic-empty :step cv/step :load (fn [x] (cv/step cv/generic-empty [:load x])) :code cv/->code\n :source cv/->source :read cv/read-source :diff cv/diff})\n(def freqt-model {:empty cv/empty :step cv/step :load (fn [x] (cv/step cv/empty [:load x])) :code cv/->code\n :source cv/->source :read cv/read-source :diff cv/diff})\n\n(define! \"loadbang\" {:doc \"Sends a bang when the engine starts (▶).\" :io [0 1] :receive (fn [_] {:out [[0 :bang]]})})\n(define! \"bang\" {:doc \"A button: when pressed (or on receiving anything) it sends a bang.\" :io [1 1] :display :bang\n :receive (fn [_] {:out [[0 :bang]] :show :bang})})\n(defn msg-word\n \"A word of a msg box, read as Clojure reads it: a number, :x a keyword, true false nil, and any other\n word a name (a symbol) — inc, but also free text such as e4, 6/5, +7, https://…, /osc/address, whose\n whole text is (str x).\"\n [w]\n (cond (re-matches #\"-?(\\d+\\.?\\d*|\\.\\d+)(e-?\\d+)?\" w) (js/parseFloat w)\n (and (str/starts-with? w \":\") (> (count w) 1)) (keyword (subs w 1))\n (= w \"true\") true\n (= w \"false\") false\n (= w \"nil\") nil\n :else (symbol w)))\n\n(defn msg-words\n \"The content of a msg box, after its class, read as in Clojure: numbers, keywords with their colon\n (:stop, :rec), names (inc, e4, https://…), true false nil, text between quotes as strings —\n \\\"https://…\\\", \\\"two words\\\", with \\\\\\\" and \\\\\\\\ inside (an unclosed quote takes the rest) — and EDN forms\n ([0 4 7], {:freq 440}, #{60 64}).\"\n [text]\n (let [t (str/trim (str text))\n t (subs t (count (klass t)))\n n (count t)]\n (loop [i 0 out [] word nil quoted nil]\n (if (>= i n)\n (cond quoted (conj out quoted)\n word (conj out (msg-word word))\n :else out)\n (let [c (nth t i)]\n (cond\n (some? quoted) (cond (and (= c \"\\\\\") (< (inc i) n)) (recur (+ i 2) out word (str quoted (nth t (inc i))))\n (= c \"\\\"\") (recur (inc i) (conj out quoted) nil nil)\n :else (recur (inc i) out word (str quoted c)))\n (re-matches #\"\\s\" c) (recur (inc i) (if word (conj out (msg-word word)) out) nil nil)\n (and (= c \"\\\"\") (nil? word)) (recur (inc i) out nil \"\")\n ;; a form: [..], {..}, #{..}, (..) as EDN, whole\n (and (nil? word) (or (#{\"[\" \"{\" \"(\"} c) (and (= c \"#\") (= \"{\" (get t (inc i))))))\n (let [rest-t (subs t i)\n len (form-end (if (= c \"#\") (subs rest-t 1) rest-t))\n len (if (= c \"#\") (inc len) len)\n src (subs rest-t 0 len)]\n (recur (+ i len) (conj out (try (edn/read-string src) (catch :default _ (symbol src)))) nil nil))\n :else (recur (inc i) out (str word c) nil)))))))\n\n(define! \"msg\" {:doc \"Message: when pressed it sends its content, read as in Clojure: numbers, keywords with their colon (:stop, :rec 4), names (any other word: inc, e4, 6/5, https://…), true false nil, text between quotes (\\\"two words\\\") as a string and EDN forms ([0 4 7], {:freq 440}); several make a list. A word without its colon is a name, not a keyword: msg stop does not stop a metro, msg :stop does.\" :usage \"msg :stop · msg 0 8 4 · msg inc\"\n :io [1 1] :display :msg\n :parse msg-words\n :receive (fn [{:keys [args]}] {:out [[0 (case (count args) 0 :bang 1 (first args) (vec args))]] :show :bang})})\n(define! \"number\" {:doc \"A draggable number; sends it when it changes or on receiving a bang. Let go (or typed), its value stays in its text, as a knob's does: it travels with the work, and going back in the history brings back the number it had.\" :usage \"number [initial]\"\n :io [1 1] :display :number :receive number-box\n ;; like a knob (issue #146): on release the value is written in the box text\n :args [[:initial 0]] :persist (fn [v] {:initial v})})\n(defn print-label\n \"The label of a print box: everything written after print (print out0 · print the left hand), or nil.\"\n [text]\n (let [t (strip-meta text) l (str/trim (subs t (count (klass t))))] (when (seq l) l)))\n\n(define! \"print\" {:doc \"Writes to the REPL whatever it receives, after its label: print out0 writes out0: 60 (without one, print: 60). A string is written as it is, anything else as EDN; to shape what it writes, a format or str before it (format \\\"%.1f Hz\\\").\"\n :usage \"print [label]\"\n :io [1 0] :parse print-label\n :receive (fn [{:keys [value args]}] {:effects [(if (string? args) [:print value args] [:print value])]})})\n\n;; ───── draw: a view made of the messages that arrive (kairotic.shapes) ─────\n;; Shapes arrive as data and are drawn as the shapes of any component: SVG, in the theme's colours,\n;; without markup of their own. A shape with :hit k, pressed, sends k out.\n\n(def draw-kinds #{:rect :circle :line :arc :needle :path :text :curve :group})\n(def draw-max 600)\n\n(defn draw-shape? [x] (and (vector? x) (contains? draw-kinds (first x)) (or (nil? (second x)) (map? (second x)))))\n\n(def draw-palette #{:ink :soft :accent :kairos :bg :grid})\n\n(defn draw-positional\n \"A shape written as a msg can write it, its numbers in order: circle cx cy r · rect x y w h ·\n line x1 y1 x2 y2 · arc cx cy r from to · text x y \\\"words\\\" — then, in any order, a colour of the\n palette (accent, kairos…) and hit name. [:circle 60 50 18 :accent :hit :sun] → the shape, or nil.\"\n [v]\n (when (and (vector? v) (#{:circle :rect :line :arc :text} (first v)) (number? (second v)))\n (let [[kind & more] v\n nums (vec (take-while number? more)) words (drop (count nums) more)\n colour (first (filter draw-palette words))\n hit (second (drop-while (fn [w] (not= :hit w)) words))\n txt (first (filter string? words))\n o (fn [ks] (zipmap ks nums))]\n (case kind\n :circle (when (= 3 (count nums)) [:circle (cond-> (assoc (o [:cx :cy :r]) :fill (or colour :accent) :stroke nil) hit (assoc :hit hit))])\n :rect (when (= 4 (count nums)) [:rect (cond-> (assoc (o [:x :y :w :h]) :fill (or colour :accent) :stroke nil) hit (assoc :hit hit))])\n :line (when (= 4 (count nums)) [:line (cond-> (assoc (o [:x1 :y1 :x2 :y2]) :stroke (or colour :ink) :weight 2) hit (assoc :hit hit))])\n :arc (when (= 5 (count nums)) [:arc (cond-> (assoc (o [:cx :cy :r :from :to]) :stroke (or colour :ink) :weight 2) hit (assoc :hit hit))])\n :text (when (= 2 (count nums)) [:text (cond-> (assoc (o [:x :y]) :fill (or colour :ink) :size 12) hit (assoc :hit hit)) (or txt \"\")])))))\n\n(defn as-shape [x] (if (draw-shape? x) x (draw-positional x)))\n\n(defn draw-size [args]\n (let [[w h] (filter number? args)]\n [(clamp (or w 240) 40 480) (clamp (or h 160) 30 480)]))\n\n(defn draw-receive [{:keys [value state]}]\n (let [st (or state {:named {} :order [] :n 0})\n put (fn [st k f] (-> st (assoc-in [:named k] f) (update :order (fn [o] (if (some #{k} o) o (conj o k))))))\n trim (fn [st] (if (> (count (:order st)) draw-max)\n (let [drop (take (- (count (:order st)) draw-max) (:order st))]\n (-> st (update :named (fn [m] (apply dissoc m drop))) (update :order (fn [o] (vec (drop-while (set drop) o))))))\n st))\n shown (fn [st] (mapv (fn [k] (get-in st [:named k])) (:order st)))\n done (fn [st] {:state st :show (shown st)})]\n (cond\n ;; a part of the view pressed (its own gesture): what that part is called goes out\n (and (vector? value) (= :pressed (first value)) (some? (second value))) {:out [[0 (second value)]]}\n (as-shape value) (let [k (keyword (str \"s\" (inc (:n st))))] (done (trim (put (assoc st :n (inc (:n st))) k (as-shape value)))))\n (and (sequential? value) (seq value) (every? draw-shape? value))\n (done (trim (reduce (fn [st [i f]] (put st (keyword (str \"s\" (inc i))) f))\n {:named {} :order [] :n (count value)} (map-indexed vector value))))\n ;; [:set k shape], or as a msg writes it: set k circle 10 10 4 kairos\n (and (vector? value) (= :set (first value)) (some? (second value))\n (or (as-shape (nth value 2 nil)) (as-shape (vec (drop 2 value)))))\n (done (trim (put st (second value) (or (as-shape (nth value 2 nil)) (as-shape (vec (drop 2 value)))))))\n (and (vector? value) (#{:unset :remove} (first value)))\n (done (-> st (update :named dissoc (second value)) (update :order (fn [o] (vec (remove #{(second value)} o))))))\n (#{:clear} value) (done {:named {} :order [] :n 0})\n :else {})))\n\n(define! \"draw\" {:doc \"A view drawn from the messages that arrive: each shape of kairotic.shapes ([:circle {:cx 40 :cy 40 :r 10 :fill :accent}], [:line …], [:path {:points [[x y] …]}], [:text {:x :y} \\\"…\\\"], [:curve …], [:group {:x :y :rotate} [shapes]]) is added — or as a msg writes it: :circle 40 40 10 :accent, :rect x y w h, :line x1 y1 x2 y2, :arc cx cy r from to, :text x y \\\"words\\\", with a colour and :hit name; a list of shapes replaces them all; [:set k shape] (:set k :circle …) adds or replaces the shape called k (to move a cursor), [:unset k] removes it, :clear empties it. A shape with :hit k, pressed, sends k out.\"\n :usage \"draw [width height]\"\n :io [1 1]\n :size (fn [b] (draw-size (:args b)))\n :receive draw-receive\n :draw (fn [{:keys [shown w h]}]\n (into [[:rect {:x 0.5 :y 0.5 :w (- w 1) :h (- h 1) :r 3 :stroke :grid :fill nil}]]\n (if (sequential? shown) shown [])))\n ;; a press on a shape with :hit: sent once, on release, as [:pressed k]\n :gesture (fn [{:keys [up hit]}] (when (and up (some? hit)) [:pressed hit]))})\n(define! \"mtof\" {:doc \"MIDI pitch → Hz (lists too).\" :receive (fn [{:keys [value]}] (if (or (number? value) (sequential? value)) {:out [[0 (map-num cv/midi->hz value)]]} {}))})\n(define! \"ftom\" {:doc \"Hz → MIDI pitch (lists too).\" :receive (fn [{:keys [value]}] (if (or (number? value) (sequential? value)) {:out [[0 (map-num cv/hz->midi value)]]} {}))})\n(doseq [[op-name op] [[\"+\" +] [\"-\" -] [\"*\" *] [\"/\" (fn [a b] (if (zero? b) 0 (/ a b)))]]]\n (define! op-name {:doc (str \"Arithmetic: left inlet \" op-name \" argument (or the last thing that came in on the right); lists too.\")\n :usage (str op-name \" n\") :io [2 1] :receive (arit op)}))\n;; the other way round, as in Max and Pd: !/ 1 turns a length in seconds into a frequency in Hz\n(doseq [[op-name op] [[\"!-\" (fn [a b] (- b a))] [\"!/\" (fn [a b] (if (zero? a) 0 (/ b a)))]]]\n (define! op-name {:doc (str \"Arithmetic the other way round: argument \" (subs op-name 1) \" left inlet (\" op-name \" 1 turns seconds into Hz); lists too.\")\n :usage (str op-name \" n\") :io [2 1] :receive (arit op)}))\n(define! \"metro\" {:doc \"Sends periodic bangs: 1 or bang starts it, 0 or :stop stops it.\" :usage \"metro ms\" :io [2 1] :receive metro})\n(define! \"counter\" {:doc \"Each bang sends the value and advances one step; goes back to the minimum on reaching the maximum.\" :usage \"counter step [max] [min]\" :io [2 1] :receive counter})\n(define! \"ramp\" {:doc \"Linear motion: a bang (or [a b s]) goes from a to b in s seconds; a number jumps there.\" :usage \"ramp a b s [loop]\" :io [2 1] :receive ramp})\n(define! \"canvas\" {:doc \"Graphic buffer for any numeric data: strokes in a plane with axes of any range, linear or log ((axis :b1 :y -1 1)). A number on the inlet (or a click) comes out on the left; edits on the inlet ([:stroke pts], [:erase :t1], [:clear], [:batch [...]]) change it, and questions ([:read x], [:strokes], [:get :t1], [:data]) are answered on the left. The right outlet is the buffer for a reader, which can read it along X or Y.\"\n :io [1 2] :display :canvas :receive (canvas-receiver cv/generic-empty) :model canvas-model})\n(define! \"freqt\" {:doc \"Graphic buffer of frequency over time: Hz on a log scale, time from 0, tunings (Scala) and bar grids, drawn as a canvas or as a score ((view :b1 :score), ⇄ in its header). A number on the inlet (or a click) comes out on the left; edits on the inlet ([:note t \\\"c4\\\" dur], [:stroke pts], [:erase :t1], [:clear], [:batch [...]]) change it, and questions ([:read t], [:strokes], [:end], [:data]) are answered on the left. The second outlet is the buffer for a reader. A musical tree on the inlet is shown over it, measured; shown as a score, the edits you make on that tree's notes leave by the third outlet ([:edit …]): connect it back to the tree box.\"\n :io [1 3] :display :canvas :views [:canvas :score] :receive canvas-box :model freqt-model})\n(define! \"reader\" {:doc \"Reads the buffer connected to its right inlet (canvas, freqt, ring) at the position that comes in on the left, in the buffer's own units — the X axis of a canvas (Y with `reader y`), the time of a freqt, the seconds of a ring — or, with `norm`, from 0 to 1, as reader~ does at audio rate. On a canvas or freqt: ids on the right and the values on the left (every crossing); with `reader path [stroke]` a position from 0 to 1 travels along a stroke in the order it was drawn and gives [x y]. On a ring: what it crosses, each value as it was written, either way (a move larger than its jump is a seek); or, without positions, it follows the ring's head d behind, then a speed (reader d 1 speed 0.5; msg :d, :speed, :jump, :stop).\"\n :usage \"reader [x|y|path [stroke]] [norm] [d s] [speed x] [jump s]\"\n :io [2 2] :receive reader :reads-buffer true})\n(doseq [[n io] [[\"state\" [1 1]] [\"transition\" [2 1]] [\"instruction\" [1 0]] [\"region\" [1 1]]]]\n (define! n {:doc \"Kairotic class with no semantics yet.\" :io io}))\n\n;; ───────── core: audio ─────────\n\n;; synth~ moved to the package @kairotic/synth (Study 14)\n\n(define! \"osc~\" {:doc \"Sine oscillator. A number on the left changes its frequency; a signal on the left (from reader~, sig~…) is its frequency in Hz.\"\n :usage \"osc~ [hz]\" :io [2 1]\n :receive (fn [{:keys [inlet value]}] (if (and (zero? inlet) (num-of value)) {:effects [[:freq (num-of value)]]} {}))\n :audio {:create (fn [ac c _] (let [o (.createOscillator ac) g (.createGain ac)\n base (atom (or (num-of (first (:args c))) 440))]\n (set! (.. o -frequency -value) @base)\n (set! (.. g -gain -value) 0.15)\n (.connect o g) (.start o)\n {:osc o :base base :inlets [[(.-frequency o) 0]] :outlets [[g 0]]}))\n :effects {:freq (fn [node x at] (reset! (:base node) x) (.linearRampToValueAtTime (.-frequency (:osc node)) x at))}\n ;; with a signal on the left the frequency is only that signal\n :wired (fn [node ins] (set! (.. (:osc node) -frequency -value) (if (contains? ins 0) 0 @(:base node))))\n :dispose (fn [node] (try (.stop (:osc node)) (catch :default _ nil)))}})\n(define! \"gain~\" {:doc \"Gain: signal on the left, factor on the right — a number, or a signal (an envelope, a reader~) that then is the factor.\"\n :usage \"gain~ [factor]\" :io [2 1]\n :receive (fn [{:keys [inlet value]}] (if (and (= 1 inlet) (num-of value)) {:effects [[:gain (num-of value)]]} {}))\n :audio {:create (fn [ac c _] (let [g (.createGain ac) base (atom (or (num-of (first (:args c))) 0.5))]\n (set! (.. g -gain -value) @base)\n {:g g :base base :inlets [[g 0] [(.-gain g) 0]] :outlets [[g 0]]}))\n :effects {:gain (fn [node x at] (reset! (:base node) x) (.setTargetAtTime (.-gain (:g node)) x at 0.01))}\n :wired (fn [node ins] (set! (.. (:g node) -gain -value) (if (contains? ins 1) 0 @(:base node))))}})\n(defn dac-channels\n \"The output channels of a dac~ (1-based): its numbers, or 1 2.\"\n [b] (let [cs (filterv (fn [x] (and (number? x) (>= x 1))) (:args b))] (if (seq cs) cs [1 2])))\n\n(define! \"dac~\" {:doc \"Audio output: each inlet is an output channel, the ones written after it (dac~ 1 2 by default; dac~ 1 2 3 4 … if the sound card has them).\"\n :usage \"dac~ [channel …]\"\n :io (fn [b] [(count (dac-channels b)) 0]) :dynamic-io true\n :receive (fn [_] {})\n :audio {:create (fn [_ b env]\n {:inlets (vec (for [c (dac-channels b)]\n [(or ((:channel env) (dec c)) (:silent env)) 0]))\n :outlets []})\n :key (fn [b] (dac-channels b))}})\n\n;; ───────── space ─────────\n;; pan~ and space~ moved to the package @kairotic/spatial (Study 14)\n\n;; ───────── core: ports of a sub-patch ─────────\n;; Seen from inside, an inlet only has an outlet and an outlet only has an inlet; seen from\n;; the parent patch they are the ports of the sub-patch box. They just pass on what arrives.\n\n(defn pass-on [{:keys [value]}] {:out [[0 value]]})\n\n(defn pass-audio [ac _ _]\n (let [g (.createGain ac)] {:inlets [[g 0]] :outlets [[g 0]] :g g}))\n\n(define! \"inlet\" {:doc \"An inlet of the sub-patch it is in (inlets are numbered left to right). Passes on the messages that arrive at it.\"\n :io [0 1] :receive pass-on})\n(define! \"outlet\" {:doc \"An outlet of the sub-patch it is in (numbered left to right). Sends out of the sub-patch what arrives at it.\"\n :io [1 0] :receive pass-on})\n(define! \"inlet~\" {:doc \"An audio inlet of the sub-patch it is in (numbered left to right, together with the message inlets).\"\n :io [0 1] :receive (fn [_] {}) :audio {:create pass-audio}})\n(define! \"outlet~\" {:doc \"An audio outlet of the sub-patch it is in (numbered left to right, together with the message outlets).\"\n :io [1 0] :receive (fn [_] {}) :audio {:create pass-audio}})\n\n(defn listing\n \"The registered components: [[class doc usage origin] …].\"\n []\n (vec (for [[k d] (sort-by key @registry)] [k (:doc d) (:usage d) (:origin d)])))\n","kairotic/core.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · shared core\n;; Utilities shared by all the studies: escaping text, encoding EDN ⇄ JSON\n;; without evaluating anything, and the REPL where every gesture is written as code.\n\n(ns kairotic.core\n (:require [clojure.string :as str]))\n\n(defn esc [s]\n (-> (str s)\n (str/replace \"&\" \"&\")\n (str/replace \"<\" \"<\")\n (str/replace \">\" \">\")\n (str/replace \"\\\"\" \""\")))\n\n;; ───────── EDN ⇄ JSON (for saving in the db) ─────────\n;; Keywords, names (symbols) and maps are tagged so they come back as EDN without evaluating foreign code.\n\n(defn enc [x]\n (cond (keyword? x) {\"k\" (if (namespace x) (str (namespace x) \"/\" (name x)) (name x))}\n ;; a name (a msg sends inc, e4, 6/5 as names): its whole text, tagged like a keyword\n (symbol? x) {\"y\" (str x)}\n (map? x) {\"m\" (mapv (fn [[k v]] [(enc k) (enc v)]) x)}\n (sequential? x) (mapv enc x)\n :else x))\n\n(defn dec* [x]\n (cond (map? x) (cond (contains? x \"k\") (keyword (str (get x \"k\")))\n (contains? x \"y\") (symbol (str (get x \"y\")))\n (contains? x \"m\") (into {} (for [kv (get x \"m\") :when (and (sequential? kv) (= 2 (count kv)))]\n [(dec* (first kv)) (dec* (second kv))]))\n :else nil)\n (sequential? x) (mapv dec* x)\n :else x))\n\n;; ───────── evaluation ─────────\n;; All the code from the REPL and from gestures is evaluated in the `user` namespace,\n;; where each page defines its commands.\n\n(defn eval-str [code]\n (js/scittle.core.eval_string (str \"(in-ns 'user)\\n\" code)))\n\n;; ───────── REPL ─────────\n\n(defonce repl-state (atom {:out nil :hist [] :hidx nil}))\n\n(defn repl-print! [cls html]\n (when-let [out (some-> (:out @repl-state) (js/document.getElementById))]\n (let [d (js/document.createElement \"div\")]\n (set! (.-className d) cls)\n (set! (.-innerHTML d) html)\n (.appendChild out d)\n (set! (.-scrollTop out) (.-scrollHeight out)))))\n\n(defn repl-eval!\n \"Evaluates code and shows it in the REPL. `source` is :repl (typed) or :gesture (generated by the interface).\"\n [code source]\n (repl-print! (str \"in\" (when (= source :gesture) \" from-patch\"))\n (str \"<span class=\\\"p\\\">\" (if (= source :gesture) \"⟵\" \"λ\") \"</span>\" (esc code)))\n (try\n (let [v (eval-str code)]\n (when (= source :repl) (repl-print! \"out\" (esc (pr-str v))))\n v)\n (catch :default e\n (repl-print! \"err\" (esc (or (.-message e) (str e))))\n nil)))\n\n(defn gesture!\n \"A gesture in the interface is written as code and evaluated: that way interface and code are the same thing.\"\n [code]\n (repl-eval! code :gesture))\n\n(defn mount-repl!\n \"Wires an input line and an output area (by id) as a REPL with ↑ ↓ history.\"\n [out-id in-id]\n (swap! repl-state assoc :out out-id)\n (let [inp (js/document.getElementById in-id)]\n (.addEventListener inp \"keydown\"\n (fn [e]\n (let [k (.-key e)]\n (cond\n (= k \"Enter\")\n (let [code (str/trim (.-value inp))]\n (when (seq code)\n (swap! repl-state (fn [s] (-> s (update :hist conj code) (assoc :hidx nil))))\n (set! (.-value inp) \"\")\n (repl-eval! code :repl)))\n (or (= k \"ArrowUp\") (= k \"ArrowDown\"))\n (let [{:keys [hist hidx]} @repl-state n (count hist)]\n (when (pos? n)\n (.preventDefault e)\n (let [i (if (= k \"ArrowUp\")\n (if (nil? hidx) (dec n) (max 0 (dec hidx)))\n (if (nil? hidx) nil (if (>= (inc hidx) n) nil (inc hidx))))]\n (swap! repl-state assoc :hidx i)\n (set! (.-value inp) (if (nil? i) \"\" (nth hist i))))))))))))\n","kairotic/corefns.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · corefns\n;; The functions of clojure.core (and clojure.string) as boxes, without writing a component for each\n;; (discussion #12): a box whose first word is one of them is that function. Its other words are its\n;; arguments, read as EDN; the message that arrives at the left inlet goes last, as with ->>:\n;;\n;; into [440] [1 2] → [440 1 2] take 3 [1 2 3 4] → [1 2 3]\n;; map inc [1 2] → [2 3] get % :freq {:freq 440} → 440\n;; conj % 440 [1 2] → [1 2 440] str/upper-case \"do\" → \"DO\"\n;;\n;; The text reads as Clojure, the inlets as Max: % puts the message somewhere else in the call\n;; (conj % 440, assoc % :freq 440, vector % 0 0), and whatever its place it is always the left inlet,\n;; the only hot one. The other arguments have an inlet each on the right, in the order they are written,\n;; which replaces them without sending; a bang on the left sends the last result again. A word that names\n;; one of these functions is that function (map inc, sort-by -).\n;;\n;; As in Clojure, data are functions too: a keyword (:freq, :freq 440 with a default), a set\n;; (#{60 64 67}: lets through only those) or a map ({60 :c 64 :e}: a table) written first is a box,\n;; and the message goes first: (:freq msg 440). A result that is nil sends nothing.\n;;\n;; ^:hot before the class (^:hot vector % 0 0) makes every inlet hot, like pak in Max: a new argument\n;; sends at once, with the last message (nil before the first one).\n;;\n;; Functions travel through the wires as their form, EDN data (issue #177): comp, partial, juxt,\n;; complement, fnil, constantly, every-pred and some-fn are boxes that send one, (comp inc (partial * 2)),\n;; and wherever a box takes an argument a name or such a form is that function: into the inlet of inc in\n;; map inc it changes the function live — msg dec too, since a msg sends a word without colon as a name.\n;; Nothing but these pure functions is ever made from a form.\n;;\n;; xf/ makes the transducer of a function into a box with memory, which goes through a stream of\n;; messages instead of a collection (clojure.org/reference/transducers):\n;;\n;; xf/partition-all 4 collects 4 messages and sends them as a vector (flush sends what is left)\n;; xf/partition 4 1 the last 4, at every message (a sliding window)\n;; xf/dedupe only when it changes · xf/take 1 the first one only (clear lets one more through)\n;;\n;; flush completes it (partition-all sends what it holds) and starts again; clear starts again without\n;; sending; a new argument on the right starts again too.\n;;\n;; Only pure functions are here (no evaluation of code, no time, no state of the page, nothing infinite),\n;; so these boxes are safe in a shared room: an xf/ box remembers only the messages that went through\n;; it. A result that is a sequence goes on as a vector, of at most 4096 elements. A class registered\n;; with the same name (+, -, print, mtof…) comes first.\n\n(ns kairotic.corefns\n (:require [clojure.string :as str]\n [clojure.edn :as edn]\n [kairotic.components :as comp]))\n\n(defn format*\n \"clojure.core/format, as Java's printf writes it, for what a patch needs: %s (str of the value), %d (an\n integer, rounded), %f %.2f (a number with that many decimals, 6 by default), %e, %x, %%, with a width\n (%5.1f, %-8s left-aligned, %05d with zeros) and %n for a new line. A directive with no value left, or a\n %d or %f with something that is not a number, writes it as %s does.\"\n [fmt & args]\n (let [re #\"%([-0]?)(\\d+)?(?:\\.(\\d+))?([sdfexn%])\"]\n (loop [out \"\" i 0 xs args]\n (if-let [m (.exec (js/RegExp. (.-source re) \"g\") (subs fmt i))]\n (let [[whole flag width prec conv] (vec (array-seq m))\n at (+ i (.-index m))\n lit (subs fmt i at)\n next-i (+ at (count whole))]\n (case conv\n \"%\" (recur (str out lit \"%\") next-i xs)\n \"n\" (recur (str out lit \"\\n\") next-i xs)\n (let [x (first xs)\n num? (number? x)\n body (cond\n (and (= conv \"d\") num?) (str (js/Math.round x))\n (and (= conv \"f\") num?) (.toFixed x (if prec (js/parseInt prec 10) 6))\n (and (= conv \"e\") num?) (.toExponential x (if prec (js/parseInt prec 10) 6))\n (and (= conv \"x\") num?) (.toString (js/Math.round x) 16)\n (string? x) x\n (nil? x) \"nil\"\n :else (str x))\n w (if width (js/parseInt width 10) 0)\n pad (max 0 (- w (count body)))\n body (cond (zero? pad) body\n (= flag \"-\") (str body (apply str (repeat pad \" \")))\n (and (= flag \"0\") num?) (if (str/starts-with? body \"-\")\n (str \"-\" (apply str (repeat pad \"0\")) (subs body 1))\n (str (apply str (repeat pad \"0\")) body))\n :else (str (apply str (repeat pad \" \")) body))]\n (recur (str out lit body) next-i (rest xs)))))\n (str out (subs fmt i))))))\n\n(def fns\n {;; collections\n \"into\" into \"conj\" conj \"cons\" cons \"concat\" concat \"vec\" vec \"set\" set \"seq\" seq \"list\" list \"vector\" vector\n \"hash-map\" hash-map \"first\" first \"second\" second \"last\" last \"rest\" rest \"next\" next \"butlast\" butlast\n \"nth\" nth \"count\" count \"empty?\" empty? \"not-empty\" not-empty \"reverse\" reverse \"sort\" sort \"sort-by\" sort-by\n \"distinct\" distinct \"dedupe\" dedupe \"flatten\" flatten \"frequencies\" frequencies \"group-by\" group-by\n \"take\" take \"drop\" drop \"take-last\" take-last \"drop-last\" drop-last \"take-nth\" take-nth\n \"take-while\" take-while \"drop-while\" drop-while \"interleave\" interleave \"interpose\" interpose\n \"partition\" partition \"partition-all\" partition-all \"partition-by\" partition-by \"split-at\" split-at\n \"map\" map \"mapv\" mapv \"mapcat\" mapcat \"map-indexed\" map-indexed \"filter\" filter \"filterv\" filterv\n \"remove\" remove \"keep\" keep \"reduce\" reduce \"reductions\" reductions \"apply\" apply \"some\" some\n \"every?\" every? \"range\" range \"repeat\" repeat \"zipmap\" zipmap \"identity\" identity\n ;; maps\n \"get\" get \"get-in\" get-in \"assoc\" assoc \"assoc-in\" assoc-in \"dissoc\" dissoc \"update\" update\n \"update-in\" update-in \"select-keys\" select-keys \"keys\" keys \"vals\" vals \"merge\" merge \"find\" find\n \"contains?\" contains?\n ;; numbers and comparison (+ - * / are boxes of their own)\n \"inc\" inc \"dec\" dec \"max\" max \"min\" min \"abs\" (fn [x] (js/Math.abs x)) \"quot\" quot \"rem\" rem \"mod\" mod \"max-key\" max-key\n \"min-key\" min-key \"=\" = \"not=\" not= \"<\" < \">\" > \"<=\" <= \">=\" >= \"zero?\" zero? \"pos?\" pos? \"neg?\" neg?\n \"even?\" even? \"odd?\" odd? \"number?\" number? \"not\" not \"nil?\" nil? \"some?\" some?\n ;; text and names\n \"str\" str \"format\" format* \"subs\" subs \"keyword\" keyword \"name\" name\n \"str/upper-case\" str/upper-case \"str/lower-case\" str/lower-case \"str/capitalize\" str/capitalize\n \"str/trim\" str/trim \"str/split\" str/split \"str/join\" str/join \"str/replace\" str/replace\n \"str/includes?\" str/includes? \"str/starts-with?\" str/starts-with? \"str/ends-with?\" str/ends-with?\n \"str/reverse\" str/reverse \"str/blank?\" str/blank?})\n\n(defn partition-xf\n \"The transducer clojure.core's partition does not have: (partition-xf n) or (partition-xf n step) sends\n every n messages as a vector, the next one starting step after the start of the last (step 1: a\n sliding window); like partition, an incomplete group at the end is not sent.\"\n ([n] (partition-xf n n))\n ([n step]\n (fn [rf]\n (let [buf (volatile! []) skip (volatile! 0)]\n (fn\n ([acc] (rf acc))\n ([acc x]\n (if (pos? @skip)\n (do (vswap! skip dec) acc)\n (let [b (vswap! buf conj x)]\n (if (< (count b) n)\n acc\n (do (vreset! buf (if (< step n) (subvec b step) []))\n (when (> step n) (vreset! skip (- step n)))\n (rf acc b)))))))))))\n\n;; the functions whose transducer can be an xf/ box (each one called with the box's arguments)\n(def xfs\n {\"map\" map \"map-indexed\" map-indexed \"keep\" keep \"keep-indexed\" keep-indexed \"mapcat\" mapcat\n \"filter\" filter \"remove\" remove \"take\" take \"drop\" drop \"take-while\" take-while \"drop-while\" drop-while\n \"take-nth\" take-nth \"partition-all\" partition-all \"partition-by\" partition-by \"partition\" partition-xf\n \"dedupe\" dedupe \"distinct\" distinct \"interpose\" interpose \"cat\" (fn [] cat)})\n\n(def max-items 4096)\n\n;; ───────── functions as values (issue #177) ─────────\n;; A function travels through the wires as its form, EDN data: (comp inc (partial * 2)). Where a box takes\n;; an argument, a name or such a form is the function, rebuilt in each browser from these same pure\n;; functions — nothing else is evaluated, so it is as safe in a shared room as any argument.\n\n(def builders\n \"The functions that make functions: as boxes they send a form; inside a form, they build it.\"\n {\"comp\" comp \"partial\" partial \"juxt\" juxt \"complement\" complement \"fnil\" fnil \"constantly\" constantly\n \"every-pred\" every-pred \"some-fn\" some-fn})\n\n;; names a form can use: the function boxes, the arithmetic that has boxes of its own, and the builders\n(def ^:private symbols\n (merge fns builders {\"+\" + \"-\" - \"*\" * \"/\" / \"identity\" identity}))\n\n(defn fn-form?\n \"A form that makes a function: a list whose first element names one of the builders.\"\n [x]\n (and (seq? x) (symbol? (first x)) (contains? builders (str (first x)))))\n\n(declare as-fn)\n\n(def ^:private build\n (memoize (fn [form] (apply (get builders (str (first form))) (map as-fn (rest form))))))\n\n(defn as-fn\n \"An argument as a box uses it: a name of one of these functions is that function, a form that makes one\n (comp …, partial …) is the function it makes; anything else stays as it is (a keyword is a function by\n itself, and a key).\"\n [x]\n (cond (symbol? x) (get symbols (str x) x)\n (fn-form? x) (build x)\n :else x))\n\n(defn unknown-names\n \"What, inside a form (or a word), is not one of these functions — a name it does not know, or a list\n that does not make a function ((inc 1) is a call, not a function): a form that has any cannot be made.\"\n [x]\n (cond (= x '%) []\n (symbol? x) (if (contains? symbols (str x)) [] [x])\n (fn-form? x) (vec (mapcat unknown-names (rest x)))\n (seq? x) [x]\n (coll? x) (vec (mapcat unknown-names x))\n :else []))\n\n(defn parse\n \"The arguments written after the class, as EDN data (a name or a form that makes a function stays\n as written, and becomes the function when it is called: as-fn), or {:error message}. Its metadata says\n whether the box is ^:hot.\"\n [text]\n (let [t (comp/strip-meta text)\n rest-text (str/trim (subs t (count (comp/klass t))))]\n (try (with-meta (vec (edn/read-string (str \"[\" rest-text \"]\")))\n {:hot (contains? (comp/meta-flags text) :hot)})\n (catch :default e {:error (str \"cannot read its arguments: \" (.-message e))}))))\n\n(defn slots\n \"The places of the arguments that have an inlet of their own (all but %), in the order they are written:\n inlet 1 replaces the first of them, inlet 2 the second…\"\n [args]\n (vec (keep-indexed (fn [i a] (when-not (= a '%) i)) args)))\n\n(defn- finite\n \"A result that can travel: a sequence becomes a vector (or an error, if it is too long).\"\n [r]\n (if (and (seq? r) (not (counted? r)))\n (let [v (vec (take (inc max-items) r))]\n (if (> (count v) max-items) (throw (js/Error. (str \"more than \" max-items \" elements\"))) v))\n (if (seq? r) (vec r) r)))\n\n(defn call\n \"f with its arguments and the message: at the place of % if there is one, else last (first when\n lead is true, as a keyword, a set or a map takes it).\"\n ([f args v] (call f args v false))\n ([f args v lead]\n (let [has% (some #{'%} args)\n args (map (fn [a] (if (= a '%) a (as-fn a))) args)]\n (finite (cond has% (apply f (map (fn [a] (if (= a '%) v a)) args))\n lead (apply f v args)\n :else (apply f (concat args [v])))))))\n\n(defn- fresh\n \"The state of a box for this text: the one it has if it was made for the same class and arguments, else\n a new one (the box was rewritten).\"\n [state n args]\n (if (= (:sig state) [n args]) state {:sig [n args]}))\n\n(defn- send-result [state v r]\n {:state (assoc state :last v) :out (if (nil? r) [] [[0 r]])})\n\n(defn receive\n \"A function box. Left inlet: calls the function with the message (a bang: with the last message, and\n the arguments as they are now). Other inlets: replace an argument, sending nothing — or, ^:hot,\n sending at once with the last message.\"\n [{:keys [f n lead]} {:keys [args state inlet value]}]\n (if (map? args)\n {:effects [[:print (:error args)]]}\n (let [state (fresh state n args)\n as (or (:args state) args)]\n (cond\n (pos? inlet)\n (if-let [i (get (slots args) (dec inlet))]\n (let [st (assoc state :args (assoc as i value))]\n (if (:hot (meta args))\n (send-result st (:last st) (call f (:args st) (:last st) lead))\n {:state st}))\n {:state state})\n (and (= value :bang) (not (contains? state :last))) {:state state}\n :else (let [v (if (= value :bang) (:last state) value)]\n (send-result state v (call f as v lead)))))))\n\n(defn- xf-instance\n \"A transducer of make with these arguments, ready to take messages: what it lets through gathers in :buf.\"\n [make args]\n (let [buf (volatile! [])\n rf ((apply make (map as-fn args)) (fn ([acc] acc) ([acc x] (vswap! buf conj x) acc)))]\n {:rf rf :buf buf :done false}))\n\n(defn- drain\n \"What an xf/ box let through since last time, as messages from its outlet (nil sends nothing).\"\n [st]\n (let [xs @(:buf st)]\n (vreset! (:buf st) [])\n (vec (keep (fn [x] (let [x (finite x)] (when (some? x) [0 x]))) xs))))\n\n(defn xf-receive\n \"An xf/ box: each message on the left goes through the transducer (a bang too: it is a message like any\n other); flush completes it and starts again, clear starts again; the inlets on the right replace an\n argument and start again.\"\n [{:keys [make n]} {:keys [args state inlet value]}]\n (if (map? args)\n {:effects [[:print (:error args)]]}\n (let [state (fresh state n args)\n as (or (:args state) args)\n st (if (:rf state) state (merge state (xf-instance make as)))]\n (cond\n (pos? inlet)\n (if-let [i (get (slots args) (dec inlet))]\n (let [as (assoc as i value)]\n {:state (merge (assoc st :args as) (xf-instance make as))})\n {:state st})\n (#{:clear} value) {:state (merge st (xf-instance make as))}\n (#{:flush} value) (do ((:rf st) nil)\n {:state (merge st (xf-instance make as)) :out (drain st)})\n (:done st) {:state st :out []}\n :else (let [r ((:rf st) nil value)]\n (if (reduced? r)\n (do ((:rf st) nil) {:state (assoc st :done true) :out (drain st)})\n {:state st :out (drain st)}))))))\n\n;; ───────── boxes that make functions ─────────\n\n(defn builder-receive\n \"A box that makes a function (comp inc (partial * 2)): it sends its form, which the boxes that take a\n function as an argument use as that function. Without %, any message on the left (a bang) sends it; with %,\n the message goes there (comp % inc composes the function that arrives) and a bang sends it again. The\n inlets on the right replace the other arguments, sending nothing (^:hot: sending). A form with a name that\n is not one of these functions is not sent: it is written in the REPL.\"\n [{:keys [n]} {:keys [args state inlet value]}]\n (if (map? args)\n {:effects [[:print (:error args)]]}\n (let [state (fresh state n args)\n as (or (:args state) args)\n has% (some #{'%} args)\n form (fn [as v] (apply list (symbol n) (if has% (map (fn [a] (if (= a '%) v a)) as) as)))\n send (fn [st v]\n (let [f (form (:args st as) v)\n bad (unknown-names f)]\n (if (seq bad)\n {:state st :effects [[:print (str n \": \" (str/join \", \" (distinct bad)) \" is not a function it knows\")]]}\n {:state (assoc st :last v) :out [[0 f]]})))]\n (cond\n (pos? inlet)\n (if-let [i (get (slots args) (dec inlet))]\n (let [st (assoc state :args (assoc as i value))]\n (if (and (:hot (meta args)) (or (not has%) (contains? st :last))) (send st (:last st)) {:state st}))\n {:state state})\n (not has%) (send state nil)\n (and (= value :bang) (not (contains? state :last))) {:state state}\n :else (send state (if (= value :bang) (:last state) value))))))\n\n;; ───────── what each kind of box is ─────────\n\n(defn data-fn\n \"A keyword, a set or a map written as the class, as the function it is in Clojure; nil for anything else.\"\n [n]\n (cond\n (re-matches #\":[^\\s\\[\\]{}()\\\"#,;]+\" n) (keyword (subs n 1))\n (re-find #\"^#?\\{\" n) (let [x (try (edn/read-string n) (catch :default _ nil))]\n (when (or (map? x) (set? x)) x))\n :else nil))\n\n(defn docs-url\n \"The page of a function at clojuredocs.org (clojure.core or clojure.string).\"\n [n]\n (let [[ns-name fname] (if (str/starts-with? n \"str/\") [\"clojure.string\" (subs n 4)] [\"clojure.core\" n])]\n (str \"https://clojuredocs.org/\" ns-name \"/\" (js/encodeURIComponent (str/replace fname \"?\" \"_q\")))))\n\n(def ^:private transducers-ref [\"Transducers\" \"https://clojure.org/reference/transducers\"])\n(def ^:private hot-ref [\"Metadata (^:hot)\" \"https://clojure.org/reference/metadata\"])\n\n(defn- clj-doc [n]\n (try (:doc (meta (get (ns-publics (if (str/starts-with? n \"str/\") 'clojure.string 'clojure.core))\n (symbol (str/replace n #\"^str/\" \"\")))))\n (catch :default _ nil)))\n\n(def ^:private how-fn\n (str \" as a box: the message at the left goes last among its arguments, or where % is, and is always the left\"\n \" inlet, the only hot one; the other inlets replace the other arguments, in the order they are written,\"\n \" without sending (^:hot before the class: sending); a bang sends the last result again; nil sends nothing.\"\n \" An argument that is a function (map inc) takes in its inlet another one: a form sent by comp, partial…\"))\n\n(defn- kind\n \"What a class name is: {:kind :fn|:builder|:data|:xf …}, or nil.\"\n [n]\n (cond\n (contains? fns n) {:kind :fn :f (get fns n) :n n}\n (contains? builders n) {:kind :builder :n n}\n (and (str/starts-with? n \"xf/\") (contains? xfs (subs n 3))) {:kind :xf :make (get xfs (subs n 3)) :n n}\n :else (when-let [f (data-fn n)] {:kind :data :f f :n n :lead true})))\n\n(defn- describe\n \"The :doc, :usage and :ref of a kind of box.\"\n [{:keys [kind n f]}]\n (case kind\n :builder {:doc (str \"clojure.core/\" n \" as a box that makes a function: it sends its form — (\" n \" …) as written —\"\n \" and a box that takes a function as an argument (map inc, xf/filter odd?, sort-by :freq…)\"\n \" uses it in that argument's inlet, changing it live. A bang sends it; with %, the message\"\n \" goes there (comp % inc composes the function that arrives). Inside, any function box\"\n \" names a function, + - * / too, and the forms nest: comp inc (partial * 2). Only the form\"\n \" travels, rebuilt in each browser from the same pure functions.\"\n (when-let [clj (clj-doc n)] (when (seq clj) (str \"\\n\\n\" clj))))\n :usage (str n \" [functions and arguments…] · bang sends it · % takes the message\")\n :ref [[(str \"clojure.core/\" n) (docs-url n)]\n [\"Higher-order functions\" \"https://clojure.org/guides/higher_order_functions\"]]}\n :fn (let [qual (str (if (str/starts-with? n \"str/\") \"clojure.string/\" \"clojure.core/\") (str/replace n #\"^str/\" \"\"))\n clj (clj-doc n)]\n {:doc (str qual how-fn (when (seq clj) (str \"\\n\\n\" clj)))\n :usage (str n \" [arguments…] · % marks where the message goes · ^:hot \" n \" …: every inlet hot\")\n :ref [[qual (docs-url n)] hot-ref]})\n :xf (let [base (subs n 3) clj (clj-doc base)]\n {:doc (str \"The transducer of clojure.core/\" base \" as a box with memory: it goes through the stream of messages\"\n \" that arrive at the left (a bang is one more message), not through a collection; what it lets\"\n \" through goes out one message at a time. flush completes it (partition-all sends what it holds)\"\n \" and starts again; clear starts again without sending; a new argument on the right starts again.\"\n (when (= base \"partition\") \" (partition n step: every n messages, each group starting step after the last; step 1 is a sliding window.)\")\n (when (seq clj) (str \"\\n\\n\" clj)))\n :usage (str n \" [arguments…] · flush · clear\")\n :ref [[(str \"clojure.core/\" base) (docs-url base)] transducers-ref]})\n :data (let [[what anchor] (cond (keyword? f) [\"A keyword\" \"Keywords\"] (set? f) [\"A set\" \"Sets\"] :else [\"A map\" \"Maps\"])]\n {:doc (str what \" as a function, as in Clojure: the message goes first, (\" n \" msg)\"\n (cond (keyword? f) \" — its value under that key, or the argument written after it if there is none\"\n (set? f) \" — the message if it is in the set, nothing if not: a filter\"\n :else \" — what the map has under the message, or the argument after it: a table\")\n \"; nil sends nothing. The other inlets replace the arguments, without sending (^:hot: sending).\")\n :usage (str n (when (keyword? f) \" [default]\"))\n :ref [[(str what \" as a function\") (str \"https://clojure.org/reference/data_structures#\" anchor)] hot-ref]})))\n\n(def ^:private defs (atom {}))\n\n(defn definition\n \"The class of a box named after one of these functions, an xf/ transducer, or a keyword, set or map (made\n once, then kept), or nil.\"\n [n]\n (when-let [k (and (string? n) (seq n) (kind n))]\n (or (get @defs n)\n (let [d (merge {:class n :origin :core :display :text :corefn true\n :parse parse\n :io (fn [{:keys [text]}] (let [a (parse text)] [(inc (if (map? a) 0 (count (slots a)))) 1]))\n :dynamic-io true\n :receive (case (:kind k)\n :xf (fn [m] (xf-receive k m))\n :builder (fn [m] (builder-receive k m))\n (fn [m] (receive k m)))}\n (describe k))]\n (swap! defs assoc n d)\n d))))\n\n(defn names \"The functions that can be boxes, the ones that make functions, and the xf/ transducers.\" []\n (vec (concat (sort (keys fns)) (sort (keys builders)) (sort (map #(str \"xf/\" %) (keys xfs))))))\n\n(swap! comp/fallbacks (fn [fs] (if (some #{definition} fs) fs (conj fs definition))))\n\n;; ───────── dispatch: a message to one of several outlets ─────────\n;; dispatch n has n outlets, numbered from 0 as every port is. What comes in on the left goes out by the one the\n;; selector chooses; the selector comes in on the right (and may be written after n): a number k is outlet k,\n;; nil or false closes the way (nothing goes out), true is outlet 0 (dispatch 1 as an open/closed gate). A function\n;; — a name, a form (comp …), a keyword, a map — chooses for each message: what it gives for the message is the\n;; outlet (a number, true, or nil/false to let nothing through); a set lets its members through outlet 0.\n\n(defn- dispatch-of\n \"The outlet a selector sends message v to among n, or nil.\"\n [sel v n]\n (let [r (cond (or (nil? sel) (false? sel)) nil\n (true? sel) 0\n (number? sel) sel\n (set? sel) (when (contains? sel v) 0)\n :else ((as-fn sel) v))\n r (if (true? r) 0 r)]\n (when (and (number? r) (integer? r) (<= 0 r) (< r n)) r)))\n\n(defn- dispatch-n [args] (let [n (first args)] (if (and (number? n) (>= n 1)) (js/Math.floor n) 2)))\n\n(defn dispatch-receive [{:keys [args state inlet value]}]\n (if (map? args)\n {:effects [[:print (:error args)]]}\n (let [n (dispatch-n args)\n st (if (= (:sig state) args) state {:sig args :sel (second args)})]\n (if (pos? inlet)\n (let [bad (when (or (symbol? value) (seq? value)) (unknown-names value))]\n (if (seq bad)\n {:state st :effects [[:print (str \"dispatch: \" (str/join \", \" (distinct bad)) \" is not a function it knows\")]]}\n {:state (assoc st :sel value) :show (pr-str value)}))\n (let [k (try (dispatch-of (:sel st) value n) (catch :default _ nil))]\n {:state st :out (if k [[k value]] [])})))))\n\n(comp/define! \"dispatch\"\n {:doc (str \"A message to one of several outlets, numbered from 0: dispatch n has n of them. The right inlet chooses\"\n \" the way: a number k is outlet k; nil or false closes it (nothing goes out); true is outlet 0, so dispatch 1\"\n \" is a gate that opens and closes. A function chooses for each message — a name or a form\"\n \" (comp …, partial …), a keyword, a map ({60 0 64 1}): what it gives for the message is the outlet, nil\"\n \" lets nothing through — and a set lets its members through outlet 0. The selector can be written after n\"\n \" (dispatch 3 0, dispatch 2 {60 0 64 1}); a msg sends it as written (msg 1, msg nil, msg :freq). Named after the\"\n \" dispatch function of Clojure's multimethods, which looks at a value and chooses where it goes.\")\n :usage \"dispatch n [selector] · right: k · nil · true · a function, keyword, map or set\"\n :io (fn [{:keys [text]}] (let [a (parse text)] [2 (if (map? a) 1 (dispatch-n a))]))\n :dynamic-io true\n :parse parse\n :receive dispatch-receive\n :ref [[\"Multimethods: a dispatch function chooses\" \"https://clojure.org/reference/multimethods\"]\n [\"Truthiness: nil and false\" \"https://clojure.org/guides/learn/flow#_truth\"]\n [\"Maps, sets and keywords as functions\" \"https://clojure.org/reference/data_structures\"]]})\n","kairotic/engine.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · engine\n;; Makes the patch work without knowing anything about concrete classes: it asks everything of the\n;; component registry (kairotic.components). It routes outlets along the lines, keeps a queue of\n;; future messages and processes everything a little ahead of the AudioContext clock, so that\n;; sound effects are scheduled at the exact instant (`at`).\n;; What is sounding lives in this tab and does not enter the history of the work.\n;;\n;; Messages and time (Study 21): messages travel whenever something sends them — a click, a gesture,\n;; a data box that changed — with or without ▶. ▶ starts what needs a clock: the sound (audio nodes) and\n;; time (the queue of future messages: metro, ramp, mt play, loadbang). A message that comes back to\n;; the same box too many times in one instant is a loop without time: it is cut, and said so.\n\n(ns kairotic.engine\n (:require [clojure.string :as str]\n [kairotic.components :as comp]\n [kairotic.canvas :as cv]\n [kairotic.span :as span]))\n\n(defonce ctx* (atom nil))\n(defn ctx [] (or @ctx* (reset! ctx* (js/AudioContext.))))\n(defn now [] (.-currentTime (ctx)))\n\n(defonce rt (atom {:on false :shows {} :prints []}))\n\n(def lookahead 0.12)\n\n;; compatibility with code that already used these functions from the engine\n(def klass comp/klass)\n(def args-of comp/args-of)\n(def num-of comp/num-of)\n\n(defn def-of [p id] (comp/lookup (comp/klass (get-in p [:boxes id :text]))))\n(defn audio? [p id] (boolean (:audio (def-of p id))))\n\n;; ───────── sub-patches: the engine works on a flat patch ─────────\n;; Every embedded `patch` box and every instance of an abstraction is replaced by its boxes, with\n;; ids prefixed by the path (:b5 inside :b2 → :b2.b5). A line to port i of a sub-patch goes to its\n;; i-th inlet box, and a line from port o comes from its o-th outlet box.\n\n(def max-depth 8)\n\n(defn flat-id\n \"The id of box `id` of the sub-patch at `path` in the flat patch.\"\n [path id]\n (if (empty? path) id (keyword (str (str/join \".\" (map name path)) \".\" (name id)))))\n\n(defn substitute\n \"$1 $2 … in a box text → the words written after the class of the instance.\"\n [text words]\n (str/replace (str text) #\"\\$(\\d)\"\n (fn [[_ n]] (or (get words (dec (js/parseInt n 10))) \"0\"))))\n\n(defn line-ref\n \"The line a `patch @name` box uses (discussion #117): name, or nil for any other box.\"\n [b]\n (let [[k r] (str/split (str/trim (str (:text b))) #\"\\s+\")]\n (when (and (= k \"patch\") r (str/starts-with? r \"@\") (> (count r) 1)) (subs r 1))))\n\n;; how the page reads a line used as a sub-patch: (fn [box] patch) — the page knows the lines and their\n;; histories; the engine only asks\n(defonce line-resolver (atom nil))\n\n(defn inner-patch\n \"The patch inside a box: the data of an embedded `patch`, the line a `patch @name` uses, or the :patch\n of an abstraction with its $-arguments filled in. nil for any other box.\"\n [b]\n (let [k (comp/klass (:text b)) d (comp/lookup k)]\n (cond\n (and (= k \"patch\") (line-ref b)) (or (when-let [f @line-resolver] (f b)) {:boxes {} :lines []})\n (= k \"patch\") (or (:data b) {:boxes {} :lines []})\n (map? (:patch d)) (let [words (vec (rest (str/split (str/trim (str (:text b))) #\"\\s+\")))]\n (update (:patch d) :boxes\n (fn [bs] (into {} (for [[id ib] bs] [id (update ib :text substitute words)])))))\n :else nil)))\n\n(defn flatten-patch\n ([p] (flatten-patch p [] 0))\n ([p path depth]\n (let [subs (into {} (for [[id b] (:boxes p) :let [inner (when (< depth max-depth) (inner-patch b))] :when inner]\n [id inner]))\n ports (into {} (for [[id inner] subs] [id (comp/patch-ports inner)]))\n flats (for [[id inner] subs] (flatten-patch inner (conj path id) (inc depth)))\n own (into {} (for [[id b] (:boxes p) :when (not (contains? subs id))] [(flat-id path id) b]))\n from (fn [a o] (if-let [pt (get ports a)]\n (when-let [x (get (:outlets pt) o)] [(flat-id (conj path a) x) 0])\n [(flat-id path a) o]))\n to (fn [b i] (if-let [pt (get ports b)]\n (when-let [x (get (:inlets pt) i)] [(flat-id (conj path b) x) 0])\n [(flat-id path b) i]))]\n {:boxes (apply merge own (map :boxes flats))\n :lines (vec (concat (keep (fn [[a o b i]] (let [s (from a o) t (to b i)] (when (and s t) (into s t)))) (:lines p))\n (mapcat :lines flats)))})))\n\n(defonce flat-cache (atom [nil nil]))\n\n(defn flat\n \"flatten-patch, remembered for the last patch (the engine asks for it on every tick).\"\n [p]\n (let [[k v] @flat-cache]\n (if (identical? k p) v (let [f (flatten-patch p)] (reset! flat-cache [p f]) f))))\n\n(defn patch [] (if-let [f (:patch-fn @rt)] (flat (f)) {:boxes {} :lines []}))\n\n;; ───────── audio ─────────\n\n(defn dispose! [node]\n (try (when-let [f (get-in node [:def :audio :dispose])] (f node)) (catch :default e (js/console.error e)))\n (doseq [[n _] (:outlets node)] (try (.disconnect n) (catch :default _ nil))))\n\n(defn updates? [d] (fn? (get-in d [:audio :update])))\n\n(defn signature\n \"What the audio graph depends on: [boxes lines texts]. A box whose class can :update itself is known\n by its class (and :key), so a new text does not rebuild it; its text goes in `texts` instead.\"\n [p]\n (let [audio (for [[id b] (:boxes p) :let [d (comp/lookup (comp/klass (:text b)))] :when (:audio d)] [id b d])]\n [(into (sorted-map)\n (for [[id b d] audio]\n [id [(if (updates? d) (comp/klass (:text b)) (:text b))\n (when-let [f (get-in d [:audio :key])] (f (comp/box-info b)))]]))\n (vec (filter (fn [[a _ b _]] (and (audio? p a) (audio? p b))) (:lines p)))\n (into (sorted-map) (for [[id b d] audio :when (updates? d)] [id (:text b)]))]))\n\n(defn forget!\n \"Forgets what a box holds while it sounds (its state and what it showed): after its text changes,\n the text is what counts.\"\n [id]\n (swap! rt (fn [r] (-> r (update :states dissoc id) (update :shows dissoc id)))))\n\n(defn sync!\n \"Fits the audio nodes to the patch: creates the missing ones, removes those left over or changed,\n redoes the connections, and tells the nodes that :update themselves about a new text.\"\n []\n (let [p (patch) [boxes lines texts :as s] (signature p) old (:signature @rt)]\n (when (not= (take 2 s) (take 2 old))\n (doseq [[id node] (:nodes @rt) :when (not= (get boxes id) (:signature node))]\n (dispose! node)\n (swap! rt update :nodes dissoc id))\n (doseq [[id sig] boxes :when (not (get-in @rt [:nodes id]))]\n (let [b (get-in p [:boxes id]) d (comp/lookup (comp/klass (:text b)))]\n (try\n ;; :create gets the box (text, args, data) with its id and its current state\n (when-let [node ((get-in d [:audio :create]) (ctx) (assoc (comp/box-info b) :id id :state (get-in @rt [:states id])) (:env @rt))]\n (swap! rt assoc-in [:nodes id] (assoc node :signature sig :def d :text (:text b))))\n (catch :default e (js/console.error \"could not create the audio of\" (str id) e)))))\n (doseq [[_ node] (:nodes @rt) [n _] (:outlets node)] (try (.disconnect n) (catch :default _ nil)))\n (doseq [[a o b i] lines]\n (let [[sn so] (get-in @rt [:nodes a :outlets o]) [dn di] (get-in @rt [:nodes b :inlets i])]\n ;; an inlet can also be an AudioParam (a frequency, a gain): the signal is added to its value\n (when (and sn dn) (try (if (instance? js/AudioParam dn) (.connect sn dn so) (.connect sn dn so di))\n (catch :default e (js/console.error e))))))\n ;; every node learns which of its inlets receive a signal (osc~ and gain~ then let it take over)\n (doseq [[id node] (:nodes @rt) :let [f (get-in node [:def :audio :wired])] :when f]\n ;; only lines that carry a signal: a message line (a msg, a number) into gain~'s right inlet sets it, it does not take over\n (try (f node (set (keep (fn [[a o b i]] (when (and (= b id) (get-in @rt [:nodes a :outlets o])) i)) lines))) (catch :default e (js/console.error e))))\n (swap! rt update :states (fn [ss] (into {} (filter (fn [[id _]] (get-in p [:boxes id])) ss)))))\n ;; a new text for a node that updates itself: no new node, the node takes the new arguments\n (when (not= (nth s 2) (nth old 2 nil))\n (doseq [[id text] texts :let [node (get-in @rt [:nodes id])] :when (and node (not= text (:text node)))]\n (forget! id)\n (swap! rt assoc-in [:nodes id :text] text)\n (try ((get-in node [:def :audio :update]) node (assoc (comp/box-info (get-in p [:boxes id])) :id id) (now))\n (catch :default e (js/console.error e)))))\n (swap! rt assoc :signature s)))\n\n(defn print!\n \"Something to write in the REPL at instant at; label: the name of the print box that wrote it (print out0).\"\n ([at x] (print! at x nil))\n ([at x label] (swap! rt update :prints (fn [ps] (conj (vec (take-last 200 ps)) (if label [at x label] [at x]))))))\n\n;; ───────── tasks: what a box asks of the world, outside its pure logic ─────────\n;; A component declares :tasks {k (fn [x box] promise)}, as an audio component declares :audio :effects.\n;; Its :receive asks for one with the effect [k x]; the engine runs it and the outcome comes back to the\n;; same box on inlet :task, as {:task k :arg x :value v} or {:task k :arg x :error \"…\"}, one more\n;; message: what the box does with it (:out, :show, :state, :effects [[:keep d]]) stays in its pure logic.\n;; It works with or without ▶, and what it finds lives in this tab, like what is sounding: only [:keep d]\n;; turns it into a gesture of the work (the data of the box, in the history, the same for everyone).\n\n(def ^:dynamic *remote*\n \"True while a message that another performer played (a jam) is delivered here: what it makes is\n theirs to keep, so [:keep …] from it is not written again by this tab.\"\n false)\n\n(declare inject!)\n\n(defn arrive!\n \"The outcome of a task reaches its box on inlet :task, now (it came from outside: there is no instant\n of the score to wait for). A box that was deleted meanwhile gets nothing.\"\n [id value remote?]\n (when-let [f (:patch-fn @rt)]\n (binding [*remote* remote?]\n (try (inject! f id :task value) (catch :default e (js/console.error e))))))\n\n(defn task-of\n \"The task k of box id, or nil. Only a class that declares a task of that name sends the engine to the\n patch to find out (an effect of an audio box while ■ falls here too, and often).\"\n [id k]\n (when (some (fn [d] (contains? (:tasks d) k)) (vals @comp/registry))\n (get-in (def-of (patch) id) [:tasks k])))\n\n(defn wired\n \"What the outlets of box id reach in patch p: [{:outlet o :inlet i :id to :class \\\"faust~\\\" :text … :data …} …],\n for a task that needs to know what it drives (realize~ learns the faust~ it plays).\"\n [p id]\n (vec (for [[a o b i] (:lines p) :when (= a id) :let [t (get-in p [:boxes b])] :when t]\n (assoc (comp/box-info t) :outlet o :inlet i :id b :class (comp/klass (:text t))))))\n\n(defn run-task! [id f k x]\n (let [remote? *remote*\n p (patch)\n box (assoc (comp/box-info (get-in p [:boxes id])) :id id :state (get-in @rt [:states id]) :wired (wired p id))]\n (-> (js/Promise.resolve nil)\n (.then (fn [_] (f x box)))\n (.then (fn [v] (arrive! id {:task k :arg x :value v} remote?))\n (fn [e] (arrive! id {:task k :arg x :error (str (or (.-message e) e))} remote?))))))\n\n(defn effect! [id [k x label] at]\n (cond\n (= k :print) (print! at x label)\n ;; a box keeps what it found (a task's outcome) as its data: a gesture of whoever made it happen\n (= k :keep) (when-not *remote* (when-let [f (:effect-hook @rt)] (f id [k x] at)))\n ;; effects for the page (a tree box asked to change its data: that is a gesture of the work; a presets\n ;; box asked to recall, morph or generate: issue #35)\n (#{:tree-edit :tree-set :canvas-edit :presets :sample} k) (when-let [f (:effect-hook @rt)] (f id [k x] at))\n ;; on its audio node (the common case, many per second: looked up first)\n (get-in @rt [:nodes id :def :audio :effects k])\n (let [node (get-in @rt [:nodes id])]\n (try ((get-in node [:def :audio :effects k]) node x at) (catch :default e (js/console.error e))))\n :else\n (when-let [f (task-of id k)] (run-task! id f k x))))\n\n;; ───────── messages ─────────\n\n(defonce tree-bufs (atom {})) ; box → [tree buffer]: a tree turned into a buffer once, not on every tick\n\n(defn tree-buffer\n \"The buffer of the musical tree a canvas, freqt or score shows (Study 23): one stroke per note.\"\n [id tree]\n (let [[t b] (get @tree-bufs id)]\n (if (identical? t tree)\n b\n (let [b (when-let [f @comp/tree-buffer] (try (f tree) (catch :default _ nil)))]\n (swap! tree-bufs assoc id [tree b])\n b))))\n\n(defn buffer-of\n \"The canvas (or freqt) connected to the right inlet of a box: [id data]. A box that shows a musical\n tree gives that tree as its buffer, so a reader~ plays what the score shows.\"\n [p id]\n (some (fn [[a _ b i]]\n (cond\n (not (and (= b id) (= i 1))) nil\n ;; a ring is what it keeps now (the state of its box), for the boxes that read messages from it\n (= \"ring\" (comp/klass (get-in p [:boxes a :text])))\n (when (#{\"reader\" \"writer\"} (comp/klass (get-in p [:boxes id :text])))\n [a (or (get-in @rt [:states a])\n (span/ring (comp/num-of (first (comp/args-of (get-in p [:boxes a :text]))))))])\n ;; a ring~ is its node (kairotic.ringaudio): the reader~ and writer~ on it take a slot there\n (= \"ring~\" (comp/klass (get-in p [:boxes a :text])))\n (when (#{\"reader~\" \"writer~\"} (comp/klass (get-in p [:boxes id :text])))\n [a (get-in @rt [:nodes a :ring])])\n (#{\"canvas\" \"freqt\" \"sample\" \"tree\"} (comp/klass (get-in p [:boxes a :text])))\n ;; a tree box is its tree (discussion #92); a canvas or freqt, the tree it shows, else its buffer\n (let [k (comp/klass (get-in p [:boxes a :text]))\n tree (if (= \"tree\" k)\n (:tree (get-in p [:boxes a :data]))\n (get-in @rt [:states a :tree]))]\n [a (or (when tree (tree-buffer a tree))\n (when (= \"tree\" k) cv/empty)\n (get-in p [:boxes a :data]) (:empty (comp/model-of (get-in p [:boxes a]))) cv/empty)])))\n (:lines p)))\n\n(defn show! [id at v]\n (swap! rt update-in [:shows id] (fn [q] (conj (vec (take-last 31 q)) [at v]))))\n\n(defn shown-at\n \"The last thing a box showed up to instant `t`: [at value] or nil.\"\n [id t]\n (last (filter (fn [[at _]] (<= at t)) (get-in @rt [:shows id]))))\n\n(defn enqueue! [at id inlet value]\n (swap! rt update :queue (fn [q] (vec (sort-by first (conj (or q []) [at id inlet value]))))))\n\n(defonce counter (atom 0))\n(defonce visits (atom {})) ; box → messages it got in this instant\n(def loop-limit 100)\n\n(defn fresh-instant! [] (reset! counter 0) (reset! visits {}))\n\n(defn loop-cut!\n \"Stops a message that came back to the same box too many times in one instant (a loop without time).\"\n [id at]\n (when-not (contains? (:loops @rt) id)\n (swap! rt update :loops (fnil conj #{}) id)\n (print! at (str \"loop cut at \" (name id) \": a message came back to it \" loop-limit\n \" times in one instant. A loop needs time (metro, a delay) or a box that only sends what changed.\"))))\n\n;; ───── probes (discussion #183): what goes out of the outlets someone is watching ─────\n;; The page puts a probe on a wire; what is watched is the outlet it leaves from ([box outlet], flat ids), since\n;; every wire from one outlet carries the same messages. With no probe, nothing is kept.\n\n(defonce probes (atom #{})) ; #{[flat-id outlet]}\n(defonce probe-seen (atom {})) ; [flat-id outlet] → {:v last value :at its instant :n how many :times [ms …]}\n\n(defn probe!\n \"Something left outlet o of box id: kept if that outlet is watched.\"\n [id o v at]\n (when (and (seq @probes) (contains? @probes [id o]))\n (let [t (.now js/performance)]\n (swap! probe-seen update [id o]\n (fn [s] {:v v :at at :n (inc (:n s 0))\n ;; the times of the last ones, for a rate over the last second\n :times (conj (vec (take-last 99 (:times s))) t)})))))\n\n(defn deliver! [p id inlet value at]\n (cond\n (>= (swap! counter inc) 20000)\n (when (= 20000 @counter) (print! at \"too many messages in one instant (20000): the rest are not delivered\"))\n (> (get (swap! visits update id (fnil inc 0)) id) loop-limit)\n (loop-cut! id at)\n :else\n (when-let [b (get-in p [:boxes id])]\n (let [d (comp/lookup (comp/klass (:text b)))]\n (when-let [f (:receive d)]\n (let [[bid bdata] (when (:reads-buffer d) (buffer-of p id))\n r (try (f {:id id :state (get-in @rt [:states id]) :args (comp/args-for d (:text b)) :data (:data b)\n :inlet inlet :value value :at at :buffer bdata :buffer-id bid})\n (catch :default e\n {:effects [[:print (str (comp/klass (:text b)) \" \" (name id) \": \" (or (.-message e) e))]]}))]\n (when (map? r)\n (when (contains? r :state) (swap! rt assoc-in [:states id] (:state r)))\n (when (contains? r :show) (show! id at (:show r)))\n (doseq [e (:effects r)] (effect! id e at))\n (doseq [[at2 inl v] (:later r)] (enqueue! at2 id inl v))\n (doseq [[o v] (:out r)]\n (probe! id o v at)\n (doseq [[a oo bb ii] (:lines p)\n :when (and (= a id) (= oo o))]\n (deliver! p bb ii v at))))))))))\n\n(defn report!\n \"From the sound back to the messages: an audio node gives its own box a value it found (a level, a\n block of samples, an error). It reaches the box's :receive on inlet :audio at instant `at` (the time\n of the sound it was found in), as one more message of the queue, so what the box does with it (:out,\n :show, :state) stays in its pure logic. Only while the engine runs, and only for a box that sounds.\"\n [id value at]\n (when (and (:on @rt) (get-in @rt [:nodes id]))\n (enqueue! (if (number? at) at (now)) id :audio value)))\n\n(reset! comp/audio-report report!)\n\n;; an audio node asks the page for something itself (a recording to keep as the data of its box), even\n;; when the engine has just stopped and no message can reach its box any more\n(reset! comp/audio-effect (fn [id e] (effect! id e (now))))\n\n(defn feed!\n \"Audio nodes that read a buffer (:audio :feed) get it again whenever it changes.\"\n []\n (let [p (patch)]\n (doseq [[id node] (:nodes @rt) :let [f (get-in node [:def :audio :feed])] :when (and f (:fed node))]\n (let [[_ data] (buffer-of p id)]\n ;; by value: the same canvas rebuilt (the history recomputed after any change) is not new\n (when-not (or (identical? data @(:fed node)) (= data @(:fed node)))\n (reset! (:fed node) data)\n (try (f node data) (catch :default e (js/console.error e))))))))\n\n(defn tick! []\n (when (:on @rt)\n (try\n (sync!)\n (feed!)\n (when-let [f @comp/after-feed] (try (f (patch) (:nodes @rt) (:signature @rt)) (catch :default e (js/console.error e))))\n (fresh-instant!)\n (let [limit (+ (now) lookahead) p (patch)]\n (loop []\n (let [e (first (:queue @rt))]\n (when (and e (<= (first e) limit) (< @counter 20000))\n (swap! rt update :queue (fn [q] (vec (rest q))))\n (let [[at id inl v] e] (deliver! p id inl v (max at (now))))\n (recur)))))\n (catch :default ex (js/console.error ex)))))\n\n(defn running? [] (boolean (:on @rt)))\n\n;; ───────── output: one input per channel of the sound card ─────────\n;; Every channel has its own mono input (dac~ 1 → channel 1); they meet in a merger, go through the\n;; master gain and, in stereo, through a gentle compressor. The sound card's channels are used if it\n;; has more than two.\n\n(defn explicit! [node n interpretation]\n (set! (.-channelCount node) n)\n (set! (.-channelCountMode node) \"explicit\")\n (set! (.-channelInterpretation node) interpretation))\n\n(defn output! [ac]\n (let [dest (.-destination ac)\n n (max 2 (min 32 (or (.-maxChannelCount dest) 2)))]\n (try (explicit! dest n \"discrete\") (catch :default _ nil))\n (let [n (or (.-channelCount dest) 2)\n merger (.createChannelMerger ac n)\n master (.createGain ac)\n silent (.createGain ac)\n ins (vec (for [i (range n)]\n (let [g (.createGain ac)] (explicit! g 1 \"speakers\") (.connect g merger 0 i) g)))]\n (set! (.. master -gain -value) 0.8)\n (set! (.. silent -gain -value) 0)\n (explicit! master n \"discrete\")\n (.connect merger master)\n (if (= n 2)\n (let [c (.createDynamicsCompressor ac)] (.connect master c) (.connect c dest) {:master master :comp c :ins ins :n n :silent silent})\n (do (.connect master dest) {:master master :ins ins :n n :silent silent})))))\n\n(defn start!\n \"Starts the engine (if it was not running). With `loadbang?`, fires the loadbang boxes.\"\n [patch-fn loadbang?]\n (let [ac (ctx)]\n (.resume ac)\n (when-not (:on @rt)\n (let [{:keys [master] :as out} (output! ac)]\n ;; the state boxes got from messages before ▶ (a tree kept by mt play) stays\n (swap! rt assoc :on true :patch-fn patch-fn :nodes {} :queue [] :signature nil\n :master master :out out :prints []\n :env {:master master :channels (:n out) :silent (:silent out)\n :channel (fn [i] (get (:ins out) i))})\n (sync!)\n (swap! rt assoc :timer (js/setInterval tick! 25))))\n (when loadbang?\n (let [p (patch) at (+ (now) 0.05)]\n (fresh-instant!)\n (doseq [[id b] (:boxes p) :when (= \"loadbang\" (comp/klass (:text b)))]\n (deliver! p id 0 :bang at))))))\n\n(defn stop! []\n (when (:on @rt)\n (js/clearInterval (:timer @rt))\n (doseq [[_ node] (:nodes @rt)] (dispose! node))\n (try (.disconnect (:master @rt)) (catch :default _ nil))\n (swap! rt assoc :on false :queue [] :nodes {} :states {} :signature nil)))\n\n(defn message-time [] (if (:on @rt) (+ (now) 0.03) (now)))\n\n(defn inject!\n \"A gesture (or the REPL) sends a message to a box right now. It travels with or without ▶; without it\n there is no sound and no time (what a box asks for later only happens with ▶ on).\"\n [patch-fn id inlet value]\n (swap! rt assoc :patch-fn patch-fn :loops #{})\n (when (:on @rt) (sync!))\n (fresh-instant!)\n (deliver! (patch) id inlet value (message-time)))\n\n(defn emit!\n \"A box sends a value out of its outlet o, as if it had produced it (a data box that changed).\"\n [patch-fn id o value]\n (swap! rt assoc :patch-fn patch-fn)\n (when (:on @rt) (sync!))\n (fresh-instant!)\n (let [p (patch) at (message-time)]\n (probe! id o value at)\n (doseq [[a oo bb ii] (:lines p) :when (and (= a id) (= oo o))]\n (deliver! p bb ii value at))))\n\n(defn emit-to!\n \"Like emit!, but only along the lines from outlet o that reach one of `targets` ([box inlet] pairs):\n a value sent again only where it is needed (a new line, a box that changed).\"\n [patch-fn id o value targets]\n (swap! rt assoc :patch-fn patch-fn)\n (when (:on @rt) (sync!))\n (fresh-instant!)\n (let [p (patch) at (message-time)]\n (probe! id o value at)\n (doseq [[a oo bb ii] (:lines p) :when (and (= a id) (= oo o) (contains? targets [bb ii]))]\n (deliver! p bb ii value at))))\n\n(defn node [id] (get-in @rt [:nodes id]))\n\n(defn take-prints!\n \"The prints whose instant has already arrived (and removes them from the queue).\"\n []\n (let [t (now) [due later] ((juxt filter remove) (fn [[at _]] (<= at t)) (:prints @rt))]\n (when (seq due) (swap! rt assoc :prints (vec later)))\n due))\n","kairotic/faust.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · faust~\n;; A Faust code box. The official compiler (faustwasm, WebAssembly) is downloaded the\n;; first time it is needed; each source is compiled in this tab and runs as an AudioWorklet.\n;; The box's audio inlets and outlets are those of the compiled `process`; the left inlet\n;; also receives messages for its parameters (hslider, nentry, button…):\n;; [:freq 440] → the freq parameter (msg :freq 440)\n;; 440 → freq (or the first parameter if there is no freq)\n;; [440 660 …] → freq = the first one, gate = 1 (empty list → gate = 0): this way a reader plays a faust~\n;;\n;; Polyphonic: a source that declares declare options \"[nvoices:8]\"; (the Faust convention, as in the\n;; Faust IDE) is compiled as voices, each with its freq, gain and gate, played by faustwasm's own\n;; allocator (one AudioWorklet; a voice taken from the oldest when they run out), and an optional\n;; effect = …; in the same source, applied once to the sum of the voices. Then, as synth~:\n;; [440 550 660] on the left · voice ids on the right (a keyboard, a reader, mt play): each id a voice;\n;; a new id starts a note, one that disappears releases it, one whose pitch changes plays it again ·\n;; a number: one voice · [:gain 0.5] the velocity of the next notes · :stop releases them all ·\n;; [:cutoff 1200] any other parameter, for every voice (or for the effect).\n;; Notes are sent as MIDI pitches with decimals (its allocator turns them into Hz without rounding),\n;; so any tuning sounds as written.\n\n(ns kairotic.faust\n (:refer-clojure :exclude [load])\n (:require [clojure.string :as str]\n [kairotic.components :as comp]\n [kairotic.code :as code]))\n\n(defonce loading (atom nil))\n\n(defn load\n \"Promise of the compiler: {F: the faustwasm module, compiler: FaustCompiler}.\"\n []\n (or @loading (reset! loading ((.-kairoticLoadFaust js/window)))))\n\n(defn hash-text [s]\n (let [h (reduce (fn [h c] (bit-or 0 (+ (* h 31) (.charCodeAt c 0)))) 7 (str s))]\n (.toString (js/Math.abs h) 36)))\n\n(defn params-of\n \"Walks Faust's interface description and returns the input controls.\"\n [ui]\n (vec (mapcat (fn walk [it]\n (let [kind (.-type it)]\n (cond\n (some? (.-items it)) (mapcat walk (array-seq (.-items it)))\n (contains? #{\"hslider\" \"vslider\" \"nentry\" \"button\" \"checkbox\"} kind)\n [{:label (.-label it) :address (.-address it) :type kind\n :min (or (.-min it) 0) :max (or (.-max it) 1) :init (or (.-init it) 0) :step (or (.-step it) 0)}]\n :else [])))\n (array-seq ui))))\n\n(defn poly-voices\n \"The number of voices a source declares (declare options \\\"[nvoices:8]\\\"), or nil: then it is mono.\"\n [source]\n (when-let [[_ n] (re-find #\"declare\\s+options\\s+\\\"[^\\\"]*\\[\\s*nvoices\\s*:\\s*(\\d+)\\s*\\]\" (str source))]\n (max 1 (min 64 (js/parseInt n 10)))))\n\n;; the controls of a voice its allocator sets itself, note by note: not parameters of the box\n(def voice-controls #{\"freq\" \"gain\" \"gate\" \"key\" \"vel\" \"velocity\"})\n\n(defn voice-control? [p] (contains? voice-controls (last (str/split (str (:address p)) #\"/\"))))\n\n(defn compile-mono [fx source dsp-name]\n (let [gen (js/Reflect.construct (.-FaustMonoDspGenerator (.-F fx)) #js [])]\n (-> (.compile gen (.-compiler fx) dsp-name source \"-ftz 2\")\n (.then (fn [g]\n (when (nil? g) (throw (js/Error. \"Faust could not compile this source\")))\n (let [meta (js/JSON.parse (.. gen -factory -json))]\n {:value gen\n :info {:name dsp-name :ins (.-inputs meta) :outs (.-outputs meta)\n :params (params-of (.-ui meta))\n :summary (str (.-inputs meta) \" in · \" (.-outputs meta) \" out · \" (count (params-of (.-ui meta))) \" params\")}}))))))\n\n(defn compile-poly\n \"Voices, and the effect if the source has one (faustwasm compiles `effect` from the same source).\"\n [fx source dsp-name n]\n (let [gen (js/Reflect.construct (.-FaustPolyDspGenerator (.-F fx)) #js [])]\n (-> (.compile gen (.-compiler fx) dsp-name source \"-ftz 2\")\n (.then (fn [g]\n (when (or (nil? g) (nil? (.-voiceFactory gen))) (throw (js/Error. \"Faust could not compile this source\")))\n (let [vm (js/JSON.parse (.. gen -voiceFactory -json))\n em (some-> (.-effectFactory gen) .-json js/JSON.parse)\n vps (params-of (.-ui vm))\n ps (vec (concat (remove voice-control? vps) (when em (params-of (.-ui em)))))\n outs (if em (.-outputs em) (.-outputs vm))]\n (when-not (some (fn [p] (= \"freq\" (last (str/split (str (:address p)) #\"/\")))) vps)\n (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);\")))\n {:value gen\n :info {:name dsp-name :poly n :effect (some? em) :ins (.-inputs vm) :outs outs :params ps\n :summary (str n \" voices\" (when em \" + effect\") \" · \" outs \" out · \" (count ps) \" params\")}}))))))\n\n(code/register-language! \"faust\"\n (fn [source]\n (-> (load)\n (.then (fn [fx]\n (let [dsp-name (str \"k\" (hash-text source))]\n (if-let [n (poly-voices source)]\n (compile-poly fx source dsp-name n)\n (compile-mono fx source dsp-name))))))))\n\n(defn info [c] (:info (code/compiled \"faust\" (get-in c [:data :source]))))\n\n(defn find-param [node pname]\n (let [ps (get-in node [:info :params])]\n (or (first (filter (fn [p] (= (:label p) pname)) ps))\n (first (filter (fn [p] (str/ends-with? (:address p) (str \"/\" pname))) ps)))))\n\n(defn set-param! [node p v at]\n (swap! (:values node) assoc (:label p) v)\n ;; its copies elsewhere (in a ring~'s node, when it is in a loop of the ring: kairotic.ringaudio) follow it\n (doseq [f (vals @(:mirrors node))] (f (:address p) v))\n (if-let [n @(:faust node)]\n (.setParamValue n (:address p) v (max at (.-currentTime (.-context n))))\n (swap! (:pending node) assoc (:address p) v)))\n\n(defn param! [node [pname v] at]\n (when-let [p (find-param node (name pname))]\n (when (number? v) (set-param! node p v at))))\n\n(defn freqs! [node v at]\n (let [fs (if (number? v) [v] (filter number? v))\n pf (or (find-param node \"freq\") (when (number? v) (first (get-in node [:info :params]))))\n pg (find-param node \"gate\")]\n (if (seq fs)\n (do (when pf (set-param! node pf (first fs) at))\n (when (and pg (sequential? v)) (set-param! node pg 1 at)))\n (when pg (set-param! node pg 0 at)))))\n\n;; ───── voices (polyphonic) ─────\n\n(defn hz->pitch\n \"A frequency as the MIDI pitch faustwasm's allocator takes (with decimals: it does not round).\"\n [hz] (+ 69 (* 12 (/ (js/Math.log (/ hz 440)) (js/Math.log 2)))))\n\n(defn voices!\n \"Plays the voices {:pairs [[id hz] …] :vel 0…1}: an id that is new starts a note, one that is gone\n releases it, one whose pitch changed plays it again (one note per id, as synth~).\"\n [node {:keys [pairs vel]} at]\n (if-let [n @(:faust node)]\n (let [t (max at (.-currentTime (.-context n)))\n old @(:voices node)\n incoming (into {} (for [[id hz] (take (* 2 (or (get-in node [:info :poly]) 8)) pairs)\n :when (and (number? hz) (pos? hz) (js/isFinite hz))]\n [id (hz->pitch hz)]))\n v (js/Math.round (* 127 (max 0 (min 1 (if (number? vel) vel 0.8)))))]\n (doseq [[id p] old :when (not= p (get incoming id))] (.keyOff n 0 p 0 t))\n (doseq [[id p] incoming :when (not= p (get old id))] (.keyOn n 0 p (max 1 v) t))\n (reset! (:voices node) incoming))\n ;; the node is still being made: what it should play when it is ready\n (reset! (:want node) [{:pairs pairs :vel vel} at])))\n\n(defn create [ac c _]\n (let [r (code/compiled \"faust\" (get-in c [:data :source]))\n inf (:info r)\n ins (or (:ins inf) 0) outs (max 1 (or (:outs inf) 1))\n merger (when (pos? ins) (.createChannelMerger ac ins))\n splitter (.createChannelSplitter ac outs)\n node {:inlets (if merger (vec (for [i (range ins)] [merger i])) [])\n :outlets (vec (for [o (range outs)] [splitter o]))\n :merger merger :splitter splitter :info inf\n :faust (atom nil) :pending (atom {}) :alive (atom true) :voices (atom {}) :want (atom nil) :mirrors (atom {})\n :values (atom (into {} (for [p (:params inf)] [(:label p) (:init p)])))}]\n (when (= :ok (:status r))\n (-> (if (:poly inf) (.createNode (:value r) ac (:poly inf) (:name inf)) (.createNode (:value r) ac (:name inf)))\n (.then (fn [n]\n (when (and n @(:alive node))\n (when merger (.connect merger n))\n (.connect n splitter)\n (doseq [[a v] @(:pending node)] (.setParamValue n a v))\n (reset! (:faust node) n)\n (when-let [[w at] @(:want node)] (reset! (:want node) nil) (voices! node w at)))))\n (.catch (fn [e] (js/console.error \"faust~\" e)))))\n node))\n\n(defn dispose [node]\n (reset! (:alive node) false)\n (when-let [n @(:faust node)]\n (try (when (get-in node [:info :poly]) (.allNotesOff n true)) (.disconnect n) (.destroy n) (catch :default _ nil))))\n\n(defn receive-poly\n \"The messages of a polyphonic faust~ (see the header): as synth~, with ids on the right.\"\n [{:keys [state inlet value]}]\n (let [st (if (map? state) state {})\n vel (:vel st)\n play (fn [pairs] {:state (dissoc st :ids) :effects [[:voices {:pairs pairs :vel vel}]]})]\n (cond\n (= inlet 1) {:state (assoc st :ids (if (sequential? value) (vec value) [value]))}\n (not (zero? inlet)) {}\n (and (vector? value) (#{:gain :vel :velocity} (first value)) (number? (second value)))\n (let [v (second value)] {:state (assoc st :vel (if (> v 1) (/ (min v 127) 127) (max 0 v)))})\n (and (vector? value) (or (keyword? (first value)) (string? (first value)))) {:effects [[:param value]]}\n (number? value) (play (if (pos? value) [[:v0 value]] []))\n (= value :stop) (play [])\n (sequential? value)\n (let [fs (filterv number? value)\n ids (:ids st)\n ids (if (= (count ids) (count fs)) ids (mapv (fn [i] (keyword (str \"v\" i))) (range (count fs))))]\n (play (mapv vector ids fs)))\n :else {})))\n\n(def template\n \"import(\\\"stdfaust.lib\\\");\nfreq = hslider(\\\"freq\\\", 440, 40, 2000, 0.01);\ngate = button(\\\"gate\\\");\ncutoff = hslider(\\\"cutoff\\\", 2400, 200, 8000, 1);\nprocess = os.sawtooth(freq) * en.adsr(0.01, 0.15, 0.6, 0.4, gate) * 0.25 : fi.lowpass(2, cutoff);\")\n\n(comp/define! \"faust~\"\n {: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.\"\n :usage \"faust~\"\n :display :code :language \"faust\" :model code/model :template template\n :dynamic-io true\n ;; polyphonic, a second inlet for the voice ids (as synth~)\n :io (fn [c] (let [i (info c)] [(max (if (:poly i) 2 1) (or (:ins i) 0)) (max 1 (or (:outs i) 1))]))\n :params (fn [c] (:params (info c)))\n :receive (fn [{:keys [inlet value data] :as m}]\n (cond\n (:poly (info {:data data})) (receive-poly m)\n (not (zero? inlet)) {}\n (and (vector? value) (or (keyword? (first value)) (string? (first value)))) {:effects [[:param value]]}\n (or (number? value) (sequential? value)) {:effects [[:freqs value]]}\n :else {}))\n :audio {:create create :dispose dispose\n :key (fn [c] [(get-in c [:data :source]) (:status (code/compiled \"faust\" (get-in c [:data :source])))])\n :effects {:param param! :freqs freqs! :voices voices!}}})\n","kairotic/help.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · help\n;; What each box class is for, port by port, with a small patch that shows it working (like the help\n;; patches of Pd and Max). A component can carry its own help in its definition (:help, same shape);\n;; this file is the help of the core classes, and of the official packages until they ship their own.\n;;\n;; {:inlets [\"what the left inlet takes\" …] one line per inlet, left to right\n;; :outlets [\"what the left outlet gives\" …]\n;; :messages [[\"bang\" \"what it does\"] …] words and values it understands (optional)\n;; :example \"(box :b1 …)\\n(connect …)\" a help patch, as patch code (optional)\n;; :try \"something to do with the example\" (optional)\n;; :steps [{:title \"…\" :note \"…\" :try \"…\" :example \"…\"} …]\n;; more uses, after the :example: the help patch opens as a lesson, one step each, every\n;; step adding its lines to the patch of the step before (◀ ▶ travel between them) (optional)\n;; :see [\"other\" \"classes\"] (optional)\n;; :ref [[\"label\" \"https://…\"] …] outer documentation, opened in a new tab (optional;\n;; the boxes of clojure.core carry theirs: clojuredocs.org)\n;; :package \"@kairotic/synth\" when the class comes from a package\n;; :doc :usage only for classes the page may not have loaded yet}\n\n(ns kairotic.help\n (:require [clojure.string :as str]\n [kairotic.components :as comp]))\n\n(def lines (fn [& ls] (str/join \"\\n\" ls)))\n\n(def core\n {\"loadbang\"\n {:outlets [\"a bang when the engine starts (▶)\"]\n :example (lines \"(box :b1 \\\"loadbang\\\" 40 30)\" \"(box :b2 \\\"print\\\" 40 90)\" \"(connect :b1 0 :b2 0)\")\n :try \"Press ▶: the bang arrives at print, which writes it in the REPL.\"\n :see [\"bang\" \"metro\"]}\n\n \"bang\"\n {:inlets [\"anything: it flashes and sends a bang\"]\n :outlets [\"bang\"]\n :messages [[\"click\" \"sends a bang\"]]\n :example (lines \"(box :b1 \\\"bang\\\" 40 30)\" \"(box :b2 \\\"counter 1\\\" 40 90)\" \"(box :b3 \\\"print\\\" 40 150)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\")\n :try \"Start the engine and click the bang: each click counts one more.\"\n :see [\"msg\" \"loadbang\" \"metro\"]}\n\n \"msg\"\n {:inlets [\"anything (or a click): sends its content\"]\n :outlets [\"its content, read as in Clojure: a number, a keyword with its colon (:stop), a name (inc, e4, https://…), true false nil, a string between quotes (\\\"two words\\\"), an EDN form ([0 4 7], {:freq 440}), or a list of them; empty, a bang\"]\n :example (lines \"(box :b1 \\\"msg 60\\\" 40 30)\" \"(box :b2 \\\"msg 67\\\" 110 30)\" \"(box :b3 \\\"mtof\\\" 40 90)\"\n \"(box :b4 \\\"osc~ 261.63\\\" 40 140)\" \"(box :b5 \\\"gain~ 0.3\\\" 40 190)\" \"(box :b6 \\\"dac~\\\" 40 240)\"\n \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b4 0 :b5 0)\"\n \"(connect :b5 0 :b6 0)\" \"(connect :b5 0 :b6 1)\")\n :try \"Start the engine and click the two messages: two MIDI pitches become two frequencies.\"\n :messages [[\"msg :stop\" \"a keyword: what boxes understand as an order (:stop, :rec 4, :clear)\"]\n [\"msg inc\" \"a name: a function where a box takes one (map inc), or free text (e4, 6/5, a URL)\"]\n [\"msg [0 4 7] {:freq 440}\" \"EDN forms, read whole\"]]\n :ref [[\"EDN\" \"https://github.com/edn-format/edn\"] [\"Keywords and symbols\" \"https://clojure.org/reference/data_structures#Keywords\"]]\n :see [\"number\" \"bang\"]}\n\n \"number\"\n {:inlets [\"a number sets it and sends it on; a bang sends it again\"]\n :outlets [\"the number\"]\n :messages [[\"drag\" \"up and down changes it (and sends it); let go, the number stays in its text, as a knob's does\"]\n [\"double-click\" \"type a number (Enter sends it, Esc closes); so too knobs and the sliders of faust~\"]]\n :example (lines \"(box :b1 \\\"number 440\\\" 40 30)\" \"(box :b2 \\\"osc~ 440\\\" 40 90)\" \"(box :b3 \\\"gain~ 0.3\\\" 40 140)\"\n \"(box :b4 \\\"dac~\\\" 40 190)\" \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\"\n \"(connect :b3 0 :b4 0)\" \"(connect :b3 0 :b4 1)\")\n :try \"Start the engine and drag the number: the oscillator follows. Let it go: its text keeps the new number (back in the history, it goes back).\"\n :see [\"msg\" \"knob\"]}\n\n \"print\"\n {:inlets [\"anything: it is written in the REPL, after the label (print out0 → out0: 60)\"]\n :example (lines \"(box :b1 \\\"msg 440.1234\\\" 40 30)\" \"(box :b2 \\\"print freq\\\" 40 90)\"\n \"(box :b3 \\\"format \\\\\\\"%.1f Hz\\\\\\\"\\\" 180 90)\" \"(box :b4 \\\"print\\\" 180 150)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b1 0 :b3 0)\" \"(connect :b3 0 :b4 0)\")\n :try \"Click the msg: the REPL writes freq: 440.1234 and print: 440.1 Hz.\"\n :see [\"msg\" \"format\" \"str\"]}\n\n \"draw\"\n {:inlets [\"a shape ([:circle {:cx 40 :cy 40 :r 10 :fill :accent}]) is added; a list of shapes replaces them all; [:set k shape] adds or replaces the one called k; [:unset k] removes it; clear\"]\n :outlets [\"the :hit of a shape pressed (a shape with :hit k sends k)\"]\n :messages [[\"[:circle {:cx :cy :r}]\" \"a circle (also :rect :line :arc :needle :path :curve :text and :group)\"]\n [\"[[:line …] [:text …]]\" \"a list: replaces everything\"]\n [\"[:set :cursor [:line …]]\" \"the shape called :cursor, added or moved\"]\n [\"[:unset :cursor]\" \"removes it\"] [\":clear\" \"empties the view\"]]\n :example (lines \"(box :b1 \\\"msg :circle 60 55 22 :accent :hit :sun\\\" 40 30)\"\n \"(box :b2 \\\"msg :circle 160 55 14 :kairos :hit :moon\\\" 360 30)\"\n \"(box :b3 \\\"msg :set :label :text 20 100 \\\\\\\"press one of them\\\\\\\"\\\" 40 70)\"\n \"(box :b4 \\\"draw 240 120\\\" 40 120)\" \"(box :b5 \\\"print\\\" 40 270)\"\n \"(connect :b1 0 :b4 0)\" \"(connect :b2 0 :b4 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b4 0 :b5 0)\")\n :try \"Click the three messages, then press the circles: print writes :sun or :moon. From code, any shape of kairotic.shapes: (send! :b4 [:curve {:points [[10 90] [80 20] [150 80] [230 30]] :stroke :accent}]). Shapes take the theme's colours (:ink :soft :accent :kairos :bg :grid) and :opacity.\"\n :see [\"monitor\" \"pcclock\" \"msg\"]}\n\n \"mtof\"\n {:inlets [\"a MIDI pitch (60 = middle C) or a list of them\"]\n :outlets [\"the frequency in Hz (or the list)\"]\n :example (lines \"(box :b1 \\\"number 69\\\" 40 30)\" \"(box :b2 \\\"mtof\\\" 40 90)\" \"(box :b3 \\\"print\\\" 40 150)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\")\n :try \"Drag the number: 69 is A4, 440 Hz; every 12 steps the frequency doubles.\"\n :see [\"ftom\" \"osc~\"]}\n\n \"ftom\"\n {:inlets [\"a frequency in Hz or a list of them\"]\n :outlets [\"the MIDI pitch, with decimals for what falls between keys\"]\n :see [\"mtof\"]}\n\n \"+\" {:inlets [\"a number or a list: it adds the right one and sends the result\" \"the number to add (stored, nothing is sent)\"]\n :outlets [\"the sum\"]\n :example (lines \"(box :b1 \\\"number 60\\\" 40 30)\" \"(box :b2 \\\"number 7\\\" 130 30)\" \"(box :b3 \\\"+ 7\\\" 40 90)\" \"(box :b4 \\\"print\\\" 40 150)\"\n \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b3 1)\" \"(connect :b3 0 :b4 0)\")\n :try \"The right inlet only stores: change it, then drag the left number to hear (read) the result. A fifth above is + 7.\"\n :see [\"-\" \"*\" \"/\"]}\n \"-\" {:inlets [\"a number or a list: minus the right one\" \"the number to subtract (stored)\"] :outlets [\"the difference\"] :see [\"+\"]}\n \"*\" {:inlets [\"a number or a list: times the right one\" \"the factor (stored)\"] :outlets [\"the product\"] :see [\"+\" \"/\"]}\n \"/\" {:inlets [\"a number or a list: divided by the right one (0 if it is 0)\" \"the divisor (stored)\"] :outlets [\"the quotient\"] :see [\"*\" \"!/\"]}\n \"!/\" {:inlets [\"a number or a list: what divides the right one (0 if it is 0)\" \"the dividend (stored)\"] :outlets [\"the quotient: !/ 1 gives 1 / the number\"] :see [\"/\" \"sample\"]}\n \"!-\" {:inlets [\"a number or a list: subtracted from the right one\" \"the minuend (stored)\"] :outlets [\"the difference\"] :see [\"-\"]}\n\n \"metro\"\n {:inlets [\"bang, 1 or :start: starts · 0 or :stop: stops\" \"the interval in ms\"]\n :outlets [\"a bang every interval\"]\n :example (lines \"(box :b1 \\\"msg 1\\\" 40 30)\" \"(box :b2 \\\"msg 0\\\" 100 30)\" \"(box :b3 \\\"metro 250\\\" 40 90)\"\n \"(box :b4 \\\"counter 1 8\\\" 40 150)\" \"(box :b5 \\\"print\\\" 40 210)\"\n \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b4 0 :b5 0)\")\n :try \"Start the engine, then 1 and 0: a pulse that counts from 0 to 7.\"\n :see [\"counter\" \"ramp\" \"loadbang\"]}\n\n \"counter\"\n {:inlets [\"bang (or a number): sends the value and advances one step · :reset: back to the minimum\" \"a number sets the next value\"]\n :outlets [\"the value\"]\n :see [\"metro\"]}\n\n \"dispatch\"\n {:inlets [\"a message: goes out by the outlet the selector chooses (or by none)\"\n \"the selector: k (outlet k, from 0) · nil or false (closed) · true (outlet 0) · a function, keyword or map that chooses for each message · a set (its members by outlet 0)\"]\n :outlets [\"outlet 0\" \"outlet 1 … (dispatch n has n)\"]\n :messages [[\"msg 1\" \"every message by outlet 1\"] [\"msg nil\" \"nothing goes out\"]\n [\"msg {60 0 64 1}\" \"60 by outlet 0, 64 by outlet 1, anything else by none\"]\n [\"msg :to\" \"each message by the outlet its :to says ({:freq 440 :to 1})\"]]\n :example (lines \"(box :b1 \\\"msg 60\\\" 40 30)\" \"(box :b2 \\\"msg 64\\\" 100 30)\" \"(box :b3 \\\"msg 67\\\" 160 30)\"\n \"(box :b4 \\\"msg 0\\\" 260 30)\" \"(box :b5 \\\"msg 1\\\" 320 30)\" \"(box :b6 \\\"msg nil\\\" 380 30)\" \"(box :b7 \\\"msg {60 0 64 1}\\\" 470 30)\"\n \"(box :b8 \\\"dispatch 2\\\" 40 100)\" \"(box :b9 \\\"print out0\\\" 40 170)\" \"(box :b10 \\\"print out1\\\" 200 170)\"\n \"(connect :b1 0 :b8 0)\" \"(connect :b2 0 :b8 0)\" \"(connect :b3 0 :b8 0)\"\n \"(connect :b4 0 :b8 1)\" \"(connect :b5 0 :b8 1)\" \"(connect :b6 0 :b8 1)\" \"(connect :b7 0 :b8 1)\"\n \"(connect :b8 0 :b9 0)\" \"(connect :b8 1 :b10 0)\")\n :try \"Click a selector on the right (0, 1, nil or the map) and then the notes on the left: each note goes out by the way chosen — the REPL says which, out0 or out1 — or by none. With the map, 60 and 64 choose their own way and 67 is held back.\"\n :see [\"msg\" \"get\"]}\n\n \"ramp\"\n {:inlets [\"bang: goes from a to b in s seconds · [a b s]: that motion · a number: jumps there · :stop\" \"1 / 0: loop on or off\"]\n :outlets [\"the moving value\"]\n :example (lines \"(box :b1 \\\"loadbang\\\" 40 30)\" \"(box :b2 \\\"ramp 220 880 4 loop\\\" 40 90)\" \"(box :b3 \\\"osc~ 220\\\" 40 150)\"\n \"(box :b4 \\\"gain~ 0.3\\\" 40 200)\" \"(box :b5 \\\"dac~\\\" 40 250)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b4 0 :b5 0)\" \"(connect :b4 0 :b5 1)\")\n :try \"Press ▶: a glissando of two octaves in four seconds, again and again.\"\n :see [\"metro\" \"reader\" \"phasor~\"]}\n\n \"presets\"\n {:inlets [\"a keyframe to recall: its number (1 = the first) or its label · bang: a new preset · [:generate seed] · [:morph a b t] · keep\"\n \"a position between keyframes: 1.5 morphs halfway from the first to the second\"]\n :outlets [\"the values of the controls it set: {:b3 0.5 :b5 880}\"]\n :messages [[\"2 · intro\" \"recalls that keyframe: every box takes its text of then, as one event of the history\"]\n [\"1.5 (right)\" \"moves the controls (knobs, envelopes…) between two keyframes, as messages, as a drag does\"]\n [\":keep\" \"writes the last morph into the texts of the controls, as one event\"]\n [\"bang · [:generate 42]\" \"a new preset: what is the same in every keyframe stays, what changes takes a value within its range\"]\n [\"(keyframes) · (recall 2) · (morph 1 2 0.5) · (morph :keep) · (generate 42)\" \"the same from the REPL, with every keyframe of the work\"]\n [\"(store-presets! :bN) · (presets! :bN […])\" \"keeps its keyframes in the box (only what changes): then it uses them, and they travel with the patch in its code, links and embeds\"]]\n :example (lines \"(box :b1 \\\"msg 1\\\" 40 30)\" \"(box :b2 \\\"msg 2\\\" 100 30)\" \"(box :b3 \\\"bang\\\" 160 30)\"\n \"(box :b4 \\\"knob 1 2 1\\\" 230 20)\" \"(box :b5 \\\"presets\\\" 40 120)\"\n \"(box :b6 \\\"knob 100 1000 220 log\\\" 40 180)\" \"(box :b7 \\\"osc~ 220\\\" 40 280)\"\n \"(box :b8 \\\"gain~ 0.2\\\" 40 330)\" \"(box :b9 \\\"dac~\\\" 40 380)\"\n \"(connect :b1 0 :b5 0)\" \"(connect :b2 0 :b5 0)\" \"(connect :b3 0 :b5 0)\" \"(connect :b4 0 :b5 1)\"\n \"(connect :b6 0 :b7 0)\" \"(connect :b7 0 :b8 0)\" \"(connect :b8 0 :b9 0)\" \"(connect :b8 0 :b9 1)\")\n :try \"Press ◆ Snapshot, turn the lower knob and press ◆ again: two keyframes. Start the engine: 1 and 2 recall them, the knob on the right morphs between them, and the bang makes a new preset in between.\"\n :see [\"knob\" \"patch\"]}\n\n \"canvas\"\n {:inlets [\"a position (or a click): it comes out on the left · an edit ([:stroke [[x y] …]], [:erase :t1], [:clear], [:axis :y 0 1]… or [:batch [edits]]): it changes the buffer, as one event · a question ([:read x], [:strokes], [:get :t1], [:count], [:end], [:range], [:data]): the answer comes out on the left · a musical tree: shown over it\"]\n :outlets [\"the position, or the answer to a question\" \"the buffer, for a reader or reader~ (on their right inlet)\"]\n :messages [[\"(axis :bN :x -1 1)\" \"range of an axis, :log for logarithmic\"] [\"(stroke :bN [[x y] …])\" \"draws\"]\n [\"the corner · (resize :bN 640 300)\" \"drag its bottom-right corner to resize it; a double-click there brings back its size\"]\n [\"[:stroke [[0 0] [1 1]]] · [:stroke :t3 pts]\" \"a stroke by message (a new id, or that one)\"]\n [\"[:move :t1 dx dy] · [:stretch :t1 k] · [:erase :t1] · [:clear]\" \"edit strokes by message\"]\n [\"[:axis :x lo hi] · [:axis :y lo hi :log] · [:grid-y step]\" \"axes and grid by message\"]\n [\"[:batch [[:clear] [:stroke pts] …]]\" \"several edits, one event of the history\"]\n [\"[:read 0.5] · [:read :y 0.2] · [:strokes] · [:get :t1] · [:count] · [:range] · [:data]\" \"questions: the answer comes out on the left\"]\n [\"{ } in the header (or a double-click on its right) · (source :bN)\" \"the buffer as EDN text, in the code window: edit it and apply (Ctrl+Enter); what changed is one event\"]]\n :example (lines \"(box :b1 \\\"canvas\\\" 40 60)\" \"(box :b2 \\\"loadbang\\\" 40 15)\" \"(box :b3 \\\"ramp 0 1 4 loop\\\" 120 15)\"\n \"(box :b4 \\\"reader\\\" 40 290)\" \"(box :b5 \\\"print\\\" 40 340)\"\n \"(connect :b2 0 :b3 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b1 1 :b4 1)\" \"(connect :b4 0 :b5 0)\"\n \"(axis :b1 :x 0 1)\" \"(axis :b1 :y 0 1)\" \"(stroke :b1 [[0 0.2] [0.5 0.9] [1 0.4]])\")\n :try \"Press ▶: the reader goes along X and prints the height of the stroke. Draw another stroke and listen to the list grow.\"\n :steps [{:title \"An automation\"\n :note \"A reader~ goes along the canvas at audio rate: its value is a signal that can move a parameter, here the factor of a gain~ (a tremolo drawn by hand).\"\n :example (lines \"(box :b6 \\\"phasor~ 0.5\\\" 300 15)\" \"(box :b7 \\\"reader~ norm\\\" 300 290)\" \"(box :b8 \\\"osc~ 330\\\" 420 290)\"\n \"(box :b9 \\\"gain~ 0\\\" 420 340)\" \"(box :b10 \\\"dac~\\\" 420 390)\"\n \"(connect :b6 0 :b7 0)\" \"(connect :b1 1 :b7 1)\" \"(connect :b8 0 :b9 0)\" \"(connect :b7 0 :b9 1)\"\n \"(connect :b9 0 :b10 0)\" \"(connect :b9 0 :b10 1)\")\n :try \"Press ▶: the stroke becomes the volume of the oscillator every two seconds. Draw a zigzag and listen to it.\"}\n {:title \"A path in two dimensions\"\n :note \"With reader path, the position (0…1) goes along a stroke, and both its X and Y come out: a trajectory, for space~ or for two parameters at once.\"\n :example (lines \"(clear :b1)\" \"(axis :b1 :x -1 1)\" \"(axis :b1 :y -1 1)\"\n \"(stroke :b1 [[0 0.8] [0.7 0.4] [0.5 -0.6] [-0.6 -0.5] [-0.7 0.5] [0 0.8]])\"\n \"(text! :b4 \\\"reader path\\\")\")\n :try \"Press ▶: print writes [x y] as the reader goes around the shape. Connect its outlet to a space~ (see its help) to move a sound along it.\"}]\n :see [\"reader\" \"reader~\" \"freqt\"]}\n\n \"freqt\"\n {:inlets [\"a time (or a click): it comes out on the left · an edit ([:note t \\\"c4\\\" dur], [:stroke [[t hz] …]], [:erase :t1], [:clear], [:tuning \\\"19-tet\\\"], [:grid-x 0.25 [4]]… or [:batch [edits]]): it changes the buffer, as one event · a question ([:read t], [:strokes], [:get :t1], [:count], [:end], [:data]): the answer comes out on the left · a musical tree: shown over it\"]\n :outlets [\"the time, or the answer to a question\" \"the buffer, for a reader or reader~\"\n \"shown as a score: the edits made on the notes of the tree it shows ([:edit …]), for the tree box\"]\n :messages [[\"(note :bN t \\\"c4\\\" dur)\" \"a note\"] [\"(tuning :bN \\\"31-tet\\\" 261.63)\" \"a tuning\"] [\"(grid-x :bN 0.25 \\\"3+3+2\\\")\" \"a bar grid\"]\n [\"the corner · (resize :bN 640 300)\" \"drag its bottom-right corner to resize it (as a score, its width reflows the notation); a double-click there brings back its size\"]\n [\"[:note 0 \\\"c4\\\" 1] · [:note 1 64 0.5]\" \"a note by message (pitch as a name or MIDI)\"]\n [\"[:move :t1 dt cents] · [:stretch :t1 k] · [:erase :t1] · [:clear]\" \"edit notes by message\"]\n [\"[:tuning \\\"19-tet\\\" 261.63] · [:grid-x 0.25 [4]]\" \"tuning and grid by message\"]\n [\"[:batch [[:clear] [:note 0 \\\"c4\\\" 1] …]]\" \"several edits, one event of the history\"]\n [\"[:read 2] · [:strokes] · [:get :t1] · [:count] · [:end] · [:data]\" \"questions: the answer comes out on the left\"]\n [\"⇄ score in the header · (view :bN :score)\" \"the same buffer, quantized and drawn as a score: measures in the meter of its bar grid, tuplets, ties (⇄ canvas brings it back)\"]\n [\"(quantize :bN {:meter \\\"6/8\\\"})\" \"the tree that score shows, to keep or edit (options: :meter :divs :merge :nest :voices :grace :legato)\"]\n [\"shown as a score, alt-click a note · (division! :bN t)\" \"its beat divided the next way (another division, in halves, with the next beat), kept in the buffer\"]\n [\"(to-tree! :bN)\" \"a tree box beside it, with its strokes as notes: the drawing, now a tree\"]\n [\"(quant :bN {:meter \\\"6/8\\\" :key \\\"eb\\\"}) · [:quantize {…}]\" \"how its score is quantized and in which key, kept in its buffer (one event); (quant :bN nil): the defaults. {:meters [\\\"3/4\\\" \\\"5/8[2+3]\\\"]}: a meter for each bar, the last going on\"]\n [\"(track! :bN) · (quant :bN {:time :track})\" \"what was played freely (transcribe, at any tempo, with rubato) written on its beats: the tempo and the beats are found, and track! keeps them (the time map) so that the score stays as it is; if the bar starts in the wrong place, (track! :bN {:downbeat t}) with the time of a note that starts a bar; (track! :bN nil) forgets them\"]\n [\"shown as a score, shift-alt-click a note · (enharmonic! :bN t midi)\" \"another name for that note (c#4 → db4), kept in the buffer\"]\n [\"shown as a score, click a note of a tree\" \"↑ ↓ pitch (⇧ octave) · a…g the nearest note of that name · + − duration · ← → next · Delete → rest\"]\n [\"click a rest\" \"Enter → a note (the pitch of the one before) · ↑ ↓ a step above or below it · a…g that note\"]\n [\"(keep! :bN)\" \"writes the tree it shows into its buffer, with its recipe beside it (the tree and the boxes that made it)\"]\n [\"(recipe :bN) · (remake! :bN)\" \"the recipe of a kept buffer · the tree written back, without the changes made since\"]\n [\"{ } in the header (or a double-click on its right) · (source :bN)\" \"the buffer as EDN text, in the code window: edit it and apply (Ctrl+Enter); what changed is one event\"]]\n :example (lines \"(box :b1 \\\"freqt\\\" 40 60)\" \"(box :b2 \\\"phasor~ 0.25\\\" 40 15)\" \"(box :b3 \\\"reader~ norm 1 gate\\\" 40 290)\"\n \"(box :b4 \\\"osc~\\\" 40 340)\" \"(box :b5 \\\"gain~\\\" 40 390)\" \"(box :b6 \\\"dac~\\\" 40 440)\"\n \"(connect :b2 0 :b3 0)\" \"(connect :b1 1 :b3 1)\" \"(connect :b3 0 :b4 0)\" \"(connect :b3 1 :b5 1)\"\n \"(connect :b4 0 :b5 0)\" \"(connect :b5 0 :b6 0)\" \"(connect :b5 0 :b6 1)\"\n \"(melody :b1 \\\"c4/1 e4/.5 d4/.5 g4/2\\\" 0)\")\n :try \"Press ▶: the reader~ plays the four beats again and again. Draw a stroke of your own, straight or curved: it sounds at the frequency it passes through.\"\n :steps [{:title \"A tuning and a grid\"\n :note \"A freqt can have a tuning (the lines of its Y axis: any equal division, just intonation, a Scala .scl) and a grid of time with its bars. Drawing snaps to both.\"\n :example (lines \"(tuning :b1 \\\"19-tet\\\")\" \"(grid-x :b1 0.5 [4])\")\n :try \"Draw a few notes: they fall on the 19 degrees of the octave and on the half beats. Try (tuning :b1 \\\"just-5\\\") or (tuning :b1 nil) to draw freely again.\"}\n {:title \"As a score\"\n :note \"The same buffer can be shown as a score, quantized into measures (in the meter of its bar grid, with tuplets and ties): ⇄ score in its header, or (view :b1 :score). Nothing changes in the data; ⇄ canvas brings the drawing back, and (quantize :b1) gives the tree the score shows.\"\n :example (lines \"(tuning :b1 nil)\" \"(view :b1 :score)\")\n :try \"Press ▶: the score sounds the same as the drawing did. To edit notes one by one in a score, show a tree: see the help of tree.\"}\n {:title \"The viewer of a tree\"\n :note \"A freqt shown as a score is the viewer of a tree that comes transformed (tree → mt transpose 7 → freqt). Its third outlet sends the edits made on the notes back to the tree box. (A box written \\\"score\\\", from older works, is a freqt shown as a score.)\"\n :example (lines \"(box :b7 \\\"bang\\\" 500 15)\" \"(box :b8 \\\"tree\\\" 500 60)\" \"(code :b8 \\\"\\\\\\\"c5/1 b4/.5 a4 g4/2\\\\\\\"\\\")\"\n \"(box :b9 \\\"freqt\\\" 500 160)\" \"(view :b9 :score)\"\n \"(connect :b7 0 :b8 0)\" \"(connect :b8 0 :b9 0)\" \"(connect :b9 2 :b8 0)\")\n :try \"Click a note of the new score and press ↑ or ↓, + or −, Delete (a rest) and then Enter (a note again): the change goes back to the tree by the dashed line.\"}]\n :see [\"canvas\" \"reader\" \"tree\" \"quantize\" \"transcribe\"]}\n\n \"reader\"\n {:inlets [\"a position in the units of the buffer (along X, or Y with reader y; 0…1 with reader norm, or with reader path) · on a ring: in seconds (0…1 with norm), or :d, :speed, :stop\"\n \"the buffer of a canvas, freqt or ring (a ring's right outlet)\"]\n :outlets [\"the values where the position crosses something (a list) · from a ring, each value as it was written\" \"their ids (sent first), for voices\"]\n :messages [[\"reader d 1 · msg :d 1\" \"on a ring: it follows the ring's head 1 s behind, on its own — a canon, a delay; it starts when the ring's time does\"]\n [\"reader d 1 speed 0.5 · msg :speed 0.5\" \"first the distance, then the speed: at 0.5 it falls behind (an augmentation), at −1 it goes back over what was written\"]\n [\"a number (a ramp, a counter)\" \"on a ring: moves it there; it sends what it crosses, either way, and a move larger than its jump (0.5 s; jump 1, msg :jump 1) is a seek\"]\n [\":stop\" \"it stops following\"]]\n :example (lines \"(box :b1 \\\"msg 60\\\" 40 30)\" \"(box :b2 \\\"msg 64\\\" 100 30)\" \"(box :b3 \\\"msg 67\\\" 160 30)\"\n \"(box :b4 \\\"ring 8\\\" 40 90)\" \"(box :b5 \\\"reader d 1\\\" 40 150)\" \"(box :b6 \\\"reader d 2 speed 0.5\\\" 180 150)\"\n \"(box :b7 \\\"print canon\\\" 40 210)\" \"(box :b8 \\\"print slower\\\" 180 210)\"\n \"(connect :b1 0 :b4 0)\" \"(connect :b2 0 :b4 0)\" \"(connect :b3 0 :b4 0)\"\n \"(connect :b4 1 :b5 1)\" \"(connect :b4 1 :b6 1)\" \"(connect :b5 0 :b7 0)\" \"(connect :b6 0 :b8 0)\")\n :try \"Press ▶ and click the three messages: each comes back a second later, and from the second reader two seconds later, twice as slow. A ramp into a reader on the ring moves it by hand.\"\n :see [\"ring\" \"writer\" \"canvas\" \"reader~\"]}\n\n \"osc~\"\n {:inlets [\"a number: the frequency in Hz · a signal: the frequency itself\" \"—\"]\n :outlets [\"a sine signal (quiet: 0.15)\"]\n :example (lines \"(box :b1 \\\"number 440\\\" 40 30)\" \"(box :b2 \\\"osc~ 440\\\" 40 90)\" \"(box :b3 \\\"gain~ 0.3\\\" 40 140)\"\n \"(box :b4 \\\"dac~\\\" 40 190)\" \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\"\n \"(connect :b3 0 :b4 0)\" \"(connect :b3 0 :b4 1)\")\n :try \"Start the engine and drag the number. Then put a phasor~ through a * into the left inlet: a signal instead of numbers.\"\n :see [\"gain~\" \"dac~\" \"phasor~\" \"mtof\"]}\n\n \"gain~\"\n {:inlets [\"the signal\" \"the factor: a number, or a signal (an envelope) that then is the factor\"]\n :outlets [\"the signal times the factor\"]\n :see [\"osc~\" \"adsr~\" \"dac~\"]}\n\n \"dac~\"\n {:inlets [\"one inlet per output channel: those written after it (1 2 by default)\"]\n :example (lines \"(box :b1 \\\"osc~ 330\\\" 40 30)\" \"(box :b2 \\\"gain~ 0.2\\\" 40 80)\" \"(box :b3 \\\"dac~ 1 2\\\" 40 130)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\")\n :try \"Only the left channel sounds: connect the gain~ to the right inlet too.\"\n :see [\"gain~\" \"pan~\" \"space~\" \"adc~\"]}\n\n \"adc~\"\n {:outlets [\"one signal per input channel: those written after it (1 by default)\"]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"scope~ 20\\\" 40 80)\" \"(box :b3 \\\"snapshot~ 50 db\\\" 240 80)\"\n \"(box :b4 \\\"print\\\" 240 140)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b1 0 :b3 0)\" \"(connect :b3 0 :b4 0)\")\n :try \"Press ▶ and allow the microphone: sing or clap and watch the scope and the level. It does not go to dac~, so it cannot feed back; send it through a gain~ to hear it (with headphones).\"\n :see [\"dac~\" \"snapshot~\" \"scope~\"]}\n\n \"snapshot~\"\n {:inlets [\"the signal; a number changes ms, a bang sends the last value again\"]\n :outlets [\"its value (or its level with rms, peak or db) every ms, only when it changed\"]\n :messages [[\"rms · peak · db\" \"written in the box: its level over each ms instead of its value\"]]\n :example (lines \"(box :b1 \\\"phasor~ 0.5\\\" 40 30)\" \"(box :b2 \\\"snapshot~ 100\\\" 40 80)\" \"(box :b3 \\\"print\\\" 40 130)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\")\n :try \"Press ▶: the ramp of the phasor~ arrives as numbers ten times a second. Write snapshot~ 100 peak and connect an adc~ instead.\"\n :see [\"adc~\" \"scope~\" \"phasor~\"]}\n\n \"scope~\"\n {:inlets [\"the signal; a number changes the time shown (ms)\"]\n :messages [[\"drag up/down\" \"zoom (⇧ finer)\"] [\"drag sideways\" \"the time shown\"]]\n :example (lines \"(box :b1 \\\"osc~ 220\\\" 40 30)\" \"(box :b2 \\\"scope~ 20\\\" 40 80)\" \"(connect :b1 0 :b2 0)\")\n :try \"Press ▶: a sine wave stands still. Drag over it to zoom; connect an adc~ instead of the osc~.\"\n :see [\"adc~\" \"snapshot~\"]}\n\n \"record\"\n {:inlets [\"numbers (a knob, snapshot~, features~…); :rec starts a take from 0, :stop ends it\" \"a bang: the stroke being drawn ends, the next number begins another\"]\n :outlets [\"edits for a canvas or freqt (its inlet): [:batch …], at most every 2 seconds\"]\n :messages [[\":rec\" \"starts from 0; its first write clears the buffer\"] [\":rec t (msg :rec 4)\" \"from t seconds: what is before t stays, what is after is replaced\"] [\":ovr t (msg :ovr 4)\" \"from t seconds, over only what the take covers: what comes after it stays\"] [\":stop\" \"writes what is left and stops\"]]\n :example (lines \"(box :b1 \\\"knob 0 1 0.5\\\" 40 30)\" \"(box :b2 \\\"msg :rec\\\" 140 30)\" \"(box :b3 \\\"msg :stop\\\" 200 30)\"\n \"(box :b4 \\\"record 0 1\\\" 40 120)\" \"(box :b5 \\\"canvas\\\" 40 170)\"\n \"(connect :b1 0 :b4 0)\" \"(connect :b2 0 :b4 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b4 0 :b5 0)\")\n :try \"Press ▶, click rec, move the knob for a few seconds, click stop: the canvas holds the gesture. A phasor~ into a reader~ with the canvas on its right plays it back as an automation.\"\n :see [\"canvas\" \"snapshot~\" \"reader~\" \"transcribe\"]}\n\n \"ring\"\n {:inlets [\"any value: written where the ring's time is (from its first message) · a writer's edits · :clear\"]\n :outlets [\"what it is asked ([:data])\" \"the buffer, for a reader or a writer (on their right or middle inlet); :start when its time starts\"]\n :messages [[\"ring 8\" \"keeps the last 8 seconds: its write head goes round as a tape head, so what is older than one turn is gone\"]\n [\":clear\" \"empties it; its time starts again at the next message\"]\n [\"[:data]\" \"what it keeps, as {:dur :events [[position value] …]}\"]]\n :example (lines \"(box :b1 \\\"msg 60\\\" 40 30)\" \"(box :b2 \\\"msg 67\\\" 100 30)\" \"(box :b3 \\\"ring 4\\\" 40 90)\"\n \"(box :b4 \\\"reader d 0.5\\\" 40 150)\" \"(box :b5 \\\"reader d 1.5\\\" 160 150)\" \"(box :b6 \\\"print\\\" 40 210)\"\n \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b3 1 :b4 1)\" \"(connect :b3 1 :b5 1)\"\n \"(connect :b4 0 :b6 0)\" \"(connect :b5 0 :b6 0)\")\n :try \"Press ▶ and click the messages: a canon in three voices, 0.5 s and 1.5 s behind. After 4 seconds what you played is gone.\"\n :see [\"reader\" \"writer\" \"record\"]}\n\n \"writer\"\n {:inlets [\"what is written where the writer is · :rec t / :ovr t · :stop\" \"the buffer (a ring's right outlet)\" \"a position in seconds of the span (0…1 with norm), from any source\"]\n :outlets [\"edits for the ring (its left inlet)\"]\n :messages [[\"writer · writer mix\" \"ovr (the default) replaces what it passes, silence too, as a tape head; mix leaves it (an overdub)\"]\n [\"a position on the right\" \"it goes there: moving, with ovr it erases what it passes; a move larger than its jump (0.5 s; writer jump 1) is a seek\"]\n [\":ovr t (msg :ovr 2)\" \"to t, then on at speed 1, replacing what it passes\"]\n [\":rec t (msg :rec 2)\" \"the same, and on a ring everything else is erased first\"]\n [\":stop\" \"it stays where it is\"]]\n :example (lines \"(box :b1 \\\"msg 60\\\" 40 30)\" \"(box :b2 \\\"msg 67\\\" 100 30)\" \"(box :b3 \\\"msg :ovr 0\\\" 160 30)\"\n \"(box :b4 \\\"writer\\\" 40 90)\" \"(box :b5 \\\"ring 4\\\" 40 150)\" \"(box :b6 \\\"reader d 1\\\" 40 210)\" \"(box :b7 \\\"print\\\" 40 270)\"\n \"(connect :b1 0 :b4 0)\" \"(connect :b2 0 :b4 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b4 0 :b5 0)\"\n \"(connect :b5 1 :b4 1)\" \"(connect :b5 1 :b6 1)\" \"(connect :b6 0 :b7 0)\")\n :try \"Press ▶ and click the notes: without a position the writer writes where the ring's head is, and the reader plays them a second later. Click :ovr 0: now the writer goes round from the ring's position 0 at speed 1, wherever the ring's head is, replacing what it passes, and the reader meets the notes when it gets there. A ramp on its right inlet moves it by hand.\"\n :see [\"ring\" \"reader\" \"record\"]}\n\n \"phasor~\"\n {:inlets [\"a number: the frequency in Hz (0.25 = once every 4 seconds)\"]\n :outlets [\"a ramp signal from 0 to 1\"]\n :see [\"reader~\" \"sig~\"]}\n\n \"sig~\"\n {:inlets [\"a number: the new constant value\"] :outlets [\"a constant signal\"] :see [\"phasor~\" \"osc~\"]}\n\n \"reader~\"\n {:inlets [\"the position signal, in the buffer's units (the X axis of a canvas, the time of a freqt, the seconds of a sample) or 0…1 with reader~ norm (a phasor~ straight in); along a stroke (path) always 0…1 · on a ring~: a position in seconds (0…1 with norm), or nothing (then it follows the ring's head); :d, :speed, :jump, :gain\"\n \"the buffer of a canvas or freqt, the sound of a sample (then it plays it, 0 its start and 1 its end), or a ring~ (its right outlet)\"]\n :outlets [\"one signal per voice (the values it crosses) · from a ring~, the sound it reads\" \"with gate: one more per voice, 1 where it sounds and 0 where not\"]\n :messages [[\"reader~ d 1 · msg :d 1\" \"on a ring~, without a position: 1 s behind the ring's head — a canon, a delay; a new d glides (the pitch bends) or, larger than its jump (0.25 s), seeks with a crossfade\"]\n [\"reader~ d 1 speed 0.5 · msg :speed -1\" \"first the distance, then the speed: at 0.5 an octave down and falling behind, at −1 backwards\"]\n [\"a position signal on a ring~\" \"it reads there (seconds; norm: 0…1, a phasor~), at any speed, either way\"]]\n :example (lines \"(box :b1 \\\"freqt\\\" 40 60)\" \"(box :b2 \\\"phasor~ 0.25\\\" 40 15)\" \"(box :b3 \\\"reader~ norm 1 gate\\\" 40 290)\"\n \"(box :b4 \\\"osc~\\\" 40 340)\" \"(box :b5 \\\"gain~\\\" 40 390)\" \"(box :b6 \\\"dac~\\\" 40 440)\"\n \"(connect :b2 0 :b3 0)\" \"(connect :b1 1 :b3 1)\" \"(connect :b3 0 :b4 0)\" \"(connect :b3 1 :b5 1)\"\n \"(connect :b4 0 :b5 0)\" \"(connect :b5 0 :b6 0)\" \"(connect :b5 0 :b6 1)\"\n \"(stroke :b1 [[0 220] [1 330] [1.5 293.66]])\" \"(stroke :b1 [[2.5 440] [4 220]])\")\n :try \"Press ▶: the drawing plays every four seconds, and is silent where nothing is drawn (the gate).\"\n :see [\"phasor~\" \"adsr~\" \"freqt\" \"reader\" \"sample\"]}\n\n \"ring~\"\n {:inlets [\"the sound, written where the ring's time is (its write head goes round as a tape head) · :clear silences it\"]\n :outlets [\"—\" \"the buffer, for reader~ and writer~ (on their right / middle inlet)\"]\n :messages [[\"ring~ 8\" \"keeps the last 8 seconds (up to 60)\"] [\":clear\" \"silence, the heads where they are\"]\n [\"up to 8 heads\" \"the reader~ and writer~ on it share one node: a feedback inside the ring is exact, through other boxes it costs a block (128 samples)\"]\n [\"reader~ → faust~ → writer~\" \"a faust~ in a loop of the ring runs inside the ring's node, one sample at a time: exact at any d (a string whose d is its period, a comb, a tape echo that darkens); its parameters follow it there (not a polyphonic one)\"]]\n :example (lines \"(box :b1 \\\"adc~\\\" 40 30)\" \"(box :b2 \\\"ring~ 8\\\" 40 90)\" \"(box :b3 \\\"reader~ d 1\\\" 40 150)\"\n \"(box :b4 \\\"reader~ d 1 speed 0.5\\\" 200 150)\" \"(box :b5 \\\"gain~ 0.4\\\" 40 210)\" \"(box :b6 \\\"dac~\\\" 40 270)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 1 :b3 1)\" \"(connect :b2 1 :b4 1)\" \"(connect :b3 0 :b5 0)\" \"(connect :b4 0 :b5 0)\"\n \"(connect :b5 0 :b6 0)\" \"(connect :b5 0 :b6 1)\")\n :try \"With headphones, press ▶ and sing: you come back a second later, and from the second reader~ an octave down, ever later. msg :d 0.25 into a reader~ glides it nearer.\"\n :see [\"reader~\" \"writer~\" \"ring\" \"sample\"]}\n\n \"writer~\"\n {:inlets [\"the sound it writes · :rec t / :ovr t · :stop · :keep x\" \"the ring~'s buffer (its right outlet)\" \"a position signal (seconds, or 0…1 with norm: a phasor~); without one, where the ring's head is\"]\n :messages [[\"writer~ · writer~ mix · writer~ mix 0.8\" \"ovr (the default) replaces what is there, silence too, as a tape head; mix adds to it, keeping what was there times 0.8\"]\n [\"a position signal\" \"it writes there as it goes, at any speed, either way; a jump larger than its jump (0.25 s) is a seek\"]\n [\":ovr t (msg :ovr 2) · :rec t\" \"to t, then on at speed 1, replacing; rec erases the ring first\"] [\":stop\" \"it stays where it is\"]]\n :example (lines \"(box :b1 \\\"adc~\\\" 40 30)\" \"(box :b2 \\\"phasor~ -0.25\\\" 200 30)\" \"(box :b3 \\\"writer~ norm\\\" 40 90)\"\n \"(box :b4 \\\"ring~ 4\\\" 200 90)\" \"(box :b5 \\\"reader~ d 0.5\\\" 200 150)\" \"(box :b6 \\\"gain~ 0.4\\\" 200 210)\" \"(box :b7 \\\"dac~\\\" 200 270)\"\n \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b3 2)\" \"(connect :b4 1 :b3 1)\" \"(connect :b4 1 :b5 1)\"\n \"(connect :b5 0 :b6 0)\" \"(connect :b6 0 :b7 0)\" \"(connect :b6 0 :b7 1)\")\n :try \"With headphones, press ▶ and sing: the writer~ goes round the ring backwards (a phasor~ at −0.25 Hz), so the reader~, which goes forwards, plays you reversed, in chunks.\"\n :see [\"ring~\" \"reader~\" \"phasor~\"]}\n\n \"sample\"\n {:inlets [\"the signal to record; :rec starts, :stop ends (or its length in seconds), :clear empties it, a bang asks its length\"]\n :outlets [\"its length in seconds (after each recording, and on a bang)\" \"the sound, for a reader~ (on its right inlet)\"]\n :messages [[\":rec\" \"records what reaches it, from the beginning\"] [\":rec t (msg :rec 2.5)\" \"keeps its first t seconds and records from there\"] [\":ovr t (msg :ovr 2.5)\" \"replaces only what the take covers, keeping what comes after (:ovr: from 0)\"] [\":stop\" \"keeps what was heard\"]\n [\":clear\" \"empties it\"] [\"a URL (msg https://… · msg :url github:… · a string)\" \"loads the sound there; every browser that opens the work fetches it\"]\n [\"(load-sound! :bN)\" \"brings in a sound file\"] [\"(load-sound! :bN \\\"https://…\\\")\" \"loads it from a URL\"]\n [\"(sample! :bN {:url \\\"…\\\"})\" \"a sample that is only a URL, as a link or a shared session writes it\"]\n [\"github:owner/repo@ref/path.wav\" \"a file of a public GitHub repository (through jsDelivr: no CORS problem)\"]\n [\"freesound:12345\" \"a sound of Freesound, with your API key: (freesound-key! \\\"…\\\"); (sounds \\\"kick\\\") searches; (credits) lists who made them\"]\n [\"(save-sound :bN)\" \"saves it as WAV\"]]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"msg :rec\\\" 140 30)\" \"(box :b3 \\\"msg :stop\\\" 200 30)\"\n \"(box :b4 \\\"sample 10\\\" 40 90)\" \"(box :b5 \\\"!/ 1\\\" 40 190)\" \"(box :b6 \\\"phasor~\\\" 40 240)\"\n \"(box :b7 \\\"reader~ norm\\\" 40 290)\" \"(box :b8 \\\"gain~ 0.5\\\" 40 340)\" \"(box :b9 \\\"dac~\\\" 40 390)\"\n \"(connect :b1 0 :b4 0)\" \"(connect :b2 0 :b4 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b4 0 :b5 0)\"\n \"(connect :b5 0 :b6 0)\" \"(connect :b6 0 :b7 0)\" \"(connect :b4 1 :b7 1)\" \"(connect :b7 0 :b8 0)\"\n \"(connect :b8 0 :b9 0)\" \"(connect :b8 0 :b9 1)\")\n :try \"Press ▶, click rec, sing a phrase, click stop: its length becomes the speed of the phasor~ (!/ 1: one over the seconds), and the reader~ plays it in a loop. Use headphones. Change the phasor~ to play it faster, slower or backwards.\"\n :see [\"reader~\" \"adc~\" \"phasor~\"]}\n\n \"faust~\"\n {:inlets [\"audio inputs of process (if any); the left one also takes parameters: [:freq 440]\"]\n :outlets [\"audio outputs of process\"]\n :messages [[\"(code :bN \\\"process = …;\\\")\" \"writes its source\"] [\"double-click\" \"edit the code, beside its patch of Faust's own elements (Patch in the bar hides it); Ctrl+Enter applies\"]\n [\"Recipe (in the window's bar)\" \"the values of its sliders that sound closest to a sample box or a sound file, written in the code; Ctrl+Enter applies them\"]\n [\"declare options \\\"[nvoices:8]\\\"\" \"polyphonic: Hz on the left, voice ids on the right (a second inlet), as synth~; each id a voice\"]\n [\"[:gain 0.6] · :stop\" \"polyphonic: the velocity of the next notes · releases every voice\"]\n [\"effect = …;\" \"polyphonic: applied once to the sum of the voices\"]]\n :example (lines \"(box :b1 \\\"faust~\\\" 40 30)\" \"(box :b2 \\\"dac~\\\" 40 200)\" \"(connect :b1 0 :b2 0)\" \"(connect :b1 0 :b2 1)\"\n \"(code :b1 \\\"import(\\\\\\\"stdfaust.lib\\\\\\\");\\\\nf = hslider(\\\\\\\"freq\\\\\\\", 220, 50, 2000, 1);\\\\nprocess = os.sawtooth(f) * 0.1 : fi.lowpass(2, 1200);\\\")\")\n :try \"Press ▶. Then change 1200 in the code and apply with Ctrl+Enter: the filter opens.\"\n :steps [{:title \"Polyphonic: a keyboard\"\n :note \"With declare options \\\"[nvoices:8]\\\" the source is a voice: its freq, gain and gate are set note by note by Faust's own allocator, for up to 8 notes at once (the oldest is taken when they run out). Hz on the left and voice ids on the right, as synth~; [:gain v] is the velocity of the next notes.\"\n :example (lines \"(box :b3 \\\"faust~\\\" 300 30)\" \"(code :b3 \\\"import(\\\\\\\"stdfaust.lib\\\\\\\");\\\\ndeclare options \\\\\\\"[nvoices:8]\\\\\\\";\\\\nfreq = hslider(\\\\\\\"freq\\\\\\\", 440, 40, 4000, 0.01);\\\\ngain = hslider(\\\\\\\"gain\\\\\\\", 0.8, 0, 1, 0.01);\\\\ngate = button(\\\\\\\"gate\\\\\\\");\\\\ncutoff = hslider(\\\\\\\"cutoff\\\\\\\", 2400, 200, 8000, 1);\\\\nprocess = os.sawtooth(freq) * gain * en.adsr(0.01, 0.2, 0.6, 0.6, gate) * 0.12 : fi.lowpass(2, cutoff);\\\")\" \"(box :b4 \\\"keyboard\\\" 300 210)\" \"(connect :b4 0 :b3 0)\" \"(connect :b4 1 :b3 1)\" \"(connect :b4 3 :b3 0)\" \"(connect :b3 0 :b2 0)\" \"(connect :b3 0 :b2 1)\")\n :try \"Press ▶ and play a chord (⇧-click several keys): every key a voice. Touch lower on the keys to play louder. Its other controls (cutoff) are for every voice.\"}\n {:title \"A score in several voices\"\n :note \"mt play sends the Hz of the notes sounding and their voice ids: each note of a chord, a voice of the faust~.\"\n :example (lines \"(box :b5 \\\"tree\\\" 560 30)\" \"(code :b5 \\\"\\\\\\\"c4+e4+g4/2 d4+f4+a4/2 b3+d4+g4/2 c4+e4+g4+c5/2\\\\\\\"\\\")\" \"(box :b6 \\\"msg :bang\\\" 560 150)\" \"(box :b7 \\\"msg :stop\\\" 640 150)\" \"(box :b8 \\\"mt play loop\\\" 560 190)\" \"(connect :b5 0 :b8 0)\" \"(connect :b6 0 :b8 0)\" \"(connect :b7 0 :b8 0)\" \"(connect :b8 0 :b3 0)\" \"(connect :b8 1 :b3 1)\")\n :try \"Press ▶ and click msg :bang: the four chords in a loop; msg :stop ends it.\"}\n {:title \"Any tuning\"\n :note \"The notes reach the voices as MIDI pitches with decimals, so any frequency sounds as written: here a just major triad (4:5:6), then the equal-tempered one.\"\n :example (lines \"(box :b9 \\\"msg 220 275 330\\\" 560 260)\" \"(box :b10 \\\"msg 220 277.18 329.63\\\" 700 260)\" \"(box :b11 \\\"msg :stop\\\" 870 260)\" \"(connect :b9 0 :b3 0)\" \"(connect :b10 0 :b3 0)\" \"(connect :b11 0 :b3 0)\")\n :try \"Press ▶ and click the first two messages in turn: the just third is 14 cents lower, and it does not beat.\"}\n {:title \"An effect for all the voices\"\n :note \"effect = …; in the same source is applied once, to the sum of the voices (here an echo); its controls are parameters of the box too.\"\n :example (lines \"(code :b3 \\\"import(\\\\\\\"stdfaust.lib\\\\\\\");\\\\ndeclare options \\\\\\\"[nvoices:8]\\\\\\\";\\\\nfreq = hslider(\\\\\\\"freq\\\\\\\", 440, 40, 4000, 0.01);\\\\ngain = hslider(\\\\\\\"gain\\\\\\\", 0.8, 0, 1, 0.01);\\\\ngate = button(\\\\\\\"gate\\\\\\\");\\\\ncutoff = hslider(\\\\\\\"cutoff\\\\\\\", 2400, 200, 8000, 1);\\\\nprocess = os.sawtooth(freq) * gain * en.adsr(0.01, 0.2, 0.6, 0.6, gate) * 0.12 : fi.lowpass(2, cutoff);\\\\neffect = ef.echo(1, 0.33, 0.45);\\\")\")\n :try \"Press ▶ and play the keyboard again: every note echoes. Change ef.echo(1, 0.33, 0.45) and apply it (Ctrl+Enter).\"}]\n :see [\"knob\" \"component\" \"script\"]}\n\n \"script\"\n {:inlets [\"what its function receives, by inlet (as many as the first number)\"]\n :outlets [\"what its function returns in :out (as many as the second number)\"]\n :messages [[\"source\" \"(fn [m] {:out [[0 (* 2 (:value m))]]})\"]]\n :see [\"component\"]}\n\n \"component\"\n {:doc \"Defines a box class inside the work. It has no inlets nor outlets, so it is not drawn in the patch: the Components tab lists the work's definitions and opens them.\"\n :messages [[\"source\" \"a map {:class \\\"x\\\" :doc … :io [1 1] :receive (fn [m] …)}: defines the class x in the work\"]\n [\"New component (Components tab) · (new-component!)\" \"a new definition, from a template, open in the code window\"]\n [\"Edit · × (Components tab)\" \"its code in the code window · removes it (one event of the history)\"]\n [\"a click on its row\" \"chooses it: the Claude tab can then change it\"]]\n :see [\"script\" \"faust~\"]}\n\n \"patch\"\n {:inlets [\"one per inlet / inlet~ box inside, left to right\"] :outlets [\"one per outlet / outlet~ box inside\"]\n :messages [[\"double-click\" \"opens it (patch @name: opens its line, in its tab)\"]\n [\"patch @name\" \"uses the line called name (spaces as -): its newest point, so it changes as the line advances; inside it, adc~ and dac~ are quiet (they play when the line plays alone): sound goes in and out through inlet~ / outlet~\"]\n [\"(pin-ref :bN)\" \"pins a patch @name to the point of its line it reads now · (follow-ref :bN) follows the line again\"]\n [\"(abstract :bN \\\"name\\\")\" \"turns it into a class (an abstraction)\"]]\n :see [\"inlet\" \"outlet\"]}\n\n \"inlet\" {:outlets [\"what arrives at this inlet of the sub-patch\"] :see [\"patch\" \"outlet\" \"inlet~\"]}\n \"outlet\" {:inlets [\"what leaves the sub-patch by this outlet\"] :see [\"patch\" \"inlet\" \"outlet~\"]}\n \"inlet~\" {:outlets [\"the signal that arrives at this inlet of the sub-patch\"] :see [\"patch\" \"outlet~\"]}\n \"outlet~\" {:inlets [\"the signal that leaves the sub-patch by this outlet\"] :see [\"patch\" \"inlet~\"]}\n\n \"tree\"\n {:inlets [\"a bang: sends the tree again · [:edit …] (from the edits outlet of a freqt shown as a score): changes it · a tree: replaces it\"]\n :outlets [\"the tree, expanded (melody strings become notes, [:use …] the fragments it names), whenever it changes\"\n \"its notes as a buffer (strokes of frequency over time), for the right inlet of a reader~\"]\n :messages [[\"{ } in the header (or a double-click on its right) · (source :bN)\" \"its text, in the code window (Ctrl+Enter applies): only the nodes that changed go into the history\"]\n [\"(tree! :bN [:voice …])\" \"writes a tree into it, as edits of the nodes that change\"]\n [\"(tree-edit! :bN [:attrs [0 1 2] {…}])\" \"edits nodes by their path: [:set p x] [:attrs p {…}] [:insert p x] [:remove p]\"]\n [\"(node-at :bN [0 1])\" \"the node at a path\"]\n [\"score: how it is shown at first · (view :bN :score)\" \"the tree drawn as a score, in this box (⇄ roll shows its roll)\"]\n [\"in a score: click a note\" \"↑ ↓ pitch (⇧ octave) · a…g the nearest note of that name · # another name (c#4 → db4) · + − duration · ← → next · Delete → rest\"]\n [\"{:key \\\"eb\\\"} on the tree, a voice or a measure\" \"the score's key: its signature, accidentals that last the bar; :none writes every accidental\"]\n [\"in a score: click a rest\" \"Enter → a note (the pitch of the one before) · ↑ ↓ a step above or below it · a…g that note\"]\n [\"(as-tree :bN)\" \"reads it back as data\"]\n [\"⇄ roll · (view :bN :roll)\" \"a piano roll: its notes as strokes of frequency over time: drawing, dragging, stretching or erasing there edits the tree (free time; with measures, the bars it touches are quantized again; ⌥ to a free voice)\"]\n [\"(quantize! :bN) · (unquantize! :bN)\" \"its free time written in measures, and back (one event each)\"]\n [\"(track! :bN)\" \"its free time played (in seconds, at any tempo): the beats are found and kept in its :quant, so that its score and quantize! write it on them\"]]\n :example (lines \"(box :b1 \\\"bang\\\" 40 20)\" \"(box :b2 \\\"tree\\\" 40 60)\"\n \"(code :b2 \\\"[:voice\\\\n [:measure {:meter [3 4]} \\\\\\\"e5/1\\\\\\\" [:tuplet {:ratio [3 2]} \\\\\\\"d5/.5 c5 b4\\\\\\\"] [:note {:pitch \\\\\\\"a4\\\\\\\" :dur 1 :dyn \\\\\\\"p\\\\\\\"}]]\\\\n [:measure \\\\\\\"g4/3\\\\\\\"]]\\\")\"\n \"(box :b3 \\\"mt transpose 7\\\" 40 190)\" \"(box :b4 \\\"tree\\\" 40 230)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b3 0 :b4 0)\")\n :try \"The tree box is its own score: click a note and press ↑ (or a…g, + −, Delete), or press { } in its header, change a note in its text and apply it (Ctrl+Enter). It sends its tree whenever it changes: through mt transpose 7 it reaches the second tree box, a fifth higher, which follows. Press ⇄ roll on the tree box to draw notes into it. (A tree that comes into a tree box is written into it, as one event of the history.)\"\n :see [\"mt\" \"quantize\" \"freqt\"]}\n\n \"mt\"\n {:inlets [\"a tree: it comes out transformed (for play: a tree to play, then bang, :stop)\"\n \"for transpose, invert, augment, rotate, canon, thin: the amount · for seq, par: the tree to join\"]\n :outlets [\"the result (for play: the Hz of the notes sounding, a list)\"]\n :messages [[\"mt transpose 7\" \"seven semitones up\"] [\"mt invert c4\" \"mirrored around c4\"] [\"mt retrograde\" \"backwards\"]\n [\"mt augment 2\" \"twice as long\"] [\"mt rotate 1\" \"the first element goes to the end\"] [\"mt canon 2 7\" \"against itself, 2 beats later, a fifth up\"]\n [\"mt canon d 2 k P5 speed 0.5\" \"the same with the words of a reader on a ring: d beats later, k away (semitones or an interval), the comes at a speed — 0.5 twice as slow (an augmentation canon), −1 backwards (a crab) —, and inversion upside down\"]\n [\"mt thin 0.5\" \"keeps half the notes of each measure, the ones on its strongest positions (metric weight)\"]\n [\"mt seq · mt par\" \"the left tree followed by (or with) the right one\"] [\"mt events · mt pitches · mt duration\" \"the tree as data\"]\n [\"mt play [loop]\" \"plays it: Hz (0) and voice ids (1) for synth~, parameters (2), dynamics and texts (3)\"]\n [\"mt play speed 0.5 · msg :speed -1\" \"at a speed: twice as slow, or the tree backwards — the reader of a tree on its own clock (a reader moved by positions reads the tree box instead: what sounds where it is)\"]]\n :example (lines \"(box :b1 \\\"bang\\\" 40 20)\" \"(box :b2 \\\"tree\\\" 40 60)\" \"(code :b2 \\\"\\\\\\\"c4/1 d4/.5 e4 g4/1 e4 f4/.5 e4 d4/2\\\\\\\"\\\")\"\n \"(box :b4 \\\"number 7\\\" 220 170)\" \"(box :b3 \\\"mt transpose 7\\\" 40 170)\" \"(box :b5 \\\"tree\\\" 40 220)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b4 0 :b3 1)\" \"(connect :b3 0 :b5 0)\")\n :try \"Change the box text to mt retrograde, mt invert c4 or mt augment 2: the score follows. (The number on the right inlet takes effect with the next tree: click the bang.)\"\n :steps [{:title \"Two voices: a canon\"\n :note \"mt canon d i puts the tree against itself, d beats later and i semitones away: two voices that the score shows as two staves.\"\n :example (lines \"(text! :b3 \\\"mt canon 2 7\\\")\" \"(delete :b4)\")\n :try \"Click the bang. Change it to mt canon 1 -12 (an octave below, one beat later) or mt canon 4 0.\"}\n {:title \"Playing it\"\n :note \"mt play reads a tree in time: the Hz of the notes that sound (left) and their voice ids (second) go to a synth~, which gives each voice its own note.\"\n :example (lines \"(box :b6 \\\"msg :bang\\\" 500 170)\" \"(box :b7 \\\"msg :stop\\\" 570 170)\" \"(box :b8 \\\"mt play loop\\\" 500 220)\"\n \"(box :b9 \\\"synth~\\\" 500 270)\" \"(box :b10 \\\"gain~ 0.3\\\" 500 320)\" \"(box :b11 \\\"dac~\\\" 500 370)\"\n \"(connect :b3 0 :b8 0)\" \"(connect :b6 0 :b8 0)\" \"(connect :b7 0 :b8 0)\" \"(connect :b8 0 :b9 0)\" \"(connect :b8 1 :b9 1)\"\n \"(connect :b9 0 :b10 0)\" \"(connect :b10 0 :b11 0)\" \"(connect :b10 0 :b11 1)\")\n :try \"Press ▶, click the first bang (the tree goes to mt play) and then msg :bang: the canon sounds in a loop; :stop ends it.\"}]\n :see [\"tree\" \"freqt\" \"synth~\"]}\n\n ;; ───── official packages (until they carry their own :help) ─────\n \"features~\"\n {:package \"@kairotic/analysis\" :usage \"features~ [ms] [descriptor …]\"\n :doc \"Descriptors of a signal every ms, one outlet per word: rms, energy, zcr, loudness, centroid, spread, flatness, rolloff, kurtosis, skewness, slope, crest, sharpness, perceptualSpread, mfcc, chroma (Meyda).\"\n :inlets [\"the signal\"]\n :outlets [\"one outlet per descriptor written, in order (rms centroid flatness without words); centroid, spread and rolloff in Hz\"]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"features~ 50 rms centroid\\\" 40 90)\"\n \"(box :b3 \\\"number\\\" 40 150)\" \"(box :b4 \\\"number\\\" 200 150)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b2 1 :b4 0)\")\n :try \"Press ▶ and allow the microphone: whisper and then hum — the centroid (brightness) falls.\"\n :see [\"pitch~\" \"chroma~\" \"snapshot~\"]}\n\n \"pitch~\"\n {:package \"@kairotic/analysis\" :usage \"pitch~ [lo hi] [threshold]\"\n :doc \"The pitch of a signal by YIN: Hz on the left (0 once when it stops hearing one), how clearly periodic on the right.\"\n :inlets [\"the signal\"]\n :outlets [\"the frequency in Hz, only when it changes; 0 once when it no longer finds one\" \"the clarity, 0…1\"]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"pitch~ 80 1000\\\" 40 90)\" \"(box :b3 \\\"ftom\\\" 40 150)\"\n \"(box :b4 \\\"number\\\" 40 200)\" \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b3 0 :b4 0)\")\n :try \"Press ▶ and sing: the box shows the note and its cents, the number the MIDI pitch.\"\n :see [\"onset~\" \"ftom\" \"freqt\"]}\n\n \"onset~\"\n {:package \"@kairotic/analysis\" :usage \"onset~ [threshold] [ms]\"\n :doc \"A bang at the beginning of each sound (a note, a stroke, a syllable), and its strength.\"\n :inlets [\"the signal; [:threshold x] and [:ms y] change them while it listens; a [:segment …] from form~ forgets the usual change of the section before\"]\n :outlets [\"a bang for each onset\" \"its strength (the growth of the spectrum, 0…1)\" \"the growth of every frame (the onset strength envelope)\"]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"onset~\\\" 40 90)\" \"(box :b3 \\\"counter 1\\\" 40 150)\"\n \"(box :b4 \\\"number\\\" 40 200)\" \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b3 0 :b4 0)\")\n :try \"Press ▶ and clap: the counter counts the claps. Raise the threshold if it counts too much.\"\n :see [\"pitch~\" \"sample\" \"counter\" \"form~\"]}\n\n \"chroma~\"\n {:package \"@kairotic/analysis\" :usage \"chroma~ [ms]\"\n :doc \"How much of each pitch class a signal has: 12 values from C to B, and the strongest class as a word.\"\n :inlets [\"the signal\"]\n :outlets [\"12 values, C to B, 0…1 (the strongest 1)\" \"the strongest pitch class (:c … :b), when it changes\"]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"chroma~\\\" 40 90)\" \"(box :b3 \\\"print\\\" 40 170)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 1 :b3 0)\")\n :try \"Press ▶ and play a chord or a drone: the bars show its pitch classes; print writes the strongest.\"\n :see [\"pitch~\" \"mt\" \"features~\"]}\n\n \"quantize\"\n {:about \"**Free time written in measures, when you ask.** What `transcribe` or a drawing left in a `freqt` — notes placed anywhere in time — becomes a measured tree: measures, tuplets, ties, grace notes, voices, ready for a `tree` box, `mt` and the rest.\n\n**Only a bang sends.** The options can be tried first, one message at a time, and nothing goes out until you bang it: a tree written into a tree box is an event of the work's history.\n\n**Two ways in.** A `freqt` on the right inlet (its second outlet: the buffer), or a tree on the left — in free time, or measured (it is made free first, to be written again another way). Two `quantize` boxes can write the same take two ways.\"\n :inlets [\"a bang: quantize and send · a tree (free or measured): the material, until the next one · [:meter \\\"6/8\\\"] and the other options, or a map of them · [:meter nil] forgets one · :reset forgets all · :clear forgets the tree\"\n \"a freqt (from its second outlet): the material, read at the bang\"]\n :outlets [\"the measured tree, for a tree box\" \"what it found: {:bars :meter :tempo :notes :voices}\"]\n :messages [[\":bang\" \"quantize the material and send the tree\"]\n [\"[:meter \\\"3/4\\\"]\" \"the meter (\\\"6/8\\\", \\\"7/8[2+2+3]\\\" for its groups); without one, the freqt's bar grid, or 4/4\"]\n [\"[:meters [\\\"3/4\\\" \\\"5/8\\\"]]\" \"a meter for each bar, the last one going on\"]\n [\"[:divs [1 2 3 4]]\" \"the divisions a beat may take (1 to 8 by default: 3, 5, 7 are tuplets)\"]\n [\"[:merge []]\" \"no two beats joined into one tuplet ([3 5 6] by default)\"]\n [\"[:legato 0.25]\" \"the largest gap before the next note that is not a rest, in beats (0: every gap is a rest)\"]\n [\"[:chord 0.04]\" \"starts this close (beats) are one chord\"]\n [\"[:voices 1]\" \"how many voices overlapping notes may take (2 by default)\"]\n [\"[:grace false]\" \"no grace notes: a note too short for any point is dropped\"]\n [\"[:key \\\"eb\\\"]\" \"the key it is written in: its signature and its spelling\"]\n [\"[:tempo 72]\" \"the tempo written in the tree\"]\n [\"[:time :track]\" \"what was played freely (with rubato, at any tempo): its beats are found first (also: quantize track)\"]\n [\"{:meter \\\"6/8\\\" :divs [1 2 3]}\" \"several options at once\"]\n [\":reset\" \"the options forgotten (the defaults again)\"]]\n :example (lines \"(box :b1 \\\"freqt\\\" 40 60)\" \"(resize :b1 420 200)\"\n \"(melody :b1 \\\"c4/1.06 e4/.47 d4/.55 g4/.94 e4/1.03 f4/.32 e4/.36 d4/.3 c4/2.1\\\" 0)\"\n \"(box :b2 \\\"msg :bang\\\" 520 30)\" \"(box :b6 \\\"msg :meter \\\\\\\"3/4\\\\\\\"\\\" 600 30)\" \"(box :b7 \\\"msg :meter nil\\\" 740 30)\"\n \"(box :b3 \\\"quantize\\\" 520 90)\" \"(box :b4 \\\"tree\\\" 520 160)\" \"(resize :b4 460 160)\" \"(box :b5 \\\"print\\\" 760 90)\"\n \"(connect :b1 1 :b3 1)\" \"(connect :b2 0 :b3 0)\" \"(connect :b6 0 :b3 0)\" \"(connect :b7 0 :b3 0)\"\n \"(connect :b3 0 :b4 0)\" \"(connect :b3 1 :b5 0)\")\n :try \"The freqt holds a phrase played freely — the durations are not quite 1, ½ or ⅓. Click :bang: quantize writes it in measures of 4/4 and the tree box shows the score. Click :meter \\\"3/4\\\" and :bang again: the same notes, in 3/4. Change a stroke in the freqt (drag it) and bang: the score follows only when you ask.\"\n :steps [{:title \"From your voice\"\n :note \"transcribe writes what pitch~ hears into the freqt, as strokes in free time; quantize writes them in measures. With :time :track (or quantize track) it first finds the beats of what you sang freely.\"\n :example (lines \"(box :b8 \\\"adc~ 1\\\" 40 330)\" \"(box :b9 \\\"pitch~ 80 1000\\\" 40 390)\" \"(box :b10 \\\"onset~\\\" 200 390)\"\n \"(box :b11 \\\"msg :rec\\\" 300 330)\" \"(box :b12 \\\"msg :stop\\\" 380 330)\" \"(box :b13 \\\"transcribe 60\\\" 40 450)\"\n \"(box :b14 \\\"msg :time :track\\\" 880 30)\"\n \"(connect :b8 0 :b9 0)\" \"(connect :b8 0 :b10 0)\" \"(connect :b9 0 :b13 0)\" \"(connect :b10 0 :b13 1)\"\n \"(connect :b11 0 :b13 0)\" \"(connect :b12 0 :b13 0)\" \"(connect :b13 0 :b1 0)\" \"(connect :b14 0 :b3 0)\")\n :try \"Press ▶, click :rec, sing a phrase, click :stop: the freqt holds it. Click :time :track, then :bang: your phrase, in measures.\"}]\n :see [\"transcribe\" \"freqt\" \"tree\" \"mt\"]}\n\n \"transcribe\"\n {:package \"@kairotic/analysis\" :usage \"transcribe [bpm] [notes|glide] [ms]\"\n :doc \"Writes what pitch~ hears into a freqt, as strokes: notes where the contour settles on another pitch (slides, vibrato and ornaments do not start notes), or contours (glide).\"\n :inlets [\"Hz from pitch~ (0: silence); :rec starts from 0, :stop ends\" \"a bang (from onset~): a new note, even on the same pitch\"]\n :outlets [\"edits for a freqt: [:batch [[:stroke …] …]], at most every 2 seconds (one event of the history each)\"]\n :messages [[\":rec\" \"starts a take from 0 (its first write clears the freqt)\"] [\":rec t (msg :rec 8)\" \"from beat t: what is before t stays, what is after is replaced\"] [\":ovr t (msg :ovr 8)\" \"from beat t, over only what the take covers: what comes after it stays\"] [\":stop\" \"writes what is left and stops\"]]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"pitch~ 80 1000\\\" 40 90)\" \"(box :b3 \\\"onset~\\\" 200 90)\"\n \"(box :b4 \\\"msg :rec\\\" 330 90)\" \"(box :b5 \\\"msg :stop\\\" 400 90)\" \"(box :b6 \\\"transcribe 60\\\" 40 160)\"\n \"(box :b7 \\\"freqt\\\" 40 220)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b6 0)\" \"(connect :b3 0 :b6 1)\"\n \"(connect :b4 0 :b6 0)\" \"(connect :b5 0 :b6 0)\" \"(connect :b6 0 :b7 0)\")\n :try \"Press ▶, click :rec, sing a phrase, click :stop: the freqt holds it (⇄ previews it as a score). To write it in measures, as a tree, connect the freqt's second outlet to a quantize box and bang it. Write transcribe 60 glide to keep the slides.\"\n :see [\"pitch~\" \"onset~\" \"freqt\" \"quantize\"]}\n\n \"spectrum~\"\n {:package \"@kairotic/analysis\" :usage \"spectrum~ [lo hi]\"\n :doc \"The spectrum of a signal drawn in the patch, on a log scale of frequency (dB from -90 to 0).\"\n :inlets [\"the signal\"]\n :example (lines \"(box :b1 \\\"osc~ 220\\\" 40 30)\" \"(box :b2 \\\"spectrum~\\\" 40 90)\" \"(connect :b1 0 :b2 0)\")\n :try \"Press ▶: one peak at 220 Hz. Connect an adc~ instead and sing a vowel: its partials and formants.\"\n :see [\"scope~\" \"features~\"]}\n\n \"monitor\"\n {:package \"@kairotic/analysis\" :usage \"monitor [seconds] [name …]\"\n :doc \"Draws the messages that arrive over the last seconds, one lane per inlet: a number as a line, a list as a strip of cells, a bang or a word as a mark.\"\n :inlets [\"anything, drawn in the first lane; with names (monitor 6 rms centroid chroma) one inlet per name, left to right\"]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"features~ 20 rms centroid\\\" 40 90)\" \"(box :b3 \\\"chroma~\\\" 260 90)\"\n \"(box :b4 \\\"onset~\\\" 460 90)\" \"(box :b5 \\\"monitor 6 rms centroid chroma onset\\\" 40 180)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b1 0 :b3 0)\" \"(connect :b1 0 :b4 0)\"\n \"(connect :b2 0 :b5 0)\" \"(connect :b2 1 :b5 1)\" \"(connect :b3 0 :b5 2)\" \"(connect :b4 0 :b5 3)\")\n :try \"Press ▶ and allow the microphone: speak, then sing a long note — the centroid falls, the chroma strip settles on one row, each syllable leaves a mark.\"\n :see [\"features~\" \"chroma~\" \"onset~\" \"print\"]}\n\n \"realize~\"\n {:package \"@kairotic/analysis\" :usage \"realize~ [settings] [midi]\"\n :doc \"Plays a faust~ from descriptors written as a score — loudness, brightness, noisiness, pitch — or from what features~ and pitch~ hear in another sound: its pitch (or freq) and gain sliders follow them, and its other sliders take the settings of that faust~ that sound nearest (Study 37).\"\n :inlets [\"loudness: dB, or a level 0…1 (features~ rms)\" \"brightness: Hz (features~ centroid)\" \"noisiness: 0…1 (features~ flatness)\" \"pitch: Hz (pitch~; 0 for none), MIDI with realize~ midi\" \"loudness heard in what it plays (features~ of the faust~: rms)\" \"brightness heard (centroid)\" \"noisiness heard (flatness): with these three it corrects itself\"]\n :outlets [\"[:slider value] for the faust~ it plays: connect it to the faust~'s left inlet\" \"how far the nearest setting is from what is written (above 1: the faust~ cannot sound like that)\"]\n :messages [[\":learn\" \"plays steady settings of the faust~ offline and listens to them (300, or the number written): after changing its code\"]]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"features~ 20\\\" 40 90)\" \"(box :b3 \\\"pitch~\\\" 260 90)\"\n \"(box :b4 \\\"realize~\\\" 40 160)\" \"(box :b5 \\\"faust~\\\" 40 240)\" \"(box :b6 \\\"dac~\\\" 40 430)\" \"(box :b7 \\\"msg :learn\\\" 300 160)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b4 0)\" \"(connect :b2 1 :b4 1)\" \"(connect :b2 2 :b4 2)\"\n \"(connect :b3 0 :b4 3)\" \"(connect :b7 0 :b4 0)\" \"(connect :b4 0 :b5 0)\" \"(connect :b5 0 :b6 0)\" \"(connect :b5 0 :b6 1)\"\n \"(code :b5 \\\"import(\\\\\\\"stdfaust.lib\\\\\\\");\\\\npitch = hslider(\\\\\\\"pitch\\\\\\\", 60, 36, 84, 0.01) : si.smoo;\\\\ngain = hslider(\\\\\\\"gain [unit:dB]\\\\\\\", -12, -80, 6, 0.1) : ba.db2linear : si.smoo;\\\\nwave = hslider(\\\\\\\"wave\\\\\\\", 0.5, 0, 1, 0.001) : si.smoo;\\\\nnoise = hslider(\\\\\\\"noise\\\\\\\", 0.1, 0, 1, 0.001) : si.smoo;\\\\ncutoff = hslider(\\\\\\\"cutoff [scale:log]\\\\\\\", 1000, 60, 14000, 1) : si.smoo;\\\\nresonance = hslider(\\\\\\\"resonance [scale:log]\\\\\\\", 1, 0.5, 8, 0.01) : si.smoo;\\\\nf0 = ba.midikey2hz(pitch);\\\\nosc = os.sawtooth(f0) * (1 - wave) + os.square(f0) * wave;\\\\nprocess = osc * (1 - noise) + no.noise * noise : fi.svf.lp(min(cutoff, 0.45 * ma.SR), resonance) * gain;\\\")\")\n :try \"Press ▶ and allow the microphone (headphones): sing, whisper, hum — the synth follows your loudness, brightness, noisiness and pitch with its own sound. Then let it listen: a features~ 20 on the faust~, its three outlets into the last three inlets of realize~ — it corrects what it asks where it falls short. Draw instead: four canvases read by reader~ and snapshot~ are a score for it.\"\n :see [\"features~\" \"pitch~\" \"faust~\" \"monitor\"]}\n\n \"form~\"\n {:package \"@kairotic/analysis\" :usage \"form~ [seconds] [step] [kernel]\"\n :doc \"How alike the moments of what arrives are over the last seconds (20): a self-similarity matrix of one frame every step seconds (0.25), drawn; where a segment begins, and the period that repeats.\"\n :inlets [\"lists of numbers (a chroma~, an mfcc), or numbers (onset~'s envelope, an rms); [:seconds x] [:step x] [:kernel x] change them; :clear forgets\"]\n :outlets [\"the novelty of each frame, 0…1 (how much the music changes there; kernel seconds (2) late)\" \"a bang where a segment begins\" \"the period that repeats most, in seconds, when it changes\" \"[:segment {:t :at :length :period}] for the segment that ends\"]\n :example (lines \"(box :b1 \\\"adc~ 1\\\" 40 30)\" \"(box :b2 \\\"chroma~\\\" 40 90)\" \"(box :b3 \\\"onset~\\\" 240 90)\"\n \"(box :b4 \\\"form~\\\" 40 170)\" \"(box :b5 \\\"print\\\" 280 300)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b4 0)\" \"(connect :b4 3 :b3 0)\" \"(connect :b4 3 :b5 0)\")\n :try \"Press ▶ and play a section, then another (other chords, another register): the squares along the diagonal are the sections, a line marks where the second begins, print writes the segment, and onset~ starts the new section afresh.\"\n :see [\"chroma~\" \"onset~\" \"monitor\"]}\n\n \"fetch\"\n {:package \"@kairotic/data\" :usage \"fetch [json|text|edn] [live]\"\n :doc \"Brings in what is at a URL (JSON read as EDN, text or EDN) as a task: it goes out on the left and is kept as the data of the box, in the history, the same for everyone; with live, only in this tab.\"\n :inlets [\"a URL (msg https://… · github:owner/repo@ref/path · [: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; a URL it already keeps is sent again, not fetched\"]\n [\":refresh\" \"fetches its URL again\"] [\"bang\" \"sends what it holds\"]\n [\":get :items 0 :name · [:get [:items 0 :name]]\" \"sends one part of it\"] [\":clear\" \"forgets it\"]\n [\"(keep! :bN {:url \\\"…\\\" :value …})\" \"what it keeps, as the code of the work writes it\"]]\n :example (lines \"(box :b1 \\\"msg github:bonuoq/kairotic@main/packages/data/package.json\\\" 40 30)\" \"(box :b2 \\\"fetch\\\" 40 80)\"\n \"(box :b3 \\\"edn 340 260\\\" 40 150)\" \"(box :b4 \\\"print\\\" 400 150)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b3 0 :b4 0)\")\n :try \"Click the message: the answer arrives in the edn box, and stays in the work (go back and forward in the history: it is not fetched again). Pick a line: its value goes to print.\"\n :see [\"edn\" \"sample\" \"print\"]}\n\n \"edn\"\n {:package \"@kairotic/data\" :usage \"edn [width height]\"\n :doc \"Any value as a tree, like Portal: collections open and close, values coloured by kind; picking a line sends that part (left) and its path (right).\"\n :inlets [\"any value; :depth n opens it n levels down; bang sends the part picked again; :clear\"]\n :outlets [\"the part picked\" \"its path, for [:get …] of a fetch box\"]\n :messages [[\":depth 2\" \"opens it two levels down\"] [\"bang\" \"the part picked again (the whole value if none)\"] [\":clear\" \"empties it\"]\n [\"▸ ▾ · a line · a drag\" \"opens or closes · picks it · scrolls (also the bar on the right)\"]]\n :example (lines \"(box :b1 \\\"tree\\\" 40 30)\" \"(tree! :b1 [:voice [:measure {:meter [4 4]} \\\"c4/1 e4 g4 c5\\\"]])\"\n \"(box :b2 \\\"edn 320 220\\\" 40 130)\" \"(box :b3 \\\"print\\\" 400 130)\" \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b2 1 :b3 0)\")\n :try \"The tree arrives: open the measure and pick a note: the note and its path go to print.\"\n :see [\"fetch\" \"print\" \"tree\"]}\n\n \"pbind\"\n {:package \"@kairotic/patterns\" :usage \"pbind [seed] [repeat] [loop]\"\n :doc \"A pattern as EDN data: a map of constants, sequences and #pat/… generators, with its randomness seeded. It sends its pattern whenever it changes, for a player.\"\n :inlets [\"bang: sends its pattern again · a map: replaces it (one event of the history) · [:set :dur [1 0.5]]: one key · [:unset :amp]\"]\n :outlets [\"its pattern (a factory of streams), for a player\"]\n :messages [[\"{:degree [0 2 4] :dur 0.5}\" \"a key with a vector is a sequence; the shorter ones start again until the longest ends\"]\n [\"#pat/choose [0.25 0.5] · #pat/white [0 7] · #pat/walk [0 2 -7 7]\" \"endless random values (the same for everyone: the seed)\"]\n [\"#pat/shuffle [0 2 4] · #pat/series [0 2 8]\" \"every pass in a new order · an arithmetic series\"]\n [\"#pat/hold [4 [:c :g :d]]\" \"one value every 4 beats (following time, not events)\"]\n [\"#pat/chord [0 4 7]\" \"a vector as one value: a chord\"]\n [\"{:degree [0 2 :rest 4]} · [0 nil 4]\" \"a silence: :rest (:_ :- :r) or nil as the degree, note or freq\"]\n [\":amp #pat/white [0.2 0.6]\" \"the loudness of each note (0…1), for synth~ and a polyphonic faust~\"]\n [\"pbind 7 · pbind 7 4 · pbind 7 loop\" \"the seed · four passes · for ever\"]]\n :example (lines \"(box :b1 \\\"pbind 7 loop\\\" 40 30)\"\n \"(code :b1 \\\"{:degree #pat/shuffle [0 2 4 7]\\\\n :dur [0.5 0.5 1]\\\\n :amp #pat/white [0.1 0.3]}\\\")\"\n \"(box :b2 \\\"msg :start\\\" 40 130)\" \"(box :b3 \\\"msg :stop\\\" 110 130)\" \"(box :b4 \\\"player 110\\\" 40 180)\"\n \"(box :b5 \\\"synth~\\\" 40 240)\" \"(box :b6 \\\"dac~\\\" 40 290)\"\n \"(connect :b2 0 :b4 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b1 0 :b4 1)\"\n \"(connect :b4 0 :b5 0)\" \"(connect :b4 1 :b5 1)\" \"(connect :b5 0 :b6 0)\" \"(connect :b5 0 :b6 1)\")\n :try \"Press ▶ and start: four notes in a new order every pass. Change :dur in the pbind (double-click it) and apply: the player goes on with it from the same beat. Change the seed (pbind 8 loop): other orders, but the same for everyone in a room.\"\n :steps [{:title \"One value per bar\"\n :note \"#pat/hold follows time: the root changes every 4 beats whatever the rhythm, as Overtone's ^{:dur 4} does.\"\n :example (lines \"(code :b1 \\\"{:degree #pat/shuffle [0 2 4 7]\\\\n :dur [0.5 0.5 1]\\\\n :root #pat/hold [4 [:c :f :g :c]]}\\\")\")\n :try \"Press start: the same figure, moving through four harmonies.\"}\n {:title \"Random, but the same\"\n :note \"Every key has a seed of its own (the box's seed and its name): changing one key leaves the randomness of the others as it was.\"\n :example (lines \"(code :b1 \\\"{:degree #pat/walk [0 1 -4 9]\\\\n :dur #pat/choose [0.25 0.25 0.5]\\\\n :scale :dorian}\\\")\")\n :try \"Start, stop and start again: the same walk. Change :scale to :lydian: the same rhythm and contour, other notes.\"}]\n :see [\"pattern\" \"player\" \"tree\"]}\n\n \"pattern\"\n {:package \"@kairotic/patterns\" :usage \"pattern [seed] [repeat] [loop]\"\n :doc \"A pattern as Clojure code: an expression that returns event maps (or one map, read as a pbind), with seeded randomness and pbind, pseq, pwhite, pchoose, pshuffle, pseries, pwalk at hand. In a shared room it runs only after (trust-scripts true).\"\n :inlets [\"bang: sends its pattern again\"]\n :outlets [\"its pattern (a factory of streams), for a player\"]\n :messages [[\"(pbind {:degree (pwhite 0 7) :dur 0.25} :inf)\" \"a pbind whose values are lazy sequences\"]\n [\"(concat (pbind m1) (pbind m2))\" \"phrases one after another\"]\n [\"(for [d (range 8)] {:degree d :dur (if (even? d) 0.5 0.25)})\" \"any Clojure that gives event maps\"]\n [\"rand · rand-int · rand-nth · shuffle\" \"seeded by the box: the same for everyone\"]]\n :example (lines \"(box :b1 \\\"pattern 3\\\" 40 30)\"\n \"(code :b1 \\\"(pbind {:degree (pwhite 0 7)\\\\n :dur (pchoose [0.25 0.25 0.5])\\\\n :octave [5 5 6]}\\\\n :inf)\\\")\"\n \"(box :b2 \\\"msg :start\\\" 40 130)\" \"(box :b3 \\\"msg :stop\\\" 110 130)\" \"(box :b4 \\\"player 120\\\" 40 180)\"\n \"(box :b5 \\\"synth~\\\" 40 240)\" \"(box :b6 \\\"dac~\\\" 40 290)\"\n \"(connect :b2 0 :b4 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b1 0 :b4 1)\"\n \"(connect :b4 0 :b5 0)\" \"(connect :b4 1 :b5 1)\" \"(connect :b5 0 :b6 0)\" \"(connect :b5 0 :b6 1)\")\n :try \"Press ▶ and start. Edit the code (double-click the box) and apply: the player follows the new pattern from the beat it is on.\"\n :see [\"pbind\" \"player\" \"script\"]}\n\n \"player\"\n {:package \"@kairotic/patterns\" :usage \"player [bpm] [quant] [jump] [limit] [edges] [spread]\"\n :doc \"Plays a pattern by its own clock (start/stop), one step at a time (bang) or at a position in beats (a number): the Hz and voice ids of the notes sounding, the whole event and the beat.\"\n :inlets [\":start · :stop: its own clock · bang: one step, now · a number: a position in beats · :seek p · :reset · [:bpm 90]\"\n \"a pattern (from a pbind or a pattern box): a new one goes on from the same beat\"]\n :outlets [\"the Hz of the notes sounding (a list), after [:gain amp] when the event has :amp\" \"their voice ids, sent first (for synth~ or a polyphonic faust~)\"\n \"the whole event, with :beat, :hz and :ids (and :dir :back when entered from its end)\" \"the beat\"]\n :messages [[\":start · :stop\" \"its own clock: every event lasts its :dur in beats at its bpm\"]\n [\"player 120 4\" \"start on a multiple of 4 beats: players with the same tempo meet\"]\n [\"[:bpm 90]\" \"another tempo, without a jump\"]\n [\"bang\" \"the next event now (and the ones of :dur 0 right after it)\"]\n [\"a number\" \"a position in beats: every event is a span, from its onset to its end, that sounds while the position is inside it — entered at its onset going forwards, at its end going backwards (:dir :back); what a step passes over sounds within it\"]\n [\":seek 8 · [:seek 8]\" \"there at once, nothing in between: what still sounds there goes on, what starts to contain that position starts\"]\n [\"player 120 0 8 8\" \"a step more than 8 (jump) times the one before it, or longer than 8 (limit) beats, is a seek: the wrap of a ramp\"]\n [\"player 120 0 8 8 edges\" \"a seek sounds only what starts exactly there\"]\n [\"player 120 0 8 8 spread\" \"what a step passes keeps its rhythm, one step later (with ▶)\"]\n [\":reset\" \"back to the beginning, silently\"]]\n :example (lines \"(box :b1 \\\"pbind 1 loop\\\" 40 30)\"\n \"(code :b1 \\\"{:note [:c4 :e4 :g4 :b4 :a4 :f4]\\\\n :dur [0.5 0.5 1]}\\\")\"\n \"(box :b2 \\\"msg :start\\\" 40 130)\" \"(box :b3 \\\"msg :stop\\\" 110 130)\" \"(box :b4 \\\"player 100\\\" 40 180)\"\n \"(box :b5 \\\"synth~\\\" 40 240)\" \"(box :b6 \\\"dac~\\\" 40 290)\" \"(box :b7 \\\"get % :beat\\\" 260 240)\" \"(box :b8 \\\"print\\\" 260 290)\"\n \"(connect :b2 0 :b4 0)\" \"(connect :b3 0 :b4 0)\" \"(connect :b1 0 :b4 1)\"\n \"(connect :b4 0 :b5 0)\" \"(connect :b4 1 :b5 1)\" \"(connect :b5 0 :b6 0)\" \"(connect :b5 0 :b6 1)\"\n \"(connect :b4 2 :b7 0)\" \"(connect :b7 0 :b8 0)\")\n :try \"Press ▶ and start: the six notes, three durations cycling. The third outlet is the whole event: print writes the beat of each.\"\n :steps [{:title \"Step by step\"\n :note \"A bang plays the next event now: the pattern follows whatever moves it — a metro, an onset~ of what someone plays, a key.\"\n :example (lines \"(box :b9 \\\"metro 300\\\" 180 130)\" \"(box :b10 \\\"msg 1\\\" 180 100)\" \"(box :b11 \\\"msg 0\\\" 230 100)\"\n \"(connect :b10 0 :b9 0)\" \"(connect :b11 0 :b9 0)\" \"(connect :b9 0 :b4 0)\")\n :try \"Stop the clock and click 1: one note every 300 ms, whatever its :dur. Connect an onset~ from an adc~ instead: one note each time you play.\"}\n {:title \"At a position\"\n :note \"A number is a position in beats, as a reader reads a buffer: every event is a span that sounds while the position is inside it. Forwards it starts at its onset; backwards at its end. The wrap of a ramp (a step far larger than the ones before) is a seek: there at once.\"\n :example (lines \"(box :b12 \\\"ramp 0 6 3 loop\\\" 330 130)\" \"(box :b13 \\\"msg :bang\\\" 330 100)\"\n \"(connect :b13 0 :b12 0)\" \"(connect :b12 0 :b4 0)\")\n :try \"Stop the clock and click bang: six beats in three seconds, again and again. Change the ramp to ramp 6 0 3 loop: the phrase backwards, each note from its end. Drag a number box into it instead: you are the clock, either way.\"}]\n :see [\"pbind\" \"pattern\" \"metro\" \"ramp\" \"reader\" \"synth~\"]}\n\n \"pcclock\"\n {:package \"@kairotic/theory\" :usage \"pcclock [notes]\"\n :doc \"A pitch-class set on the clock face: its polygon, the sets before it, its axes of symmetry; its prime form and interval vector go out.\"\n :inlets [\"a list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi), a list of 12 weights (a chroma), or a number: a note, the last n notes (4) being the set; :clear\"]\n :outlets [\"the prime form, when the set changes\" \"the interval vector\" \"the pitch class pressed\"]\n :example (lines \"(box :b1 \\\"msg 60 64 67\\\" 40 30)\" \"(box :b2 \\\"msg 60 63 66 69\\\" 140 30)\" \"(box :b3 \\\"pcclock midi\\\" 40 80)\"\n \"(box :b4 \\\"print\\\" 40 330)\" \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b3 0 :b4 0)\")\n :try \"Click the major triad, then the diminished seventh: (0 3 7) has no axis, (0 3 6 9) has four. (The messages are MIDI notes, hence midi; a keyboard sends Hz, as pitches go between boxes, so a pcclock written without midi takes it directly.) Press a pitch class on the clock: it comes out on the right.\"\n :see [\"fourier\" \"tonnetz\" \"chroma~\"]}\n\n \"fourier\"\n {:package \"@kairotic/theory\" :usage \"fourier [notes]\"\n :doc \"The six Fourier coefficients of a pitch-class distribution (chromatic, dyadic, triadic, octatonic, diatonic, whole-tone), each a point in its circle with its trail.\"\n :inlets [\"a list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi), a list of 12 weights (a chroma, from chroma~), or a number: a note (the last n count: 4); :clear\"]\n :outlets [\"the six magnitudes, 0…1\" \"the six phases, in degrees\"]\n :example (lines \"(box :b1 \\\"msg 60 62 64 65 67 69 71\\\" 40 30)\" \"(box :b2 \\\"msg 60 64 68\\\" 240 30)\" \"(box :b3 \\\"fourier midi\\\" 40 80)\"\n \"(connect :b1 0 :b3 0)\" \"(connect :b2 0 :b3 0)\")\n :try \"The diatonic scale fills f5; the augmented triad, f3 and f6 at 1. With adc~ → chroma~ → fourier, sing or play and watch the trails.\"\n :see [\"pcclock\" \"tonnetz\" \"chroma~\"]}\n\n \"tonnetz\"\n {:package \"@kairotic/theory\" :usage \"tonnetz [notes]\"\n :doc \"Triads on the Tonnetz (fifths across, thirds up) and the path of the harmony: each triad found joined to the ones before.\"\n :inlets [\"a list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi), a list of 12 weights (a chroma, above 0.5), or a number: a note (the last n count: 3); :clear forgets the path\"]\n :outlets [\"the triad, when it changes (:C, :am, :Ebm…)\" \"the pitch class pressed\"]\n :example (lines \"(box :b1 \\\"msg 60 64 67\\\" 40 30)\" \"(box :b2 \\\"msg 60 63 67\\\" 130 30)\" \"(box :b3 \\\"msg 60 63 68\\\" 220 30)\"\n \"(box :b4 \\\"msg 59 63 68\\\" 310 30)\" \"(box :b5 \\\"tonnetz midi\\\" 40 80)\" \"(box :b6 \\\"print\\\" 40 340)\"\n \"(connect :b1 0 :b5 0)\" \"(connect :b2 0 :b5 0)\" \"(connect :b3 0 :b5 0)\" \"(connect :b4 0 :b5 0)\" \"(connect :b5 0 :b6 0)\")\n :try \"Click the four messages in order: C, c, A♭, g♯ — P, L, P: each step crosses one edge of the lattice. Press a node to hear which class it is (its number comes out on the right).\"\n :see [\"pcclock\" \"fourier\" \"mt\"]}\n\n \"euclid\"\n {:package \"@kairotic/theory\" :usage \"euclid [k 3] [n 8] [rotation 0] [bars 1] [midi]\"\n :about \"**A Euclidean rhythm: k onsets spread as evenly as they can be over n pulses**, by Bjorklund's algorithm — Euclid's, for the greatest common divisor, on ones and zeros. Toussaint showed that it writes rhythms of the whole world: `euclid 3 8` is the tresillo (3-3-2), `euclid 5 8` the cinquillo, `euclid 5 16` a rotation of the bossa nova, `euclid 7 12` the bembé.\n\n**Drawn as a necklace**: the n pulses around a circle, time running clockwise from the top, the onsets joined into a polygon — the same geometry as a pitch-class set on `pcclock`. A necklace has no start; pressing a pulse makes the rhythm start there (a rotation), which may sound quite different.\n\n**Rhythm apart from pitch.** It goes out as a musical tree for a `tree` box: a bar of n pulses with an `:rtm` whose shares are the intervals between onsets (a negative share a silence). Its right inlet takes the pitches the notes take in turn, starting again when they run out — *talea* and *color*, as in an isorhythmic motet: a keyboard's chord, a melody string, a map `{:pitches …}`, the pattern of `comes`. Its middle outlet is the `:rtm` map alone, to merge with other pitches elsewhere.\"\n :args [[:k \"how many onsets\"]\n [:n \"how many pulses in the bar\"]\n [:rotation \"the pulse it starts on (a rotation of the necklace)\"]\n [:bars \"how many bars: the rhythm again, the pitches going on\"]\n [:midi \"numbers on the right inlet are MIDI notes (62), not Hz\"]]\n :doc \"A Euclidean rhythm (Bjorklund, after Toussaint): k onsets as evenly as they can be over n pulses, drawn as a necklace; pressing a pulse makes it start there. Out: a musical tree with an :rtm (the intervals as shares), the :rtm map alone, and the pulses as ones and zeros. The right inlet gives the pitches its notes take in turn.\"\n :inlets [\"a bang: send it · a number: k · [:k 5], [:n 16], [:rotation 2], [:bars 4], [:meter \\\"3/4\\\"] (or a map of them): change it, and send it when it is new\"\n \"the pitches (cold, for the next time it sends): a list of Hz (a keyboard's keys held; MIDI with midi), a melody string (\\\"c4 e4 g4\\\"), a map with :pitches or :pitch, a pattern {:note [...]} of comes or cancrizans, notes or chords of a tree · :clear forgets them (every note c4)\"]\n :outlets [\"the rhythm as a musical tree, for a tree box: [:voice [:measure {:meter [4 4]} [:rtm {:shares [3 3 2] :pitches …}]] …]\"\n \"the :rtm map alone ({:shares [3 3 2]}, with the pitches if it has them): merge it with other pitches, and write it as a node with vector :rtm %\"\n \"the pulses, ones and zeros ([1 0 0 1 0 0 1 0])\"]\n :messages [[\":bang\" \"sends it\"]\n [\"[:k 5]\" \"five onsets (a number alone is k too)\"]\n [\"[:n 16]\" \"sixteen pulses\"]\n [\"[:rotation 2]\" \"starts on the third pulse\"]\n [\"[:bars 4]\" \"four bars, the pitches going on from bar to bar\"]\n [\"[:meter \\\"3/4\\\"]\" \"a bar of another meter (by default 4/4 for 8 or 16 pulses, 12/8 for 12, n/8 up to 12, else n/16; nil goes back to it)\"]\n [\":clear\" \"on the right: forgets the pitches\"]]\n :example (lines \"(box :b1 \\\"msg :bang\\\" 40 20)\" \"(box :b2 \\\"msg [:k 5]\\\" 120 20)\" \"(box :b3 \\\"msg [:n 16]\\\" 210 20)\" \"(box :b4 \\\"msg [:rotation 3]\\\" 310 20)\"\n \"(box :b5 \\\"euclid 3 8\\\" 40 70)\" \"(box :b6 \\\"tree\\\" 260 70)\" \"(resize :b6 420 160)\" \"(box :b7 \\\"print pulses\\\" 40 300)\"\n \"(connect :b1 0 :b5 0)\" \"(connect :b2 0 :b5 0)\" \"(connect :b3 0 :b5 0)\" \"(connect :b4 0 :b5 0)\" \"(connect :b5 0 :b6 0)\" \"(connect :b5 2 :b7 0)\")\n :try \"Click bang: the tresillo, 3-3-2, in the tree box as eighths in 4/4. Click [:k 5]: the cinquillo; then [:n 16]: five in sixteen, a rotation of the bossa nova; [:rotation 3] starts it on the fourth pulse — a silence first. Press a pulse on the necklace: the rhythm starts there.\"\n :steps [{:title \"Pitches: talea and color\"\n :note \"The right inlet gives the notes their pitches, in turn, starting again when they run out: three pitches over five onsets take three bars to meet the rhythm again, as the color and the talea of an isorhythmic motet. It is cold: what arrives there sounds the next time the box sends. A keyboard sends the keys held, in Hz; a melody string or a map {:pitches …} is kept as it is.\"\n :example (lines \"(box :b8 \\\"keyboard 60 24\\\" 720 20)\" \"(box :b9 \\\"msg {:pitches \\\\\\\"c4 e4 g4\\\\\\\"}\\\" 720 110)\" \"(box :b10 \\\"msg [:bars 3]\\\" 450 20)\"\n \"(box :b11 \\\"mt play loop\\\" 260 260)\" \"(box :b12 \\\"msg :bang\\\" 380 230)\" \"(box :b13 \\\"synth~\\\" 260 310)\" \"(box :b14 \\\"dac~\\\" 260 360)\"\n \"(connect :b8 0 :b5 1)\" \"(connect :b9 0 :b5 1)\" \"(connect :b10 0 :b5 0)\" \"(connect :b6 0 :b11 0)\" \"(connect :b12 0 :b11 0)\"\n \"(connect :b11 0 :b13 0)\" \"(connect :b11 1 :b13 1)\" \"(connect :b13 0 :b14 0)\" \"(connect :b13 0 :b14 1)\")\n :try \"With five onsets ([:k 5] above), click {:pitches \\\"c4 e4 g4\\\"}, then [:bars 3] (it sends): C E G over the onsets, the color going on from bar to bar. Press ▶ and click the bang of mt play to hear it. Hold a chord on the keyboard and click bang above: the chord's notes, one onset each.\"}]\n :see [\"tree\" \"mt\" \"pcclock\" \"pbind\"]}\n\n \"cancrizans\"\n {:package \"@kairotic/theory\" :usage \"cancrizans [system] [mode] [k -7] [beats 2] [bars 6] [temp 0] [seed 1] [table] [live] [midi]\"\n :about \"**A crab canon: the second voice is your line backwards**, both sounding at once, so the work reads the same from either end. With `table` it is also upside down: one score read by two players from opposite sides of a table — a musical ambigram.\n\n**It is written from both ends to the middle**, because the comes's first note is the dux's last: each step writes a note at the start and then one at the end. A note that breaks a rule, or from which the crab could not be closed, is corrected to the nearest one that can. On the right, the **futuribles**: the notes that can come next, each with the ways it leaves to close the work. When it closes, both voices go out as patterns (for `pbind` and `player`) and as a score (outlet 4, for a `tree` box).\n\n**live** (Study 46) plays it beat by beat. In the first half you play and the box answers each note, at the same beat, with the end of your own line; at the middle the rest of your line comes out as a score to read, and while you read it the box plays your first half backwards. Both voices sound from it, with their voice ids, on one `synth~`.\n\n**System and mode** as in `comes`, in any order, and with the flags: `cancrizans hypodorian`, `cancrizans pentatonic penta-A table live`. The mode sets the range, the notes to begin on, the final it ends on and the axis of a table canon; its tenor plays no part here.\"\n :args [[:system \"the scale, its tuning and its rules: diatonic (by default), meantone, septimal31 or pentatonic\"]\n [:mode \"one of the system's modes (dorian by default): its range, the notes to begin on, the final, the axis of table\"]\n [:k \"how far away the comes is, in steps of the scale: −7 an octave below\"]\n [:beats \"beats in a bar: 2 or 3\"]\n [:bars \"its length in bars: longer, more ways to write it (and longer to count)\"]\n [:temp \"live: chance in the box's answers (0: always the one :end says)\"]\n [:seed \"the seed of its chance: the same seed, the same game\"]\n [:table \"a table canon: backwards and upside down\"]\n [:live \"played beat by beat (Study 46) instead of written by turns from both ends\"]\n [:midi \"numbers in are MIDI notes (62), not Hz\"]]\n :doc \"A crab canon written from both ends to the middle (Study 43): the comes is the dux backwards; with table, backwards and upside down — the score read by a second player from across the table, a musical ambigram. Each step writes a note at the start, then one at the end; the futuribles are the ways to close the work in the middle. When it closes, both voices go out as patterns.\"\n :inlets [\"the next note (at the start, then at the end): Hz, a list of keys held, [:midi 62], an event (:freq, or a player's :hz), or MIDI with midi · :engine · :back · :reset · [:k -4], [:mode :hypodorian], [:system :pentatonic], [:bars 5], [:table true], [:axis 62]: a new work\"\n \"live: the pulse (a bang from a metro or a pulse): a beat, with your note or the box's for you\"]\n :outlets [\"the dux, when the work closes, as a pattern {:note [...] :dur [...]} (for a pbind) · live: the Hz of both voices, yours and the box's, as a player sends them (for a synth~)\" \"the comes, as a pattern · live: their voice ids, sent first (for a synth~'s right inlet)\" \"the futuribles: the notes that can come next ({:midi :name :futures}; live, with :end, what the box will answer at the end)\" \"where the work is: {:step :steps :writing :beat :futures :dux :comes :closed :asked :played :corrected}\" \"the score, as a musical tree (for a tree box, its score): when the work closes, both voices; live, at the middle what is left of your line to read, and at the end the whole crab\"]\n :messages [[\"[:midi 62]\" \"a MIDI note as the next note (Hz, a keyboard's list or an event also)\"]\n [\":engine\" \"the next note, written by the box (live: a beat, with the box playing your note)\"]\n [\":back\" \"the last note taken back\"]\n [\":reset\" \"a new work\"]\n [\"[:system :septimal31]\" \"another system (or an EDN map) — these start a new work\"]\n [\"[:mode :hypodorian]\" \"another mode of the system\"]\n [\"[:k -4]\" \"the comes a 5th below\"]\n [\"[:bars 5]\" \"another length\"]\n [\"[:table true]\" \"a table canon: backwards and upside down\"]\n [\"[:axis 62]\" \"the axis of a table canon, a MIDI note (the final by default)\"]\n [\"[:temp 2]\" \"live: the box draws among its answers\"]\n [\"[:seed 7]\" \"live: its chance (:reset plays the same game again)\"]]\n :example (lines \"(box :b1 \\\"msg :engine\\\" 40 30)\" \"(box :b2 \\\"cancrizans\\\" 40 80)\" \"(box :b3 \\\"pbind\\\" 40 150)\" \"(box :b4 \\\"pbind\\\" 40 260)\"\n \"(box :b9 \\\"msg :start\\\" 40 370)\" \"(box :b5 \\\"player 90\\\" 40 420)\" \"(box :b6 \\\"player 90\\\" 240 420)\" \"(box :b7 \\\"synth~\\\" 40 490)\"\n \"(box :b17 \\\"synth~\\\" 240 490)\" \"(box :b8 \\\"dac~\\\" 40 550)\" \"(box :b10 \\\"print\\\" 260 80)\"\n \"(box :b19 \\\"tree\\\" 40 620)\" \"(resize :b19 460 200)\" \"(connect :b2 4 :b19 0)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b2 1 :b4 0)\" \"(connect :b3 0 :b5 1)\" \"(connect :b4 0 :b6 1)\"\n \"(connect :b9 0 :b5 0)\" \"(connect :b9 0 :b6 0)\" \"(connect :b5 0 :b7 0)\" \"(connect :b6 0 :b17 0)\"\n \"(connect :b7 0 :b8 0)\" \"(connect :b7 0 :b8 1)\" \"(connect :b17 0 :b8 0)\" \"(connect :b17 0 :b8 1)\" \"(connect :b2 3 :b10 0)\")\n :try \"Click :engine until the work closes: the box writes it from both ends, and the dux and the comes reach the pbinds. Press ▶ and click :start: the crab sounds, each voice on its own synth~ (one synth~ plays one line: a note from the other player would take the place of the last). The tree box below shows the crab as a score: read the comes from the end and it is the dux. Play notes on a keyboard into it instead (the note at the start, then the one at the end).\"\n :steps [{:title \"Played live\"\n :note \"With live (Study 46) the crab is played beat by beat: your note, and at the same beat the box's answer — the end of your own line, written ahead. Two beats before the middle a cue; at the middle the rest of your line comes out as the score to read (outlet 4, a musical tree for a score), and the box plays your first half backwards while you read it. Both voices sound from its left outlet, after their voice ids (outlet 1): one synth~ plays both. The first note to read is the last end of your line the box wrote (with an odd number of beats the middle note is shared: the box plays it with you, an octave below); from there each voice plays what the other played, backwards.\"\n :example (lines \"(box :b11 \\\"keyboard 60 24\\\" 520 30)\" \"(box :b12 \\\"cancrizans live\\\" 520 150)\" \"(box :b13 \\\"synth~\\\" 520 230)\" \"(box :b15 \\\"loadbang\\\" 720 110)\"\n \"(box :b16 \\\"html\\\" 860 30)\" \"(resize :b16 300 230)\"\n \"(code :b16 \\\"[:div.col [:h4 \\\\\\\"beat \\\\\\\" :$t \\\\\\\" of \\\\\\\" :$n \\\\\\\" · \\\\\\\" :$phase] [:p.soft :$ways \\\\\\\" ways to close it\\\\\\\"] :$in]\\\")\"\n \"(box :b14 \\\"tree\\\" 860 290)\" \"(resize :b14 460 180)\"\n \"(connect :b15 0 :b12 0)\" \"(connect :b12 2 :b16 0)\" \"(connect :b12 3 :b16 0)\" \"(connect :b12 4 :b14 0)\"\n \"(connect :b11 0 :b12 0)\" \"(connect :b12 0 :b13 0)\" \"(connect :b12 1 :b13 1)\" \"(connect :b13 0 :b8 0)\" \"(connect :b13 0 :b8 1)\")\n :try \"Press ▶: the loadbang counts the futures. The html box shows where the crab is and its futuribles as a table — each note you can play, the ways it leaves to close the crab, and :end, what the box will answer at the end of your line. Play D on the keyboard: the box answers with D an octave below — both voices on one synth~, yours as the box takes it (corrected if it must be), with their voice ids (1→1). Play on: at the middle the tree box shows, as a score, what is left of your line to read — the box's answers so far, backwards —; at the end it shows the whole crab.\"}]\n :see [\"comes\" \"pbind\" \"player\"]}\n\n \"comes\"\n {:package \"@kairotic/theory\" :usage \"comes [system] [mode] [k -7] [d 3] [beats 2] [imitation 1] [bars 8] [upbeat 0] [temp 0] [seed 1] [fourth] [inversion] [augmentation] [live] [nocues] [midi]\"\n :about \"**You play a line, the dux, and comes answers with a second voice, the comes, that imitates it** — a canon, a few beats later, by the rules of 16th-century counterpoint. A note that breaks a rule, or from which the canon could not be finished, is corrected to the nearest one that can be played, and the box says why.\n\n**Two ways to play.** By turns (the default): each note you send is a beat; the same note again, or `:hold`, holds it over the beat. With **live**, a pulse on the right inlet (a `metro`) gives the beats and a note lasts until you play the next one; held three beats in 2/2 the canon turns to 3/2, longer than a bar the section ends and the next note begins a new canon.\n\n**Where it plays: a system and one of its modes.** The **system** is the scale, its tuning and its rules: `diatonic` (the default), `meantone`, `septimal31`, `pentatonic`, or your own as EDN. The **mode** is one of its modes — `dorian` (the default), `hypodorian`, `ionian`, `aeolian`…; in the pentatonic `penta-C`, `penta-A`, `penta-D` — and sets the final, the range and the notes to begin on. Write them in the box in any order: `comes hypodorian`, `comes pentatonic penta-A`.\n\n**How the comes imitates.** `k` steps away (−7: an octave below) and `d` beats later. `imitation` 1 is a strict canon; lower, the comes moves more freely. `inversion` turns it upside down, `augmentation` makes it twice as slow, and `fourth` makes your line a cantus firmus (a note a bar) with the comes syncopated against it.\n\n**What comes out.** Both voices as Hz with their voice ids — one `synth~`, connected 0→0 and 1→1, plays both —; on the right the **futuribles**, the notes you can play next, the most plausible first, each with the ways it leaves to finish the canon (counted exactly), and where the canon is.\"\n :args [[:system \"the scale, its tuning and its rules: diatonic (by default), meantone, septimal31 or pentatonic\"]\n [:mode \"one of the system's modes: dorian (by default), hypodorian, ionian, mixolydian, aeolian and their plagals; penta-C, penta-A, penta-D in the pentatonic\"]\n [:k \"how far away the comes imitates, in steps of the scale: −7 an octave below, −4 a 5th below, 0 at the unison\"]\n [:d \"how many beats after the dux the comes comes in\"]\n [:beats \"beats in a bar: 2 (2/2) or 3 (3/2)\"]\n [:imitation \"1 a strict canon · 0.5–0.9 the comes near the dux's notes · 0.2–0.4 only following its motion · below, free\"]\n [:bars \"how long the canon is, in bars\"]\n [:upbeat \"beats of rest before the first note (an anacrusis)\"]\n [:temp \"chance: at 0 always the most plausible; higher, the comes (and the dux with :engine) drawn among the candidates\"]\n [:seed \"the seed of its chance: the same seed, the same game\"]\n [:fourth \"fourth species: your line a cantus firmus, a note a bar, and the comes syncopated\"]\n [:inversion \"the comes upside down, about the final (or [:axis 62])\"]\n [:augmentation \"the comes twice as slow (a strict canon, six bars at most)\"]\n [:live \"played on a pulse (the right inlet) instead of by turns\"]\n [:nocues \"live: it does not turn to 3/2 or end the section by itself; other boxes decide, with [:beats 3] and :end\"]\n [:midi \"numbers in are MIDI notes (62), not Hz\"]]\n :doc \"Counterpoint live: you play the dux and the comes answers, as a canon in a mode (Study 41). A note that breaks a rule of the style, or from which the canon could not be finished, is corrected to the nearest one that can be played, and the box says why. Notes may be held over the beat (ties), and a dissonance may fall on a strong beat as a suspension. By turns (the default) one note in is one beat; live, a pulse on the right is a beat, and a note lasts until the next one is struck. The system (Study 42) — the scale, its tuning and its rules — is diatonic by default, or meantone, septimal31, pentatonic, or an EDN map: its modes come with it, and the notes out are tuned.\"\n :inlets [\"the dux's next note: Hz (a number, or the list of notes held, as a keyboard or midiin sends them), [:midi 62], or an event (:freq from midiin, or a player's :hz) · :hold (by turns) · [:k -4], [:d 2], [:imitation 0.5], [:mode :hypodorian], [:system :pentatonic], [:beats 3], [:species 4]: the canon changed (by turns at once, live at the next section) · :end (the section ends: the next note begins a new canon) · :engine · :back · :reset\"\n \"live: the pulse (a bang from a metro or a pulse): a beat\"]\n :outlets [\"the Hz of both voices sounding, the dux (as played, or corrected) and the comes, as a keyboard or a player sends them\" \"their voice ids, sent first (for a synth~'s right inlet): a note held keeps its id and goes on sounding\" \"the futuribles: the notes that can come next, the most plausible first ({:midi :name :futures :bits :score :comes})\" \"where the canon is: {:t :n :bar :beat :held :asked :played :corrected :reason :comes :futures :bits :obligations :section :meter …}, or a cue {:cue :ternary|:end :section :meter}\"]\n :messages [[\"[:midi 62]\" \"a MIDI note as the dux's next note (Hz, a keyboard's list or an event also)\"]\n [\":engine\" \"the box plays the next pair itself, the most plausible\"]\n [\":hold\" \"by turns: the note held over the next beat (a tie)\"]\n [\":back\" \"the last pair taken back\"]\n [\":reset\" \"a new canon\"]\n [\":end\" \"the section ends: the next note begins a new canon\"]\n [\"[:system :pentatonic]\" \"another system (or an EDN map {:tuning … :modes …}) — these change the canon: by turns at once, live at the next section\"]\n [\"[:mode :hypodorian]\" \"another mode of the system\"]\n [\"[:k -4]\" \"the comes a 5th below\"]\n [\"[:d 2]\" \"the comes two beats after the dux\"]\n [\"[:imitation 0.5]\" \"less imitation: the comes near the dux's notes\"]\n [\"[:beats 3]\" \"3/2\"]\n [\"[:species 4]\" \"fourth species (with [:beats 2])\"]\n [\"[:transform :inversion]\" \"the comes upside down; :augmentation twice as slow; :canon back to a canon\"]\n [\"[:axis 62]\" \"the axis of the inversion, a MIDI note\"]\n [\"[:temp 1.5]\" \"chance in the comes, and in the dux of :engine (0: the futuribles' choice)\"]\n [\"[:seed 7]\" \"its chance: the same seed, the same game (:reset plays it again)\"]]\n :example (lines \"(box :b1 \\\"keyboard 60 24\\\" 40 30)\" \"(box :b2 \\\"comes\\\" 40 130)\" \"(box :b3 \\\"synth~\\\" 40 200)\"\n \"(box :b5 \\\"dac~\\\" 40 260)\" \"(box :b6 \\\"print\\\" 280 200)\" \"(box :b7 \\\"msg :engine\\\" 220 100)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b7 0 :b2 0)\" \"(connect :b2 0 :b3 0)\" \"(connect :b2 1 :b3 1)\"\n \"(connect :b3 0 :b5 0)\" \"(connect :b3 0 :b5 1)\" \"(connect :b2 3 :b6 0)\")\n :try \"Press ▶ and play D, E, F on the keyboard: the dux. From the fourth note on the comes answers an octave below, three beats later. Play a black key, or a note against the rules: the box takes the nearest one that can be played and prints why. Click :engine to let it go on alone.\"\n :steps [{:title \"Live, on a pulse\"\n :note \"With live, a metro gives the beats: hold a key and the note is held over them (a tie); hold it three beats in 2/2 and the canon turns to 3/2; longer than a bar, and the section ends: the next note begins a new canon. That is all comes reads of time: with nocues it leaves the meter and the sections to other boxes, which send [:beats 3] and end.\"\n :example (lines \"(box :b8 \\\"metro 600\\\" 380 100)\" \"(box :b9 \\\"msg 1\\\" 380 70)\" \"(box :b10 \\\"comes live\\\" 380 160)\"\n \"(connect :b9 0 :b8 0)\" \"(connect :b8 0 :b10 1)\" \"(connect :b1 0 :b10 0)\" \"(connect :b10 0 :b3 0)\" \"(connect :b10 1 :b3 1)\" \"(connect :b10 3 :b6 0)\")\n :try \"Press ▶, click 1 to start the pulse and play slowly: the comes answers on the beats. Hold a note three beats: the cue :ternary is printed.\"}]\n :see [\"keyboard\" \"midiin\" \"metro\" \"pulse\" \"tonnetz\"]}\n\n \"adsr~\"\n {:package \"@kairotic/synth\" :usage \"adsr~ [a d s r]\"\n :doc \"An envelope that follows a gate, for the factor of a gain~. Drag over it to change its shape.\"\n :inlets [\"a gate (signal or numbers: above 0 attacks, 0 releases), a bang, or [a d s r]\"]\n :outlets [\"the envelope signal, 0…peak\"]\n :example (lines \"(box :b1 \\\"bang\\\" 40 30)\" \"(box :b2 \\\"adsr~ 10 300 0 400\\\" 40 80)\" \"(box :b3 \\\"osc~ 440\\\" 220 80)\"\n \"(box :b4 \\\"gain~ 0\\\" 220 220)\" \"(box :b5 \\\"dac~\\\" 220 270)\"\n \"(connect :b1 0 :b2 0)\" \"(connect :b2 0 :b4 1)\" \"(connect :b3 0 :b4 0)\"\n \"(connect :b4 0 :b5 0)\" \"(connect :b4 0 :b5 1)\")\n :try \"Start the engine and click the bang: a plucked note. Drag over the envelope to make it longer.\"\n :see [\"gain~\" \"reader~\" \"synth~\"]}\n\n \"gendy~\"\n {:package \"@kairotic/synth\" :usage \"gendy~ [freq x-step y-min y-max y-step breakpoints]\"\n :doc \"A dynamic stochastic oscillator, after Xenakis's GENDY: a wave of breakpoints whose amplitudes and durations each take a random walk between mirror barriers, cycle after cycle — a pitch that drifts, a timbre that changes.\"\n :inlets [\"a number: the frequency in Hz · [:x-step 30], [:y-step 0.2]…: one parameter · a list of six: all of them · a signal: added to the frequency, in Hz (FM)\"]\n :outlets [\"the sound (about ±0.15 by default: y-min and y-max are its barriers)\"]\n :messages [[\"220\" \"the frequency\"] [\"[:x-step 40]\" \"how far the durations wander (0–100 %): the pitch drifts\"]\n [\"[:y-step 0.2]\" \"how far the amplitudes move each cycle: the timbre changes faster\"]\n [\"[:breakpoints 6]\" \"fewer breakpoints, a simpler wave (more of them, a richer one); changing it keeps the wave\"]\n [\"[220 10 -0.15 0.15 0.05 16]\" \"freq x-step y-min y-max y-step breakpoints\"]]\n :example \"(box :b1 \\\"gendy~ 110\\\" 40 30)\\n(box :b2 \\\"dac~\\\" 40 90)\\n(box :b3 \\\"scope~ 30\\\" 160 90)\\n(connect :b1 0 :b2 0)\\n(connect :b1 0 :b2 1)\\n(connect :b1 0 :b3 0)\"\n :try \"Press ▶: a buzz whose pitch and colour never settle. Write gendy~ 110 0 in the box: with no wander of the durations, the pitch holds and only the timbre moves.\"\n :steps [{:title \"The two walks\"\n :note \"x-step lets the durations wander (the pitch), y-step the amplitudes (the timbre). Two knobs send them by name.\"\n :example \"(box :b4 \\\"knob 0 100 10 x-step\\\" 360 20)\\n(box :b5 \\\"knob 0 0.3 0.05 y-step\\\" 450 20)\\n(connect :b4 0 :b1 0)\\n(connect :b5 0 :b1 0)\"\n :try \"Press ▶ and turn x-step up: the pitch scatters into noise. Turn it down and y-step up: one pitch, a restless colour.\"}\n {:title \"Breakpoints\"\n :note \"Few breakpoints make a simple wave, close to a triangle or a square; many, a richer and noisier one. Changing their number keeps the wave, with no click.\"\n :example \"(box :b6 \\\"msg :breakpoints 4\\\" 360 120)\\n(box :b7 \\\"msg :breakpoints 48\\\" 500 120)\\n(connect :b6 0 :b1 0)\\n(connect :b7 0 :b1 0)\"\n :try \"Press ▶ and click both messages in turn, watching the scope.\"}\n {:title \"A signal on the inlet: FM\"\n :note \"A signal connected to the inlet is added to the frequency, in Hz: a slow one makes a vibrato, a fast one frequency modulation.\"\n :example \"(box :b8 \\\"osc~ 5\\\" 360 200)\\n(box :b9 \\\"gain~ 300\\\" 360 250)\\n(connect :b8 0 :b9 0)\\n(connect :b9 0 :b1 0)\"\n :try \"Press ▶: 5 Hz around 110 Hz. Change osc~ 5 to osc~ 80 for a rougher sound.\"}]\n :see [\"osc~\" \"synth~\" \"faust~\"]}\n\n \"synth~\"\n {:package \"@kairotic/synth\" :usage \"synth~\"\n :doc \"Polyphonic triangle-wave synthesizer, one voice per id.\"\n :inlets [\"frequencies (a number or a list) · :stop\" \"voice ids (from a reader)\"]\n :outlets [\"the sound\"]\n :see [\"reader\" \"adsr~\"]}\n\n \"pan~\"\n {:package \"@kairotic/spatial\" :usage \"pan~ [position]\"\n :doc \"Stereo panning with equal power.\"\n :inlets [\"the signal\" \"the position: −1 left … 1 right\"]\n :outlets [\"left\" \"right\"]\n :see [\"space~\" \"dac~\"]}\n\n \"space~\"\n {:package \"@kairotic/spatial\" :usage \"space~ [x y]\"\n :doc \"A sound placed around the listener (binaural): drag the dot, or send [x y]. For headphones.\"\n :inlets [\"the signal; [x y] moves it (−1…1, y = 1 in front)\"]\n :outlets [\"left\" \"right\"]\n :see [\"pan~\" \"reader\"]}})\n\n(defn of\n \"The help of a class: its own :help, or the core one.\"\n [cls]\n (let [d (comp/lookup cls)]\n (merge (get core cls) (:help d))))\n\n(defn patch-steps\n \"The steps of the help patch of a class: its :example (with :try) first, then its :steps.\n [{:title :note :try :code [\\\"(box …)\\\" …]} …], empty when it has no help patch.\"\n [cls]\n (let [h (of cls)\n code (fn [e] (->> (str/split-lines (str e)) (map str/trim) (remove str/blank?) vec))]\n (vec (concat (when (:example h)\n [{:title cls :note (or (:doc (comp/lookup cls)) (:doc h) \"\") :try (or (:try h) \"\") :code (code (:example h))}])\n (for [st (:steps h)]\n {:title (or (:title st) cls) :note (or (:note st) \"\") :try (or (:try st) \"\") :code (code (:example st))})))))\n\n(defn known\n \"Every class with a help page (registered or listed here).\"\n []\n (sort (distinct (concat (keys core) (map first (comp/listing))))))\n","kairotic/hiccup.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · hiccup: a box whose view is a small HTML document, written as data (issue #146)\n;; Sliders, fields, menus, buttons and text, laid out like a web page, for interfaces that would be slow\n;; to draw with shapes (kairotic.shapes). The view is hiccup in EDN, never HTML text: before it is kept,\n;; and again before it is drawn, it goes through an allowlist of tags, attributes and style properties,\n;; and it is built with the DOM (createElement, textContent), never with innerHTML. It carries no code,\n;; so it is safe in a shared room without (trust-scripts true), like a tree box.\n;;\n;; [:div.row a tag, with classes after dots\n;; [:label \"freq \" [:input {:type \"range\" :name \"freq\" :min 100 :max 1000 :value 440 :out 0}]]\n;; [:span :$freq \" Hz\"] a hole: the value of freq, kept up to date\n;; [:button {:out 1 :send :bang} \"go\"]] a click sends :bang out of outlet 1\n;;\n;; :out o what the element gives goes out of outlet o (a slider or a number field a number, a checkbox\n;; 1 or 0, a menu or a radio its value, a text field its text, a button its :send or a bang)\n;; :name n the element shows the value called n, and what it gives becomes that value: a hole :$n\n;; anywhere in the view shows it too. A map {:freq 220} on the inlet sets values, [:freq 220] one,\n;; as a number sets a knob: shown (a slider within its range) and sent on by the elements named so\n;; that have :out; a bang sends again what they hold.\n;; Let go (a slider) or chosen (a menu, a text entered), the value is kept in the box's data,\n;; (values! :bN {:freq 440}), one event of the history, as a knob keeps its value in its text.\n;; :style a map of the allowed properties: {:gap 8 :color :accent} (numbers are pixels, a palette\n;; colour :ink :soft :accent :kairos :bg :grid follows the light or dark theme)\n;;\n;; HTML can be pasted too (in the code window or with (code :bN \"<div>…</div>\")): it is read with the\n;; browser's DOMParser, turned into hiccup (data-out and data-send become :out and :send, \"$freq\" in a\n;; text becomes a hole) and goes through the same allowlist. Only the hiccup is kept.\n\n(ns kairotic.hiccup\n (:require [clojure.string :as str]\n [clojure.edn :as edn]\n [kairotic.components :as comp]))\n\n;; ───────── the allowlist ─────────\n\n(def tags #{:div :span :p :label :input :select :option :button :textarea :output\n :h1 :h2 :h3 :h4 :ul :ol :li :br :hr :b :i :em :strong :small :code :pre :sub :sup\n :table :thead :tbody :tr :td :th :fieldset :legend :meter :progress :details :summary})\n\n(def void-tags #{:input :br :hr})\n\n;; every allowed element: :class :title :name :out :send :style :hidden; and these, by tag\n(def common-attrs #{:class :title :name :out :send :style :hidden})\n(def tag-attrs\n {:input #{:type :min :max :step :value :placeholder :checked :disabled :size :maxlength}\n :select #{:value :disabled}\n :option #{:value :selected :disabled}\n :button #{:disabled}\n :textarea #{:placeholder :rows :cols :value :disabled :maxlength}\n :meter #{:min :max :value :low :high :optimum}\n :progress #{:max :value}\n :td #{:colspan :rowspan}\n :th #{:colspan :rowspan}\n :ol #{:start}\n :details #{:open}})\n\n(def flag-attrs #{:checked :disabled :selected :hidden :open})\n(def input-types #{\"range\" \"number\" \"text\" \"checkbox\" \"radio\" \"color\"})\n\n;; style properties: no position, no background images, nothing that loads anything or leaves the box\n(def style-props\n #{:color :background-color :border :border-color :border-width :border-style :border-radius\n :font-size :font-weight :font-style :font-family :text-align :text-decoration :line-height :letter-spacing\n :white-space :vertical-align\n :padding :padding-top :padding-right :padding-bottom :padding-left\n :margin :margin-top :margin-right :margin-bottom :margin-left\n :width :height :min-width :max-width :min-height :max-height\n :display :flex :flex-direction :flex-wrap :flex-grow :flex-shrink :flex-basis\n :align-items :align-self :justify-content :gap :row-gap :column-gap\n :grid-template-columns :grid-template-rows :grid-column :grid-row\n :opacity :overflow :accent-color})\n(def unitless #{:opacity :flex :flex-grow :flex-shrink :font-weight :line-height})\n(def palette {:ink \"var(--ink)\" :soft \"var(--ink-soft)\" :accent \"var(--accent)\" :kairos \"var(--kairos)\"\n :bg \"var(--box)\" :grid \"var(--grid)\"})\n\n(def max-nodes 400)\n(def max-depth 12)\n(def max-text 2000)\n(def max-attr 200)\n(def max-outlets 16)\n\n;; ───────── reading it safely ─────────\n\n(defn hole? [x] (and (keyword? x) (str/starts-with? (name x) \"$\") (> (count (name x)) 1)))\n(defn hole-key [x] (keyword (subs (name x) 1)))\n\n(defn value-name\n \"A name for a value (:freq, \\\"freq\\\"), as a keyword, or nil if it is not one.\"\n [x]\n (let [s (cond (keyword? x) (name x) (string? x) x :else nil)]\n (when (and s (re-matches #\"[A-Za-z][A-Za-z0-9_-]{0,40}\" s)) (keyword s))))\n\n(defn- css-value\n \"A style value written safely, or nil: palette colours, numbers, and short plain words.\"\n [k v]\n (cond\n (contains? palette v) (palette v)\n (and (number? v) (js/isFinite v)) (if (unitless k) (str v) (str v \"px\"))\n (string? v) (let [s (str/trim v)]\n (when (and (<= (count s) 80)\n (re-matches #\"[-#%.,()a-zA-Z0-9 ]*\" s)\n (not (re-find #\"(?i)url|expression|image|attr|src|import\" s)))\n s))\n (keyword? v) (css-value k (name v))\n :else nil))\n\n(defn- clean-style [m]\n (when (map? m)\n (not-empty (into (sorted-map) (for [[k v] m :let [k (keyword k)] :when (style-props k)\n :let [s (css-value k v)] :when (some? s)]\n [k (if (or (contains? palette v) (number? v)) v s)])))))\n\n(defn- clean-classes [x]\n (let [words (cond (string? x) (str/split (str/trim x) #\"\\s+\")\n (keyword? x) [(name x)]\n (sequential? x) (map (fn [w] (if (keyword? w) (name w) (str w))) x)\n :else [])]\n (not-empty (str/join \" \" (filter (fn [w] (re-matches #\"[A-Za-z][A-Za-z0-9_-]{0,30}\" w)) words)))))\n\n(defn- scalar? [v] (or (string? v) (number? v) (boolean? v) (keyword? v)))\n\n(defn- clean-send [v]\n (cond (and (string? v) (<= (count v) max-attr)) v\n (and (number? v) (js/isFinite v)) v\n (or (keyword? v) (boolean? v)) v\n (and (vector? v) (<= (count v) 16) (every? (fn [x] (and (scalar? x) (not (and (string? x) (> (count x) max-attr))))) v)) v\n :else nil))\n\n(defn- clean-attr [tag k v]\n (case k\n :class (clean-classes v)\n :style (clean-style v)\n :name (value-name v)\n :out (when (and (integer? v) (<= 0 v) (< v max-outlets)) v)\n :send (clean-send v)\n :type (when (contains? input-types (str (if (keyword? v) (name v) v))) (str (if (keyword? v) (name v) v)))\n (cond\n (flag-attrs k) (when (or (true? v) (hole? v) (= v \"\") (= v (name k))) (if (hole? v) v true))\n (hole? v) v\n (and (number? v) (js/isFinite v)) v\n (and (string? v) (<= (count v) max-attr)) v\n (keyword? v) (name v)\n :else nil)))\n\n(defn- clean-attrs [tag m classes]\n (let [allowed (into common-attrs (get tag-attrs tag))\n m (if (map? m) m {})\n m (if (seq classes) (update m :class (fn [c] (str/join \" \" (remove str/blank? (concat classes [(clean-classes c)]))))) m)]\n (into (sorted-map)\n (for [[k v] m :let [k (keyword k)\n ;; pasted HTML spells them data-out and data-send\n k (get {:data-out :out :data-send :send :data-name :name} k k)]\n :when (allowed k)\n :let [c (clean-attr tag k v)] :when (some? c)]\n [k c]))))\n\n(defn- split-tag\n \"A tag keyword with classes after dots (:div.row.big) → [:div [\\\"row\\\" \\\"big\\\"]].\"\n [kw]\n (let [[t & cs] (str/split (name kw) #\"\\.\")]\n [(keyword (str/lower-case t)) (vec (remove str/blank? cs))]))\n\n(defn sanitize\n \"Hiccup made safe: what is not allowed is dropped (a tag with everything inside it, an attribute, a\n style property). Returns {:view hiccup-or-nil :dropped [\\\"…\\\" …]}.\"\n [x]\n (let [budget (atom max-nodes) dropped (atom [])\n drop! (fn [what] (when (< (count @dropped) 12) (swap! dropped conj what)) nil)\n node (fn node [x depth]\n (cond\n (<= @budget 0) (drop! \"more than 400 elements\")\n (> depth max-depth) (drop! \"more than 12 levels deep\")\n (string? x) (subs x 0 (min (count x) max-text))\n (and (number? x) (js/isFinite x)) (str x)\n (hole? x) x\n (and (vector? x) (keyword? (first x)))\n (let [[tag classes] (split-tag (first x))\n [attrs kids] (if (map? (second x)) [(second x) (drop 2 x)] [{} (rest x)])]\n (if-not (tags tag)\n (drop! (str \"<\" (name tag) \">\"))\n (do (swap! budget dec)\n (doseq [k (keys attrs) :let [k (keyword k) k (get {:data-out :out :data-send :send :data-name :name} k k)]\n :when (not (contains? (into common-attrs (get tag-attrs tag)) k))]\n (drop! (str (name tag) \" \" (name k))))\n (let [a (clean-attrs tag attrs classes)\n cs (if (void-tags tag) [] (vec (keep (fn [c] (node c (inc depth))) (mapcat (fn [c] (if (and (sequential? c) (not (and (vector? c) (keyword? (first c))))) c [c])) kids))))]\n (into (if (seq a) [tag a] [tag]) cs)))))\n (nil? x) nil\n :else (drop! (str \"a \" (cond (map? x) \"map\" (sequential? x) \"list\" :else (str (type x))) \" outside an element\"))))]\n {:view (let [v (node x 0)] (when (vector? v) v)) :dropped @dropped}))\n\n(defn clean\n \"The safe form of a view, or nil.\"\n [x]\n (:view (sanitize x)))\n\n;; ───────── HTML → hiccup (in the browser) ─────────\n\n(defn- text-parts [s]\n (vec (remove nil? (let [ps (str/split s #\"\\$[A-Za-z][A-Za-z0-9_-]*\" -1)\n hs (mapv (fn [m] (keyword m)) (re-seq #\"\\$[A-Za-z][A-Za-z0-9_-]*\" s))]\n (concat (mapcat (fn [i p] (cond-> (if (= p \"\") [] [p]) (< i (count hs)) (conj (nth hs i))))\n (range) ps))))))\n\n(defn- read-scalar\n \"An attribute of pasted HTML: a number, a :keyword, a $hole, or the text.\"\n [s]\n (cond (re-matches #\"-?\\d+(\\.\\d+)?\" s) (js/parseFloat s)\n (re-matches #\":[A-Za-z][A-Za-z0-9_-]*\" s) (keyword (subs s 1))\n (re-matches #\"\\$[A-Za-z][A-Za-z0-9_-]*\" s) (keyword s)\n :else s))\n\n(defn- parse-style [s]\n (into {} (for [decl (str/split (str s) #\";\")\n :let [[k v] (map str/trim (str/split decl #\":\" 2))]\n :when (and (seq k) (seq v))]\n [(keyword (str/lower-case k)) (if (re-matches #\"-?\\d+(\\.\\d+)?px\" v) (js/parseFloat v) v)])))\n\n(defn- dom->hiccup [n]\n (case (.-nodeType n)\n 3 (let [t (.-textContent n)] (when-not (str/blank? t) (text-parts (str/replace t #\"\\s+\" \" \"))))\n 1 (let [tag (keyword (str/lower-case (.-tagName n)))\n attrs (into {} (for [a (array-seq (.-attributes n))\n :let [k (keyword (str/lower-case (.-name a))) v (.-value a)]]\n [k (case k\n :style (parse-style v)\n (:checked :disabled :selected :hidden :open) true\n (:class :title :placeholder :type) v\n (read-scalar v))]))\n kids (vec (mapcat (fn [c] (let [h (dom->hiccup c)]\n (cond (nil? h) [] (and (vector? h) (keyword? (first h))) [h] :else h)))\n (array-seq (.-childNodes n))))]\n (into (if (seq attrs) [tag attrs] [tag]) kids))\n nil))\n\n(defn html->hiccup\n \"HTML text → hiccup (not yet made safe: `sanitize` does that). Several elements are wrapped in a div.\"\n [text]\n (let [doc (.parseFromString (js/DOMParser.) (str text) \"text/html\")\n kids (vec (mapcat (fn [c] (let [h (dom->hiccup c)]\n (cond (nil? h) [] (and (vector? h) (keyword? (first h))) [h] :else h)))\n (array-seq (.. doc -body -childNodes))))]\n (if (and (= 1 (count kids)) (vector? (first kids))) (first kids) (into [:div] kids))))\n\n(defn read-view\n \"The text of a view (EDN hiccup, or HTML when it starts with <) → safe hiccup. Throws with a reason.\"\n [text]\n (let [s (str/trim (str text))\n raw (cond (str/blank? s) (throw (js/Error. \"the view is empty: [:div …]\"))\n (str/starts-with? s \"<\") (if (some? (.-DOMParser js/globalThis))\n (html->hiccup s)\n (throw (js/Error. \"HTML can only be read in a browser\")))\n :else (try (edn/read-string s)\n (catch :default e (throw (js/Error. (str \"That is not EDN: \" (.-message e)))))))\n {:keys [view]} (when (and (vector? raw) (keyword? (first raw))) (sanitize raw))]\n (if view view (throw (js/Error. \"a view is an element of hiccup: [:div …] (or HTML)\")))))\n\n;; ───────── writing it ─────────\n\n(defn- element? [x] (and (vector? x) (keyword? (first x))))\n\n(defn pp\n \"The view as text, one element per line where it holds other elements.\"\n ([h] (pp h 0))\n ([h indent]\n (let [[tag & more] h\n [attrs kids] (if (map? (first more)) [(first more) (rest more)] [nil more])\n head (str \"[\" (pr-str tag) (when (seq attrs) (str \" \" (pr-str attrs))))]\n (if (some element? kids)\n (let [pad (apply str (repeat (inc indent) \" \"))]\n (str head (apply str (map (fn [k] (str \"\\n\" pad (if (element? k) (pp k (inc indent)) (pr-str k)))) kids)) \"]\"))\n (str head (apply str (map (fn [k] (str \" \" (pr-str k))) kids)) \"]\")))))\n\n(defn outlets\n \"How many outlets a view asks for: one more than its highest :out (at least one).\"\n [h]\n (let [os (keep (fn [x] (when (map? x) (:out x))) (tree-seq sequential? seq h))]\n (if (seq os) (inc (apply max os)) 1)))\n\n;; ───────── the box ─────────\n\n(def default-view\n [:div {:class \"col\"}\n [:label \"freq \" [:input {:type \"range\" :name \"freq\" :min 100 :max 1000 :step 1 :value 440 :out 0}]]\n [:div {:class \"row\"} [:output :$freq \" Hz\"] [:button {:out 1 :send :bang} \"go\"]]])\n\n(defn view-of\n \"The (safe) view a box shows: what it keeps, made safe again (it may come from a room or a link).\"\n [data]\n (or (clean (:view data)) default-view))\n\n;; The values its named elements hold are kept in its data, as a knob keeps its value in its text: when a\n;; slider is let go, a menu chosen, a text entered, (values! :bN {:freq 440}) writes them as one event of the\n;; history, so they travel with the work and going back in the history brings back the ones it had.\n\n(def max-values 64)\n\n(defn- value-ok? [v]\n (or (nil? v) (boolean? v) (keyword? v)\n (and (number? v) (js/isFinite v))\n (and (string? v) (<= (count v) max-text))))\n\n(defn clean-values\n \"The values of a map that can be kept: named by a word, scalars (a text up to 2000 characters), 64 at most.\"\n [m]\n (if (map? m)\n (into (sorted-map) (take max-values (for [[k v] m :let [k (value-name k)] :when (and k (value-ok? v))] [k v])))\n (sorted-map)))\n\n(defn- with-values [d vs] (if (seq vs) (assoc d :values vs) (dissoc d :values)))\n\n(def model\n {:empty {:view default-view}\n :step (fn step [d [op x]]\n (case op\n :set (if-let [v (clean x)] (assoc d :view v) d)\n ;; the values its elements hold, merged into the ones it keeps (nil forgets one)\n :values (let [vs (clean-values x)\n kept (reduce (fn [acc [k v]] (if (nil? v) (dissoc acc k) (assoc acc k v)))\n (clean-values (:values d)) vs)]\n (with-values d kept))\n ;; what :diff returns arrives as one [:batch [ev …]]\n :batch (if (sequential? x) (reduce step d (filter vector? x)) d)\n d))\n :load (fn [x] (with-values {:view (or (and (map? x) (clean (:view x))) default-view)}\n (when (map? x) (into (sorted-map) (remove (fn [[_ v]] (nil? v)) (clean-values (:values x)))))))\n :code (fn [id d] (cond-> [(str \"(code \" id \" \" (pr-str (pp (view-of d))) \")\")]\n (seq (:values d)) (conj (str \"(values! \" id \" \" (pr-str (clean-values (:values d))) \")\"))))\n :source (fn [d] (pp (view-of d)))\n :read (fn [_ text] {:view (read-view text)})\n :diff (fn [d d2] (if (= (view-of d) (:view d2)) [] [[:set (:view d2)]]))})\n\n(defn current-values\n \"The values a box shows: what its elements did since its data last changed, or else what its data keeps\n (the page forgets what they did when the data changes: going back in the history, someone else's change).\"\n [data state]\n (let [kept (clean-values (:values data))]\n (if (map? (:values state)) (merge kept (:values state)) kept)))\n\n(defn defaults-of\n \"The value each named element of a view starts with (its own :value).\"\n [h]\n (reduce (fn [acc x]\n (let [a (when (element? x) (second x))]\n (if (and (map? a) (:name a) (some? (:value a)) (not (hole? (:value a))) (not (contains? acc (:name a))))\n (assoc acc (:name a) (:value a))\n acc)))\n {} (tree-seq sequential? seq h)))\n\n(defn- set-values [vals m]\n (reduce (fn [acc [k v]] (if-let [k (value-name k)] (if (value-ok? v) (assoc acc k v) acc) acc)) vals m))\n\n(defn ui-message?\n \"What an element of the view sends its own box: [:ui outlet value name] (outlet or name may be nil).\"\n [v]\n (and (vector? v) (= 4 (count v)) (= :ui (first v))))\n\n(defn named-outlets\n \"The named elements of a view that send out of an outlet: name → [{:out o :min lo :max hi} …] (a slider's or a\n number field's own range, to keep a value within it).\"\n [h]\n (reduce (fn [acc x]\n (if (and (element? x) (map? (second x)) (:name (second x)) (some? (:out (second x))))\n (let [a (second x) num? (and (= :input (first x)) (#{\"range\" \"number\"} (:type a)))]\n (update acc (:name a) (fnil conj [])\n {:out (:out a) :min (when (and num? (number? (:min a))) (:min a))\n :max (when (and num? (number? (:max a))) (:max a))}))\n acc))\n {} (tree-seq sequential? seq h)))\n\n(defn- within [v {:keys [min max]}]\n (if (number? v) (cond-> v (number? min) (js/Math.max min) (number? max) (js/Math.min max)) v))\n\n(defn- sends-of\n \"What values that arrive on the inlet send on, as a knob does: each one out of the outlets of the elements\n named so (within their range), outlets in order.\"\n [view vals ks]\n (let [no (named-outlets view)]\n (vec (sort-by first (for [k ks :let [v (get vals k)] :when (some? v) t (get no k)] [(:out t) (within v t)])))))\n\n(defn receive [{:keys [value state data]}]\n (let [vals (current-values data state)\n view (view-of data)\n st (fn [vs] (assoc (or state {}) :values vs))\n ;; values from the inlet: set (a slider within its range), shown, and sent on (a knob does the same)\n arrive (fn [m]\n (let [no (named-outlets view)\n m (into {} (for [[k v] (set-values {} m)] [k (if-let [t (first (get no k))] (within v t) v)]))\n vals (merge vals m)]\n {:state (st vals) :show vals :out (sends-of view vals (keys m))}))]\n (cond\n (ui-message? value)\n (let [[_ o v nm] value\n vals (if-let [k (value-name nm)] (if (value-ok? v) (assoc vals k v) vals) vals)]\n {:state (st vals) :show vals\n :out (if (and (integer? o) (<= 0 o) (< o max-outlets)) [[o v]] [])})\n (map? value) (arrive value)\n (and (vector? value) (= 2 (count value)) (value-name (first value))) (arrive [value])\n ;; a bang sends again what every named element holds\n (= value :bang) {:show vals :out (sends-of view (merge (defaults-of view) vals) (keys (named-outlets view)))}\n ;; anything else (a number, a word, a list: the futuribles of a box) is the value :in, shown by :$in\n (some? value) (let [vals (assoc vals :in value)] {:state (st vals) :show vals})\n :else {:show vals})))\n\n(comp/define! \"html\"\n {:doc \"A small interface written as hiccup (HTML as EDN data): sliders, fields, menus, buttons and text, laid out like a page. An element with :out sends what it gives out of that outlet; one with :name keeps it as a value, shown by every hole :$name in the view, and when it is let go (a slider) or chosen (a menu, a text entered) the box keeps it in the work, as a knob keeps its value: (values! :bN {:freq 440}). A list of maps in a hole is shown as a table (a row each, a column for each key: the futuribles of comes or cancrizans), and anything else on the inlet that is not a map, a value or a bang (a number, a list) is the value :in, shown by :$in. A map on the inlet ({:freq 220}) sets values, as a number sets a knob: the elements named so show it (a slider within its range) and those with :out send it on; a bang sends again what they hold. What is not allowed (scripts, links, images, positions, unknown tags or attributes) is dropped, so it is safe in a shared room. Its view opens as text from { } (HTML can be pasted there too).\"\n :usage \"html\"\n :license \"MPL-2.0\"\n :display :html\n :model model\n :dynamic-io true\n :io (fn [box] [1 (outlets (view-of (:data box)))])\n :receive receive\n :help {:inlets [\"a map of values {:freq 220}, or one [:freq 220]: the elements named so and the holes :$freq show them, and the named elements with :out send them on (a slider within its range); a bang sends again what they hold\"]\n :outlets [\"what each element with :out 0 gives\" \"… :out 1, and so on: as many outlets as the view asks for\"]\n :messages [[\"{:freq 220}\" \"sets values: the elements named so show them and send them on\"] [\"[:freq 220]\" \"sets one value\"] [\"bang\" \"sends again what every named element with :out holds\"] [\"[{:name \\\"D4\\\" :futures 12} …]\" \"anything else is the value :in (:$in); a list of maps is shown as a table\"]]\n :example \"(box :b1 \\\"html\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 230)\\n(box :b3 \\\"print\\\" 200 230)\\n(connect :b1 0 :b2 0)\\n(connect :b1 1 :b3 0)\"\n :try \"Move the slider: its value goes out of the left outlet and shows beside it; let it go and the box keeps it, as a knob does (back in the history, it moves back). { } in the header opens the view as text: change it and apply.\"\n :see [\"number\" \"knob\" \"msg\"]}})\n\n;; ───────── drawing it (in the browser) ─────────\n;; build returns {:node el :live [[el kind key default] …] :binds [{:out :send :name :type} …] :defaults {name value}}:\n;; the holes and the named elements to update when the values change, what each element with :out or :name\n;; sends, and the value each named element starts with (its own :value).\n\n(def base-css\n (str \":host{display:block;width:100%;height:100%;overflow:auto;box-sizing:border-box;padding:6px 8px;\"\n \"font:12px/1.4 var(--f-ui, sans-serif);color:var(--ink);user-select:text;-webkit-user-select:text;touch-action:manipulation;}\"\n \"*{box-sizing:border-box;}\"\n \".row{display:flex;flex-direction:row;flex-wrap:wrap;align-items:center;gap:6px;}\"\n \".col{display:flex;flex-direction:column;gap:6px;}\"\n \".grid{display:grid;grid-template-columns:auto 1fr;gap:4px 8px;align-items:center;}\"\n \".soft{color:var(--ink-soft);}.accent{color:var(--accent);}.kairos{color:var(--kairos);}\"\n \"h1,h2,h3,h4{font-family:var(--f-head, sans-serif);margin:0 0 4px;font-weight:600;}\"\n \"h1{font-size:18px;}h2{font-size:15px;}h3{font-size:13px;}h4{font-size:12px;}\"\n \"p{margin:0 0 4px;}ul,ol{margin:0;padding-left:18px;}code,pre{font-family:var(--f-code, monospace);font-size:11px;}\"\n \"input,select,textarea,button{font:inherit;color:var(--ink);accent-color:var(--accent);}\"\n \"input[type=text],input[type=number],select,textarea{background:var(--box);border:1px solid var(--rule);border-radius:3px;padding:2px 4px;}\"\n \"input[type=range]{vertical-align:middle;}\"\n \"button{background:color-mix(in srgb, var(--accent) 12%, var(--box));border:1px solid var(--rule);border-radius:3px;padding:2px 10px;cursor:pointer;}\"\n \"button:active{background:var(--accent-soft);}\"\n \"table{border-collapse:collapse;}td,th{padding:2px 6px;border-bottom:1px solid var(--grid);text-align:left;}\"\n \"output{font-family:var(--f-code, monospace);}\"))\n\n(defn shown-str [v]\n (cond (nil? v) \"\" (string? v) v (keyword? v) (name v)\n (number? v) (str (if (integer? v) v (/ (js/Math.round (* v 1000)) 1000))) :else (pr-str v)))\n\n(defn- set-prop!\n \"An attribute (or the property that shows it) on el.\"\n [el tag k v]\n (cond\n (flag-attrs k) (let [on (boolean (if (number? v) (pos? v) v))]\n (case k\n :checked (set! (.-checked el) on)\n :selected (set! (.-selected el) on)\n (if on (.setAttribute el (name k) \"\") (.removeAttribute el (name k)))))\n (and (= k :value) (#{:input :textarea :select :meter :progress} tag)) (set! (.-value el) (shown-str v))\n :else (.setAttribute el (name k) (shown-str v))))\n\n(defn build\n \"The DOM of a safe view, with the values in `vals` (a map keyword → value).\"\n [h vals]\n (let [live (atom []) binds (atom []) defaults (atom {})\n mk (fn mk [x]\n (cond\n (string? x) (js/document.createTextNode x)\n (hole? x) (let [t (js/document.createTextNode (shown-str (get vals (hole-key x))))]\n (swap! live conj [t :text (hole-key x) nil]) t)\n (element? x)\n (let [[tag & more] x\n [attrs kids] (if (map? (first more)) [(first more) (rest more)] [{} more])\n el (js/document.createElement (name tag))\n nm (:name attrs)]\n ;; its type first and its value last (a slider's value is kept within its min and max)\n (doseq [[k v] (sort-by (fn [[k]] (case k :type 0 :value 2 1)) attrs)\n :when (not (#{:out :send :name :style} k))]\n (if (hole? v)\n (do (set-prop! el tag k (get vals (hole-key v))) (swap! live conj [el [:attr tag k] (hole-key v) nil]))\n (set-prop! el tag k v)))\n (when-let [st (:style attrs)]\n (doseq [[k v] st :let [s (css-value k v)] :when s] (.setProperty (.-style el) (name k) s)))\n (when nm (.setAttribute el \"name\" (name nm)))\n (when (or (some? (:out attrs)) nm)\n (set! (.. el -dataset -k) (str (count @binds)))\n (swap! binds conj {:out (:out attrs) :send (:send attrs) :name nm :tag tag :type (:type attrs)}))\n ;; a named element shows the value of its name (its own :value until it has one)\n (when (and nm (#{:input :select :textarea :meter :progress :output} tag))\n (when (and (some? (:value attrs)) (not (hole? (:value attrs))) (not (contains? @defaults nm)))\n (swap! defaults assoc nm (:value attrs)))\n (swap! live conj [el [:control tag (:type attrs)] nm (:value attrs)]))\n (doseq [k kids :let [c (mk k)] :when c] (.appendChild el c))\n ;; a menu chooses its value once its options are in it\n (when (and (= tag :select) (some? (:value attrs)) (not (hole? (:value attrs))))\n (set! (.-value el) (shown-str (:value attrs))))\n el)\n :else nil))\n node (mk h)]\n {:node node :live @live :binds @binds :defaults @defaults}))\n\n(defn- number-or [s]\n (let [n (js/parseFloat s)] (if (and (js/isFinite n) (re-matches #\"\\s*-?\\d*\\.?\\d+(e-?\\d+)?\\s*\" (str s))) n s)))\n\n(defn rows?\n \"Is v a list of maps (shown as a table: a row each, a column for each key)?\"\n [v]\n (and (sequential? v) (seq v) (every? map? v)))\n\n(defn- table-of\n \"A table for a list of maps: the keys of the first in order, then any others, as the head.\"\n [v]\n (let [ks (distinct (mapcat keys v))\n tbl (js/document.createElement \"table\")\n tr (fn [cells tag] (let [r (js/document.createElement \"tr\")]\n (doseq [c cells] (let [e (js/document.createElement tag)] (set! (.-textContent e) c) (.appendChild r e)))\n r))]\n (.appendChild tbl (tr (map name ks) \"th\"))\n (doseq [m v] (.appendChild tbl (tr (map #(shown-str (get m %)) ks) \"td\")))\n tbl))\n\n(defn- show-hole!\n \"A hole (a text node) showing v: as text, or a list of maps as a table beside it.\"\n [el v]\n (let [old (aget el \"kTable\")]\n (if (rows? v)\n (let [t (table-of v)]\n (when (not= \"\" (.-textContent el)) (set! (.-textContent el) \"\"))\n (if (and old (.-parentNode old)) (.replaceWith old t) (when-let [p (.-parentNode el)] (.insertBefore p t (.-nextSibling el))))\n (aset el \"kTable\" t))\n (let [s (if (and (sequential? v) (empty? v)) \"\" (shown-str v))]\n (when old (.remove old) (aset el \"kTable\" nil))\n (when (not= s (.-textContent el)) (set! (.-textContent el) s))))))\n\n(defn refresh!\n \"Shows the values `vals` in a built view; `skip` is an element being used (its value is not touched).\"\n [{:keys [live]} vals skip]\n (doseq [[el kind k dflt] live :let [has? (contains? vals k) v (get vals k)]]\n (cond\n (= kind :text) (show-hole! el v)\n (= (first kind) :attr) (let [[_ tag a] kind] (set-prop! el tag a v))\n (= (first kind) :control)\n (when (and has? (not (identical? el skip)))\n (let [[_ tag typ] kind]\n (cond\n (= typ \"checkbox\") (set! (.-checked el) (boolean (if (number? v) (pos? v) v)))\n (= typ \"radio\") (set! (.-checked el) (= (shown-str v) (.-value el)))\n (= tag :output) (set! (.-textContent el) (shown-str v))\n :else (let [s (shown-str v)] (when (not= s (.-value el)) (set! (.-value el) s)))))))))\n\n(defn element-value\n \"What an element with :out or :name gives when it is used: [value commit?] for this event, or nil.\"\n [el bind ev-type]\n (let [{:keys [tag type send]} bind]\n (case tag\n :button (when (= ev-type \"click\") [(if (some? send) send :bang) true])\n :input (case type\n \"checkbox\" (when (= ev-type \"change\") [(if (some? send) (if (.-checked el) send 0) (if (.-checked el) 1 0)) true])\n \"radio\" (when (and (= ev-type \"change\") (.-checked el)) [(number-or (.-value el)) true])\n (\"range\" \"number\") (let [n (js/parseFloat (.-value el))]\n (when (js/isFinite n) (case ev-type \"input\" [n false] \"change\" [n true] nil)))\n \"color\" (case ev-type \"input\" [(.-value el) false] \"change\" [(.-value el) true] nil)\n ;; text: on Enter or when it is left\n (when (= ev-type \"change\") [(.-value el) true]))\n :select (when (= ev-type \"change\") [(number-or (.-value el)) true])\n :textarea (when (= ev-type \"change\") [(.-value el) true])\n nil)))\n","kairotic/input.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · input\n;; Sound from outside, and sound back into messages and pictures.\n;;\n;; adc~ [channel …] audio input (the microphone or the sound card): one outlet per channel\n;; written after it (adc~ 1 by default). Asks for the microphone at ▶.\n;; snapshot~ [ms] [rms|peak|db]\n;; a signal as numbers, every ms (50 by default): its value, or its level\n;; (rms, peak, or rms in dB). Sends only what changed.\n;; scope~ [ms] [zoom] an oscilloscope in the patch: the last ms (20) of the signal, steady on a\n;; rising zero crossing; drag up/down to zoom, sideways for the time.\n;;\n;; The audio nodes cannot send messages: they report what they find to their own box (api/report!),\n;; which receives it on inlet :audio and decides what to send, show and keep, in its pure :receive.\n;; The loops over samples run in an AudioWorklet (api/tap): the page only handles small arrays.\n\n(ns kairotic.input\n (:require [clojure.string :as str]\n [kairotic.components :as comp]\n [kairotic.api :as api]))\n\n;; ───────── the microphone: one stream for every adc~ ─────────\n\n(defn adc-channels\n \"The input channels of an adc~ (1-based): its numbers, or 1.\"\n [b] (let [cs (filterv (fn [x] (and (number? x) (>= x 1))) (:args b))] (if (seq cs) (mapv js/Math.floor cs) [1])))\n\n(def max-channels 32)\n\n;; {:ac :p (Promise of {:stream :source :split :have}) :users n :closing timeout}\n(defonce mic (atom nil))\n\n(defn constraints\n \"What is asked of the microphone: its sound as it is (no echo cancellation, noise suppression or\n automatic gain, which are made for speech and change music), with as many channels as it has.\"\n [n]\n (clj->js {:audio {:channelCount {:ideal (max 2 n)}\n :echoCancellation false :noiseSuppression false :autoGainControl false}}))\n\n(defn close! [m]\n (.then (:p m)\n (fn [{:keys [stream source split]}]\n (try (.disconnect source) (.disconnect split) (catch :default _ nil))\n (doseq [t (array-seq (.getTracks stream))] (.stop t)))\n (fn [_] nil)))\n\n(defn open!\n \"Promise of the shared input ({:stream :source :split :have}) in AudioContext ac, opened the first\n time an adc~ asks (asking for the microphone) and shared by every adc~ after.\"\n [ac n]\n (let [m @mic]\n (if (and m (identical? (:ac m) ac))\n (do (when-let [t (:closing m)] (js/clearTimeout t))\n (swap! mic (fn [m] (-> m (update :users inc) (dissoc :closing))))\n (:p m))\n (let [md (.-mediaDevices js/navigator)\n p (if-not (and md (.-getUserMedia md))\n (js/Promise.reject (js/Error. \"this page cannot use a microphone (it needs https or localhost)\"))\n (.then (.getUserMedia md (constraints n))\n (fn [stream]\n (let [source (.createMediaStreamSource ac stream)\n split (.createChannelSplitter ac max-channels)\n track (first (array-seq (.getAudioTracks stream)))\n have (when track (.-channelCount (.getSettings track)))]\n (.connect source split)\n {:stream stream :source source :split split :have have}))))]\n (when m (close! m))\n ;; a refusal is not kept: the next ▶ asks again\n (.catch p (fn [_] (when (identical? (:p @mic) p) (reset! mic nil))))\n (reset! mic {:ac ac :p p :users 1})\n p))))\n\n(defn release!\n \"An adc~ no longer listens. When none does, the microphone is closed a moment later (an adc~ rebuilt\n because its text changed takes it again in between, without asking).\"\n []\n (when-let [m @mic]\n (if (> (:users m) 1)\n (swap! mic update :users dec)\n (swap! mic assoc :users 0\n :closing (js/setTimeout (fn [] (let [m @mic]\n (when (and m (zero? (:users m)))\n (reset! mic nil)\n (close! m))))\n 2000)))))\n\n(defn report-error [e] {:error (str \"adc~: \" (or (.-message e) e))})\n\n(comp/define! \"adc~\"\n {:doc \"Audio input (the microphone or the sound card): one outlet per input channel, the ones written after it (adc~ 1 by default; adc~ 1 2 for stereo). At ▶ it asks for the microphone, and takes its sound as it is, without the echo cancellation, noise suppression and automatic gain made for speech. Every adc~ shares one stream.\"\n :usage \"adc~ [channel …]\"\n :license \"MPL-2.0\"\n :io (fn [b] [0 (count (adc-channels b))]) :dynamic-io true\n :receive (fn [{:keys [inlet value]}]\n (if (and (= inlet :audio) (map? value) (:error value))\n {:effects [[:print (:error value)]]}\n {}))\n :audio {:create (fn [ac b _]\n (let [cs (adc-channels b)\n outs (vec (for [_ cs] (.createGain ac)))\n alive (atom true)\n node {:outs outs :alive alive :outlets (vec (for [g outs] [g 0]))}]\n (-> (open! ac (apply max cs))\n (.then (fn [{:keys [split have]}]\n (when @alive\n (doseq [[c g] (map vector cs outs) :when (<= c max-channels)]\n (.connect split g (dec c)))\n (when-let [missing (seq (filter (fn [c] (and (number? have) (> c have))) cs))]\n (api/report! (:id b) {:error (str \"adc~: the input has \" have \" channel\"\n (when (not= 1 have) \"s\") \": channel \"\n (str/join \" \" missing) \" is silent\")}\n nil)))))\n (.catch (fn [e] (when @alive (api/report! (:id b) (report-error e) nil)))))\n node))\n :key (fn [b] (adc-channels b))\n :dispose (fn [node]\n (reset! (:alive node) false)\n (doseq [g (:outs node)] (try (.disconnect g) (catch :default _ nil)))\n (release!))}})\n\n;; ───────── snapshot~: a signal as numbers ─────────\n\n(def snapshot-modes #{:rms :peak :db})\n\n(defn snapshot-value\n \"The number a snapshot~ sends for a block [last rms peak] of the tap.\"\n [mode [last rms peak]]\n (case mode\n :rms rms\n :peak peak\n :db (comp/nice (api/db rms))\n last))\n\n(defn level-unit\n \"Where a value of a snapshot~ stands on its bar (0…1): levels as they are, dB from -60 to 0.\"\n [mode v]\n (when (number? v)\n (case mode\n (:rms :peak) (comp/clamp v 0 1)\n :db (comp/clamp (/ (+ v 60) 60) 0 1)\n nil)))\n\n(defn snapshot-ms [x] (comp/clamp (or (comp/num-of x) 50) 5 10000))\n\n(comp/define! \"snapshot~\"\n {:doc \"A signal as numbers: every ms (50 by default) its last value, or with a word its level over that time — rms, peak, or db (the rms in decibels). It sends only what changed, so a constant signal sends once. A number on the left changes ms; a bang sends the last value again. With adc~ it is a level meter; with phasor~, an envelope or faust~ it brings a signal back into the messages.\"\n :usage \"snapshot~ [ms] [rms|peak|db]\"\n :license \"MPL-2.0\"\n :io [1 1]\n :size [104 30]\n :args [[:ms 50] [:mode nil]]\n :receive (fn [{:keys [inlet value state args]}]\n (let [mode (snapshot-modes (:mode args))]\n (cond\n (= inlet :audio)\n (let [block (first value)\n v (when block (snapshot-value mode (vec (array-seq block))))]\n (if (and (number? v) (not= v state))\n {:state v :show v :out [[0 v]]}\n {}))\n (= value :bang) (if (number? state) {:out [[0 state]] :show state} {})\n (comp/num-of value) {:effects [[:ms (snapshot-ms value)]]}\n :else {})))\n :derive (fn [{:keys [shown args]}]\n (let [mode (snapshot-modes (:mode args)) u (level-unit mode shown)]\n {:label (str (if (number? shown) (comp/nice shown) \"–\") (when (= mode :db) \" dB\"))\n :bar (if u (* 96 u) 0)\n :tag (if mode (name mode) \"value\")}))\n :view [[:rect {:x 2 :y 2 :w 100 :h 26 :r 3 :stroke :grid :fill :bg}]\n [:rect {:x 4 :y 22 :w :$bar :h 4 :r 1 :stroke nil :fill :accent}]\n [:text {:x 6 :y 16 :size 11} :$label]\n [:text {:x 98 :y 16 :anchor :end :size 8 :fill :soft} :$tag]]\n :audio {:create (fn [ac b _]\n (let [in (.createGain ac)\n args (comp/args-for (comp/lookup \"snapshot~\") (:text b))\n hop (fn [ms] (js/Math.max 16 (js/Math.round (* (.-sampleRate ac) (/ ms 1000)))))\n ms (snapshot-ms (:ms args))\n node {:in in :hop hop :tap (atom nil) :alive (atom true) :inlets [[in 0]] :outlets []}]\n (-> (api/tap ac {:mode :summary :size (hop ms) :hop (hop ms)}\n (fn [data at & _] (when @(:alive node) (api/report! (:id b) data at))))\n (.then (fn [w] (if @(:alive node) (do (.connect in w) (reset! (:tap node) w))\n (try (.disconnect w) (catch :default _ nil)))))\n (.catch (fn [e] (js/console.error \"snapshot~\" e))))\n node))\n :update (fn [node b _]\n (when-let [w @(:tap node)]\n (let [h ((:hop node) (snapshot-ms (:ms (comp/args-for (comp/lookup \"snapshot~\") (:text b)))))]\n (api/retap w {:size h :hop h}))))\n :effects {:ms (fn [node ms _]\n (when-let [w @(:tap node)] (let [h ((:hop node) ms)] (api/retap w {:size h :hop h}))))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n (api/untap @(:tap node))\n (try (.disconnect (:in node)) (catch :default _ nil)))}})\n\n;; ───────── scope~: an oscilloscope ─────────\n\n(def scope-w 168)\n(def scope-h 84)\n(def scope-columns 160) ; one [min max] pair per pixel of the trace (x from 4 to 164)\n\n(defn scope-ms [x] (comp/clamp (or (comp/num-of x) 20) 1 2000))\n(defn scope-zoom [x] (comp/clamp (or (comp/num-of x) 1) 0.125 64))\n\n(defn trace-points\n \"The polyline of a trace: columns pairs [min max] (a Float32Array or a seq) as points from x 4 to 164,\n around the middle line, `zoom` times taller (clipped to the box).\"\n [col zoom]\n (let [xs (vec (array-seq col)) k (quot (count xs) 2)\n mid (/ scope-h 2) half (- mid 6)\n y (fn [v] (comp/clamp (- mid (* v zoom half)) 4 (- scope-h 4)))]\n (when (pos? k)\n (vec (for [i (range k) j [0 1]]\n [(+ 4 (* (- scope-w 8) (/ i (max 1 (dec k))))) (y (nth xs (+ (* 2 i) j)))])))))\n\n(defn scope-view [m]\n (let [{:keys [ms zoom]} (merge (:args m) (when (map? (:state m)) (:state m)))]\n {:ms (scope-ms ms) :zoom (scope-zoom zoom)}))\n\n(comp/define! \"scope~\"\n {:doc \"An oscilloscope in the patch: the last ms (20 by default) of the signal on its left, drawn from a rising zero crossing so a periodic wave stands still. zoom makes it taller. Drag up or down over it to zoom (⇧ finer) and sideways to change the time; on release both stay in the box text. A number on the left changes ms.\"\n :usage \"scope~ [ms] [zoom]\"\n :license \"MPL-2.0\"\n :io [1 0]\n :size [168 84]\n :args [[:ms 20] [:zoom 1]]\n :persist (fn [{:keys [ms zoom]}] {:ms (comp/nice ms) :zoom (comp/nice zoom)})\n :receive (fn [{:keys [inlet value] :as m}]\n (let [{:keys [ms zoom] :as v} (scope-view m)]\n (cond\n (= inlet :audio) {:show (assoc v :pts (trace-points (first value) zoom))}\n (and (map? value) (contains? value :zoom))\n (let [nv {:ms (scope-ms (:ms value)) :zoom (scope-zoom (:zoom value))}]\n {:state nv :effects [[:ms (:ms nv)]]})\n (comp/num-of value) (let [nv (assoc v :ms (scope-ms value))] {:state nv :effects [[:ms (:ms nv)]]})\n :else {})))\n ;; from what it showed on press (or its text): not from its state, which the drag itself changes\n :gesture (fn [{:keys [start dx dy fine] :as m}]\n (let [{:keys [ms zoom]} (if (and (map? start) (:ms start)) start (scope-view (dissoc m :state)))\n k (if fine 4 1)]\n {:ms (scope-ms (* ms (js/Math.pow 2 (/ dx (* 40 k)))))\n :zoom (scope-zoom (* zoom (js/Math.pow 2 (/ (- dy) (* 40 k)))))}))\n :derive (fn [{:keys [shown] :as m}]\n (let [{:keys [ms zoom]} (scope-view m)]\n {:pts (when (map? shown) (:pts shown))\n :label (str (comp/nice ms) \" ms\" (when (not= zoom 1) (str \" · ×\" (comp/nice zoom))))}))\n :view [[:rect {:x 2 :y 2 :w 164 :h 80 :r 4 :stroke :grid :fill :bg}]\n [:line {:x1 4 :y1 42 :x2 164 :y2 42 :stroke :grid}]\n [:path {:points :$pts :stroke :accent :weight 1}]\n [:text {:x 162 :y 78 :anchor :end :size 8 :fill :soft} :$label]]\n :audio {:create (fn [ac b _]\n (let [in (.createGain ac)\n sr (.-sampleRate ac)\n samples (fn [ms] (js/Math.max 32 (js/Math.round (* sr (/ ms 1000)))))\n ms (scope-ms (:ms (comp/args-for (comp/lookup \"scope~\") (:text b))))\n node {:in in :samples samples :tap (atom nil) :alive (atom true) :inlets [[in 0]] :outlets []}]\n ;; about 30 pictures a second\n (-> (api/tap ac {:mode :trace :size (samples ms) :hop (js/Math.round (/ sr 30)) :columns scope-columns}\n (fn [data at & _] (when @(:alive node) (api/report! (:id b) data at))))\n (.then (fn [w] (if @(:alive node) (do (.connect in w) (reset! (:tap node) w))\n (try (.disconnect w) (catch :default _ nil)))))\n (.catch (fn [e] (js/console.error \"scope~\" e))))\n node))\n :update (fn [node b _]\n (when-let [w @(:tap node)]\n (api/retap w {:size ((:samples node) (scope-ms (:ms (comp/args-for (comp/lookup \"scope~\") (:text b)))))})))\n :effects {:ms (fn [node ms _] (when-let [w @(:tap node)] (api/retap w {:size ((:samples node) ms)})))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n (api/untap @(:tap node))\n (try (.disconnect (:in node)) (catch :default _ nil)))}})\n","kairotic/library.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · library\n;; Components that do not come from the core. Three levels, with the same format:\n;; 1. in the work: a `component` box whose source is the definition; it travels with the work and its history\n;; 2. shared: this space's library (the artifact's database), to use in other works\n;; 3. published: an npm package served by jsDelivr, pinned by version\n;; Whatever is used from 2 and 3 is copied into a `component` box of the work: so every work is complete,\n;; works offline and sounds the same even if the library changes later.\n;;\n;; Format of a published component (an .mjs module):\n;; export default { class: \"drift\", version: \"1.0.0\", author: \"…\", license: \"MPL-2.0\", doc: \"…\",\n;; source: `{:class \"drift\" :io [1 1] :receive (fn [m] …)}` };\n;;\n;; A package (Study 14) is several components published together, and travels as ONE component box:\n;; export default { package: \"@kairotic/synth\", version: \"0.1.0\", api: 1, license: \"MPL-2.0\",\n;; components: [{class: \"adsr~\", doc: \"…\", source: \"…\"}, …] };\n;; and its box holds {:package \"@kairotic/synth\" :version \"0.1.0\" :api 1 :components [<source> …]}.\n;; Writing a class that a known package defines (see `packages`) brings that package into the work.\n\n(ns kairotic.library\n (:require [clojure.string :as str]\n [kairotic.api :as api]\n [kairotic.components :as comp]\n [kairotic.code :as code]))\n\n(def template\n \"{:class \\\"echo-msg\\\"\n :doc \\\"Returns what it receives (change it to anything).\\\"\n :io [1 1]\n :receive (fn [{:keys [inlet value state args at]}]\n ;; return {:out [[outlet value]] :state … :later [[at inlet value]]}\n {:out [[0 value]]})}\")\n\n(declare validate)\n\n(defn validate-package\n \"nil if a package map is valid; otherwise, the reason.\"\n [m]\n (cond\n (not (string? (:package m))) \"a package has :package \\\"@scope/name\\\"\"\n (not (sequential? (:components m))) \"a package has :components [definition …]\"\n (and (:api m) (> (:api m) api/version)) (str (:package m) \" needs the Kairotic API \" (:api m) \" (this one is \" api/version \")\")\n :else (some (fn [c] (when-let [r (validate c)] (str (or (:class c) \"a component\") \": \" r))) (:components m))))\n\n(defn package? [m] (and (map? m) (contains? m :package)))\n\n(defn definitions\n \"The component definitions in what a component box evaluates to: one, or those of a package\n (each marked with :package and :version).\"\n [m]\n (if (package? m)\n (for [c (:components m)] (assoc c :package (:package m) :version (:version m)))\n [m]))\n\n(defn validate\n \"nil if the definition is valid; otherwise, the reason.\"\n [m]\n (cond\n (package? m) (validate-package m)\n (not (map? m)) \"a component's source is a map {:class … :receive …}\"\n (not (and (string? (:class m)) (re-matches #\"[^\\s()\\[\\]{}\\\"]+\" (:class m)))) \"missing :class (one word, e.g. \\\"fifth\\\")\"\n (= :core (:origin (comp/lookup (:class m)))) (str \"«\" (:class m) \"» is a core class; use another name\")\n (not (or (fn? (:receive m)) (map? (:audio m)) (map? (:patch m)))) \"missing :receive (fn [m] …), :audio or :patch\"\n (and (contains? m :tasks) (not (and (map? (:tasks m)) (every? keyword? (keys (:tasks m))) (every? fn? (vals (:tasks m))))))\n \":tasks is a map {:name (fn [x box] promise)}\"\n (and (contains? m :tasks) (not (fn? (:receive m)))) \"a component with :tasks needs a :receive to ask for them and get what they find\"\n (some #{:print :keep :tree-edit :tree-set :canvas-edit :presets :sample} (keys (:tasks m)))\n \"a task cannot be called :print, :keep or another effect of the page\"\n (and (contains? m :patch) (not (and (map? (:patch m)) (map? (:boxes (:patch m))))))\n \":patch is a patch {:boxes {…} :lines […]}\"\n (and (contains? m :io) (not (or (fn? (:io m)) (and (vector? (:io m)) (= 2 (count (:io m))) (every? number? (:io m))))))\n \":io is [inlets outlets] or a function\"\n :else nil))\n\n;; the language of component boxes: ClojureScript that evaluates to a definition map\n(code/register-language! \"component\"\n (fn [source]\n (js/Promise.\n (fn [res rej]\n (if-not (code/allowed? source)\n (rej (js/Error. \"not run: this work is shared; (trust-scripts true) to evaluate its components\"))\n (try\n (let [m (js/scittle.core.eval_string (str \"(do \" source \"\\n)\"))]\n (if-let [reason (validate m)]\n (rej (js/Error. reason))\n (if (package? m)\n (res {:value m\n :info {:class (:package m)\n :summary (str (:package m) \" \" (:version m) \" · \"\n (str/join \", \" (map :class (:components m))))}})\n (let [io (:io m)]\n (res {:value m\n :info {:class (:class m)\n :summary (str \"defines «\" (:class m) \"»\"\n (when (vector? io) (str \" · \" (first io) \" in · \" (second io) \" out\")))}})))))\n (catch :default e (rej e))))))))\n\n(comp/define! \"component\"\n {:doc \"Defines a box class inside the work: its source is a map {:class :doc :io :receive …} with the same contract as any component.\"\n :usage \"component\"\n :display :code :language \"component\" :model code/model :template template\n :io [0 0]})\n\n;; ───────── the registry follows the work's definitions ─────────\n\n(defonce work-classes (atom {})) ; class → [box-id definition]\n\n(defn box-num [k] (let [m (re-matches #\"b(\\d+)\" (name k))] (if m (js/parseInt (second m) 10) 1e9)))\n\n(defn sync!\n \"Registers the classes defined by the patch's component boxes (the lowest-numbered one wins if two\n define the same) and removes those no longer there. Returns true if the registry changed.\"\n [patch]\n (let [defs (for [[id b] (sort-by (fn [[k _]] (box-num k)) (:boxes patch))\n :when (= \"component\" (comp/klass (:text b)))\n :let [r (code/compiled \"component\" (get-in b [:data :source]))]\n :when (= :ok (:status r))\n m (definitions (:value r))]\n [(:class m) [id m]])\n fresh (reduce (fn [acc [c v]] (if (contains? acc c) acc (assoc acc c v))) {} defs)\n before @work-classes]\n (when (not= fresh before)\n (doseq [[c _] before :when (not (contains? fresh c))]\n (when (= :work (:origin (comp/lookup c))) (swap! comp/registry dissoc c)))\n (doseq [[c [id m]] fresh :when (not= (get before c) [id m])]\n (when-not (= :core (:origin (comp/lookup c)))\n (comp/define! c (merge (dissoc m :class) {:origin :work :from id}))))\n (reset! work-classes fresh)\n true)))\n\n;; ───────── import ─────────\n\n(defn url-of\n \"npm:package@version/path → jsDelivr; a relative path is a file of this page.\"\n [s]\n (let [s (str/trim (str s))]\n (cond\n (str/starts-with? s \"npm:\") (str \"https://cdn.jsdelivr.net/npm/\" (subs s 4))\n :else s)))\n\n(defn header [{cls :class :keys [version author license]} origin]\n (str \";; \" cls (when version (str \" \" version)) (when author (str \" · \" author))\n (when (seq license) (str \" · license \" license)) \"\\n;; imported from \" origin \"\\n\"))\n\n(defn import-module\n \"Promise of the component published at `origin`: {:class :version :author :doc :source}, or of the\n package: {:package :version :api :components [{:class :source …}]}.\"\n [origin]\n (-> ((.-kairoticImport js/window) (url-of origin))\n (.then (fn [obj]\n (let [m (js->clj obj :keywordize-keys true)]\n (when-not (and (map? m) (or (string? (:source m))\n (and (string? (:package m)) (sequential? (:components m)))))\n (throw (js/Error. \"that module does not export a component {class, source, …} nor a package {package, components, …}\")))\n m)))))\n\n(defn package-source\n \"The source of the component box that carries a package: one map with every component's source.\"\n [{:keys [package version api license components]} origin]\n (str \";; \" package \" \" version (when (seq license) (str \" · license \" license)) \"\\n\"\n \";; imported from \" origin \"\\n\"\n \"{:package \" (pr-str package) \" :version \" (pr-str version) (when api (str \" :api \" api)) \"\\n\"\n \" :components\\n [\"\n (str/join \"\\n\\n \" (map (fn [c] (str/trim (:source c))) components))\n \"]}\\n\"))\n\n;; ───────── official packages ─────────\n;; Where each official package is, and which classes it defines: writing one of these classes in a\n;; work that does not have it brings the package into the work (pinned to this version). Until a\n;; version is on npm, the page serves its own copy (:local).\n\n(def packages\n {\"@kairotic/synth\" {:version \"0.3.0\" :classes #{\"adsr~\" \"synth~\" \"gendy~\"} :local \"kairotic/packages/synth.mjs\"}\n \"@kairotic/spatial\" {:version \"0.1.1\" :classes #{\"pan~\" \"space~\"} :local \"kairotic/packages/spatial.mjs\"}\n \"@kairotic/controls\" {:version \"0.2.3\" :classes #{\"knob\" \"keyboard\" \"scale\"} :local \"kairotic/packages/controls.mjs\"}\n \"@kairotic/analysis\" {:version \"0.7.5\" :classes #{\"features~\" \"pitch~\" \"onset~\" \"chroma~\" \"spectrum~\" \"transcribe\" \"monitor\" \"form~\" \"realize~\"}\n :local \"kairotic/packages/analysis.mjs\"}\n \"@kairotic/theory\" {:version \"0.11.0\" :classes #{\"pcclock\" \"fourier\" \"tonnetz\" \"comes\" \"cancrizans\" \"euclid\"} :local \"kairotic/packages/theory.mjs\"}\n \"@kairotic/data\" {:version \"0.1.4\" :classes #{\"fetch\" \"edn\"} :local \"kairotic/packages/data.mjs\"}\n \"@kairotic/patterns\" {:version \"0.2.1\" :classes #{\"pbind\" \"pattern\" \"player\" \"render\"} :local \"kairotic/packages/patterns.mjs\"}\n \"@kairotic/spectral\" {:version \"0.1.2\" :classes #{\"shift~\"} :local \"kairotic/packages/spectral.mjs\"}\n \"@kairotic/io\" {:version \"0.2.4\" :classes #{\"midiin\" \"midiout\" \"oscin\" \"oscout\" \"motion\" \"gamepad\" \"serial\" \"control\"}\n :local \"kairotic/packages/io.mjs\"}\n \"@kairotic/net\" {:version \"0.1.3\" :classes #{\"share\" \"shared\" \"pulse\"} :local \"kairotic/packages/net.mjs\"}})\n\n;; Official packages that carry modules for the page itself rather than box classes (nothing to bring into\n;; a work): where their files are, npm first at the pinned version, then the page's own copy.\n(def module-packages\n {\"@kairotic/faust-units\" {:version \"0.1.5\" :local \"kairotic/packages/faust-units/\"}})\n\n(defn module-origins\n \"Where file `f` of a module package is, in order: npm (pinned version), then the page's own copy.\"\n [pkg-name f]\n (let [{:keys [version local]} (get module-packages pkg-name)]\n [(str \"npm:\" pkg-name \"@\" version \"/dist/\" f) (str local f)]))\n\n(defn package-of\n \"The official package that defines class k: [name info], or nil.\"\n [k]\n (first (filter (fn [[_ p]] (contains? (:classes p) k)) packages)))\n\n(defn package-origins\n \"Where to look for a package, in order: npm (pinned version), then the page's own copy.\"\n [pkg-name]\n (let [{:keys [version local]} (get packages pkg-name)]\n (cond-> [(str \"npm:\" pkg-name \"@\" version \"/dist/index.mjs\")] local (conj local))))\n\n(defn import-package\n \"Promise of [package origin]: the first of its origins that answers.\"\n [pkg-name]\n (reduce (fn [p origin]\n (.catch p (fn [_] (.then (import-module origin) (fn [m] [m origin])))))\n (js/Promise.reject (js/Error. \"no origin\"))\n (package-origins pkg-name)))\n","kairotic/links.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · links that carry a patch (Study 22)\n;; A link (?code=…, ?src=…) and a patch Claude makes (Study 23) carry the patch as code. That code is\n;; read as data (EDN: reading evaluates nothing) and only the calls a patch is made of go through, with\n;; literal arguments, so a link cannot run code in the page. What goes through is written again and\n;; evaluated by the page as gestures.\n\n(ns kairotic.links\n (:require [clojure.string :as str]\n [clojure.edn :as edn]))\n\n(def calls\n \"The calls a patch is made of.\"\n '#{box connect present view resize code stroke axis grid-x grid-y tuning tree! presets! sample! inside layer mark project})\n\n(defn literal?\n \"Plain data all the way down: numbers, strings, keywords, booleans, nil, vectors, maps, sets.\"\n [x]\n (cond (or (symbol? x) (seq? x)) false\n (map? x) (every? (fn [[k v]] (and (literal? k) (literal? v))) x)\n (coll? x) (every? literal? x)\n :else true))\n\n(defn call?\n \"Whether a form is a patch call with literal arguments (`inside` holds patch calls).\"\n [f]\n (and (seq? f) (contains? calls (first f))\n (if (= 'inside (first f))\n (and (keyword? (second f)) (every? call? (drop 2 f)))\n (every? literal? (rest f)))))\n\n(defn read-code\n \"The code of a link, read as data and written again with only the calls a patch is made of. Throws if\n anything else is in it.\"\n [src]\n (let [forms (edn/read-string (str \"[\" src \"\\n]\"))\n bad (first (remove call? forms))]\n (when bad\n (throw (js/Error. (str \"a link can only make a patch; it cannot run \"\n (let [t (pr-str bad)] (if (> (count t) 60) (str (subs t 0 60) \"…\") t))))))\n (str/join \"\\n\" (map pr-str forms))))\n","kairotic/mt.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · mt (musical time)\n;; Musical-temporal data as EDN trees, in the hiccup style: [:tag {attributes} & children].\n;; It is the common language of notation, composition and CAC in Kairotic: components take trees and\n;; return trees, and a canvas, a freqt or a score can show one. Like bach's llll it nests freely;\n;; unlike it, attributes have names, so any extra data (bach's slots) is just one more key.\n;;\n;; Time is in beats (a quarter note = 1); :tempo (beats per minute, 60 by default) turns it into seconds.\n;;\n;; sequential :seq :voice :section :measure {:meter [3 4]} :tuplet {:ratio [3 2]} children one after another\n;; a measure groups its units with {:meter [5 8] :groups [2 3]}, or {:meter \"5/8[2+3]\"}\n;; simultaneous :par :piece :chord children at once\n;; leaves :note {:pitch \"c4\" | 60.5 | :hz 440, :dur 1} :rest {:dur 1}\n;; :param {:name :cutoff :value 400 :to 2000 :dur 4} a parameter change (a ramp with :to)\n;; :dyn {:mark \"mf\"} · {:mark \"<\" :dur 2} a dynamic, or a hairpin\n;; :text {:text \"dolce\"} a text indication\n;; :use {:ref :motif :transpose 5} a fragment defined in :defs, varied\n;; :rtm {:shares [1 [1 [1 1 1]] -1 2] :pitches \"c4 d4 e4\"} proportional rhythm: shares of\n;; its :dur (or of its measure); note values and tuplets follow from shares and meter\n;; strings \"c4/1 e4/.5 r/1 c4+e4+g4/2\" melody shorthand inside any container\n;;\n;; Any node may carry :at (an offset from the start of its parent; it does not move the parent's\n;; cursor), :id, and any other key. Notes also take :art [:staccato :accent], :dyn \"p\", :text \"…\",\n;; :gliss [[0 0] [1 -150]] (cents over the note's duration), :env [[0 0] [0.1 1] [1 0]], :vel 0.8.\n;; A written name may carry :cents (its deviation: {:pitch \"c4\" :cents 50} is a quarter tone above c4).\n;; :tie true goes on into the next note of the same pitch (across a barline or into a tuplet: one sound,\n;; tied in the score); :grace true is a grace note before the next one (it takes no time in its container).\n;; A :voice with :staff \"name\" is written as a layer of that staff (voices that share it, layers 1, 2 …).\n;; A note without :dur lasts as long as the previous one of its container (1 at first). :defs (a map\n;; of fragments) can sit in the attributes of any container; [:use {:ref k}] takes them from there.\n\n(ns kairotic.mt\n (:require [clojure.string :as str]\n [clojure.edn :as edn]\n [kairotic.canvas :as cv]\n [kairotic.score :as sc]\n [kairotic.spell :as sp]))\n\n;; ───────── nodes ─────────\n\n(def seq-tags #{:seq :voice :measure :tuplet})\n(def par-tags #{:par :chord})\n;; a work: in a :piece or a :section, voices (and :par) sound together from its start, and anything\n;; else — sections in a piece, measures in a section — follows in order\n(def block-tags #{:piece :section})\n(def mark-tags #{:param :dyn :text})\n(def known-tags (into (into (into (into #{:note :rest :use :rtm} seq-tags) par-tags) block-tags) mark-tags))\n\n(defn node? [x] (and (vector? x) (keyword? (first x))))\n(defn tag [n] (when (node? n) (first n)))\n(defn attrs [n] (let [a (second n)] (if (map? a) a {})))\n(defn kids [n] (if (map? (second n)) (subvec n 2) (subvec n 1)))\n(defn make [t a ks] (into (if (seq a) [t a] [t]) ks))\n;; a node keeps its metadata (where it comes from in the written tree) when it changes\n(defn with-attrs [n a] (with-meta (make (tag n) a (kids n)) (meta n)))\n(defn with-kids [n ks] (with-meta (make (tag n) (attrs n) ks) (meta n)))\n(defn update-attrs [n f & args] (with-attrs n (apply f (attrs n) args)))\n\n(defn tree? \"Is x a musical tree (or a string of melody)?\" [x] (or (node? x) (string? x)))\n\n;; ───────── pitch ─────────\n\n(def pc-names [\"c\" \"c#\" \"d\" \"d#\" \"e\" \"f\" \"f#\" \"g\" \"g#\" \"a\" \"a#\" \"b\"])\n\n(defn midi-of\n \"The pitch of a note as a MIDI number (with decimals for microtones), or nil.\"\n [a]\n (cond\n (number? (:hz a)) (when (pos? (:hz a)) (cv/hz->midi (:hz a)))\n (some? (:pitch a)) (when-let [m (sc/pitch (:pitch a))] (+ m (/ (or (:cents a) 0) 100)))\n :else nil))\n\n(defn pitch-name\n \"60 → \\\"c4\\\"; a fractional pitch stays a number.\"\n [m]\n (if (and (number? m) (= m (js/Math.round m)))\n (str (nth pc-names (mod m 12)) (dec (js/Math.floor (/ m 12))))\n m))\n\n(defn spelling-of\n \"How a note's pitch is written ({:step :alter :oct}, kairotic.spell), when it is a name; nil for numbers and Hz.\"\n [a]\n (when-not (number? (:hz a)) (sp/parse (:pitch a))))\n\n(defn respell\n \"A name for MIDI pitch m (an integer) like the name it had: a natural when there is one, else a flat for\n a flat and a sharp for a sharp (bb4 + 1 = b4, eb4 - 1 = d4, db4 + 3 = e4, eb4 + 3 = gb4).\"\n [m was]\n (let [sign (if was (js/Math.sign (:alter was)) 1)]\n (first (sort-by (fn [x] [(js/Math.abs (:alter x)) (if (= (js/Math.sign (:alter x)) sign) 0 1)])\n (filter (fn [x] (<= (js/Math.abs (:alter x)) 1)) (sp/spellings m))))))\n\n(defn set-midi\n \"Writes a new pitch in the attributes of a note, in the same kind of value it had (name, number or Hz);\n a name keeps the way it was written as far as it can (see respell).\"\n [a m]\n (cond\n (number? (:hz a)) (assoc a :hz (cv/round-to (cv/midi->hz m) 3))\n (and (or (string? (:pitch a)) (keyword? (:pitch a))) (== m (js/Math.round m)))\n (assoc (dissoc a :cents) :pitch (sp/->name (respell (js/Math.round m) (spelling-of a))))\n (string? (:pitch a)) (assoc (dissoc a :cents) :pitch (pitch-name (cv/round-to m 3)))\n (keyword? (:pitch a)) (assoc (dissoc a :cents) :pitch (pitch-name (cv/round-to m 3)))\n :else (assoc (dissoc a :cents) :pitch (cv/round-to m 3))))\n\n;; ───────── melody shorthand ─────────\n\n(defn melody\n \"\\\"c4/1 d4/.5 r/1 c4+e4+g4/2 f4\\\" → nodes. A token without /dur keeps the previous duration.\"\n [txt]\n (loop [toks (remove str/blank? (str/split (str/trim (str txt)) #\"\\s+\")) prev 1 out []]\n (if (empty? toks)\n out\n (let [[p d] (str/split (first toks) #\"/\" 2)\n dur (if (seq d) (let [x (js/parseFloat d)] (if (js/isNaN x) prev x)) prev)\n node (if (= \"r\" (str/lower-case p))\n [:rest {:dur dur}]\n (let [ps (str/split p #\"\\+\")]\n (doseq [x ps] (when-not (sc/pitch x) (throw (js/Error. (str \"I don't understand the note «\" x \"» (use c4, f#3, bb2)\")))))\n (if (= 1 (count ps))\n [:note {:pitch (str/lower-case (first ps)) :dur dur}]\n (into [:chord {:dur dur}] (for [x ps] [:note {:pitch (str/lower-case x)}])))))]\n (recur (rest toks) dur (conj out node))))))\n\n;; ───────── numbers: exact fractions [n d] ─────────\n\n(defn- gcd [a b] (if (zero? b) (js/Math.abs a) (recur b (mod a b))))\n(defn- lcm [a b] (/ (* a b) (gcd a b)))\n(defn- r-norm [[n d]] (let [g (gcd n d)] [(/ n g) (/ d g)]))\n\n(defn- rat\n \"x as a fraction [n d] (d > 0): exact for the beats music uses (halves, thirds, fifths, eighths…).\"\n [x]\n (let [s (if (neg? x) -1 1) x (js/Math.abs x)]\n (loop [h1 1 h0 0 k1 0 k0 1 y x i 0]\n (let [a (js/Math.floor y) h (+ (* a h1) h0) k (+ (* a k1) k0)]\n (if (or (< (js/Math.abs (- x (/ h k))) 1e-9) (> i 40) (== y a))\n [(* s h) k]\n (recur h h1 k k1 (/ 1 (- y a)) (inc i)))))))\n\n(defn- r+ [[a b] [c d]] (r-norm [(+ (* a d) (* c b)) (* b d)]))\n(defn- r- [[a b] [c d]] (r-norm [(- (* a d) (* c b)) (* b d)]))\n(defn- r-div [[a b] [c d]] (r-norm [(* a d) (* b c)]))\n(defn- r< [[a b] [c d]] (< (* a d) (* c b)))\n\n(defn- prime-factors \"12 → [2 2 3] (smallest first: a span halves before it thirds).\" [n]\n (loop [n n f 2 out []]\n (cond (< n 2) out\n (> (* f f) n) (conj out n)\n (zero? (mod n f)) (recur (/ n f) f (conj out f))\n :else (recur n (inc f) out))))\n\n;; ───────── meters: groups and metric weight ─────────\n;; A meter is [p q] (p units of 1/q), and a measure may group its units: {:meter [5 8] :groups [2 3]},\n;; also written \"5/8[2+3]\". Groups say where the beats fall (beams, metric weight); without them a\n;; meter groups as it is usually read (6/8 in two dotted quarters, 3/4 in three quarters).\n;;\n;; Metric level (after Rastrum, smoge/Rastrum): 0 at the start of the bar, 1 at the start of a group,\n;; and deeper for each division of a group (or of the bar) by the prime factors of its units, twos\n;; first, then halving. Indispensability: Clarence Barlow's ranking of how much each pulse is needed\n;; for the meter to be heard as itself (N−1 the downbeat … 0 the most dispensable). It is composition\n;; data, not notation: 3/4 and 6/8 hold the same six eighths and rank them differently. For a grouped\n;; meter Kairotic ranks by metric level, then by Barlow inside each group, then the earlier group.\n\n(defn parse-meter\n \"\\\"5/8[2+3]\\\" → {:meter [5 8] :groups [2 3]}; \\\"3/4\\\" → {:meter [3 4]}; nil if it is not a meter.\"\n [s]\n (when-let [[_ p q g] (re-matches #\"\\s*(\\d+)\\s*/\\s*(\\d+)\\s*(?:\\[\\s*([\\d\\s+]+?)\\s*\\])?\\s*\" (str s))]\n (cond-> {:meter [(js/parseInt p 10) (js/parseInt q 10)]}\n g (assoc :groups (mapv (fn [x] (js/parseInt x 10)) (str/split (str/trim g) #\"\\s*\\+\\s*\"))))))\n\n(defn meter-of\n \"A meter as {:meter [p q] :groups [a b …]} (no :groups when it has none), from [5 8], \\\"5/8[2+3]\\\",\n {:meter … :groups …} or a measure.\"\n [x]\n (cond\n (node? x) (meter-of (attrs x))\n (string? x) (or (parse-meter x)\n (throw (js/Error. (str \"a meter is [p q], \\\"p/q\\\" or \\\"p/q[a+b…]\\\", not \" (pr-str x)))))\n (map? x) (let [m (meter-of (or (:meter x) [4 4]))]\n (if (seq (:groups x)) (assoc m :groups (vec (:groups x))) m))\n (and (vector? x) (= 2 (count x)) (every? number? x) (every? pos? x)) {:meter x}\n :else (throw (js/Error. (str \"a meter is [p q], \\\"p/q\\\" or \\\"p/q[a+b…]\\\", not \" (pr-str x))))))\n\n(defn- with-meter-attrs\n \"The attributes of a measure with its meter read: :meter \\\"5/8[2+3]\\\" → :meter [5 8] :groups [2 3].\"\n [a]\n (if (string? (:meter a))\n (let [m (meter-of (:meter a))]\n (cond-> (assoc a :meter (:meter m)) (and (:groups m) (not (:groups a))) (assoc :groups (:groups m))))\n a))\n\n(defn meter-level\n \"The metric level of a position (beats from the start of the bar): 0 the bar, 1 a group, then deeper;\n 20 for a position no division reaches (inside a tuplet).\"\n [meter pos]\n (let [{[p q] :meter g :groups} (meter-of meter)\n bar (* p (/ 4 q))\n x (rat (let [m (mod pos bar)] (if (< (js/Math.abs (- m bar)) 1e-9) 0 m)))]\n (if (zero? (first x))\n 0\n (loop [gs (or (seq g) [p]) start [0 1]]\n (if (empty? gs)\n 20\n (let [n (first gs) span (r-norm [(* 4 n) q]) local (r- x start)]\n (if-not (r< local span)\n (recur (rest gs) (r+ start span))\n (if (zero? (first local))\n 1\n (loop [fs (concat (prime-factors n) (repeat 16 2)) step span i 1]\n (if (empty? fs)\n 20\n (let [step (r-div step [(first fs) 1])]\n (if (= 1 (second (r-div local step)))\n (+ (if (seq g) 1 0) i)\n (recur (rest fs) step (inc i))))))))))))))\n\n(declare barlow-basic)\n\n(defn- barlow\n \"Barlow's indispensability ψ of pulse n (from 1) in a stratification (prime factors, top first).\"\n [n strata]\n (let [z (count strata) total (reduce * 1 strata) ps (vec (concat [1] strata [1]))]\n (reduce + 0 (for [r (range z)]\n (let [inner (reduce * 1 (map (fn [k] (ps (- (inc z) k))) (range (inc r))))\n outer (reduce * 1 (map ps (range (- z r))))\n m (ps (- z r))\n digit (inc (mod (inc (quot (mod (- n 2) total) inner)) m))]\n (* outer (barlow-basic digit m)))))))\n\n(defn- barlow-basic\n \"Barlow's basic indispensability Ψ of pulse n (from 1) in a prime p; primes above 3 build on p−1.\"\n [n p]\n (if (<= p 3)\n (mod (+ p n -2) p)\n (let [w (fn [x] (if (zero? x) 0 1))\n q (barlow (+ n -1 (w (- p n))) (vec (reverse (prime-factors (dec p)))))\n quarter (quot p 4)\n beyond (w (- p n 1))]\n (+ (* (+ q (w (quot q quarter))) beyond) (* quarter (- 1 beyond))))))\n\n(defn- pulse-count\n \"How many pulses of `pulse` beats fit in a unit of the meter (nil: the unit itself).\"\n [q pulse]\n (let [per (if pulse (/ (/ 4 q) pulse) 1)]\n (when-not (and (>= per 1) (< (js/Math.abs (- per (js/Math.round per))) 1e-9))\n (throw (js/Error. (str \"a pulse of \" pulse \" beats does not divide the unit of a \" q \"-meter\"))))\n (js/Math.round per)))\n\n(defn pulses\n \"The pulses of a bar, in beats from its start: one per unit, or per `pulse` beats.\"\n ([meter] (pulses meter nil))\n ([meter pulse]\n (let [{[p q] :meter} (meter-of meter) per (pulse-count q pulse) pb (/ (/ 4 q) per)]\n (mapv (fn [i] (* i pb)) (range (* p per))))))\n\n(defn indispensability\n \"Barlow's indispensability of every pulse of a bar (one per unit, or per `pulse` beats), in order:\n 3/4 in eighths → [5 0 3 1 4 2]; 6/8 → [5 0 2 4 1 3]. The downbeat is the highest.\"\n ([meter] (indispensability meter nil))\n ([meter pulse]\n (let [{[p q] :meter g :groups :as m} (meter-of meter)\n per (pulse-count q pulse)\n n (* p per)\n strata (fn [units] (vec (concat (prime-factors units) (prime-factors per))))]\n (if-not (seq g)\n (let [s (strata p)] (mapv (fn [i] (barlow (inc i) s)) (range n)))\n (let [pb (/ (/ 4 q) per)\n group-of (vec (mapcat (fn [gi k] (repeat (* k per) gi)) (range) g))\n within (vec (mapcat (fn [k] (let [s (strata k)] (map (fn [i] (barlow (inc i) s)) (range (* k per))))) g))\n order (sort-by (fn [i] [(meter-level m (* i pb)) (- (within i)) (group-of i)]) (range n))\n rank (into {} (map-indexed (fn [r i] [i (- n 1 r)]) order))]\n (mapv rank (range n)))))))\n\n(defn indispensability-at\n \"The indispensability of a position (beats from the start of the bar), or nil off the pulses.\"\n ([meter pos] (indispensability-at meter pos nil))\n ([meter pos pulse]\n (let [{[_ q] :meter} (meter-of meter) pb (/ (/ 4 q) (pulse-count q pulse)) x (/ pos pb) i (js/Math.round x)]\n (when (< (js/Math.abs (- x i)) 1e-6) (get (indispensability meter pulse) i)))))\n\n;; ───────── transformations (tree → tree) ─────────\n\n(defn walk-notes\n \"Applies f to the attributes of every note.\"\n [f n]\n (cond\n (not (node? n)) n\n (= :note (tag n)) (with-attrs n (f (attrs n)))\n :else (with-kids n (mapv (fn [k] (walk-notes f k)) (kids n)))))\n\n(defn first-pitch [n]\n (cond (not (node? n)) nil\n (= :note (tag n)) (midi-of (attrs n))\n :else (some first-pitch (kids n))))\n\n(declare expand)\n\n(defn- spelled-notes [t] (keep (fn [x] (when (and (node? x) (= :note (tag x))) (spelling-of (attrs x)))) (tree-seq node? kids t)))\n\n(defn transpose\n \"Moves every pitch by n semitones (decimals: microtones), or by an interval (\\\"M3\\\", \\\"-P5\\\", \\\"A4\\\",\n [steps semitones]). Written names move by that interval and keep their spelling (c4 e4 g4 by \\\"m3\\\" is\n eb4 g4 bb4); by a number of semitones they move by the interval it is usually written as (1 a minor\n second, 6 the augmented fourth or the diminished fifth, whichever needs fewer alterations). Its keys\n (:key) move by the same interval.\"\n [n tree]\n (let [t (expand tree)\n iv (cond (and (number? n) (== n (js/Math.round n)))\n (if (= 6 (mod n 12))\n (let [alts (fn [iv] (reduce + (map (fn [s] (js/Math.abs (:alter (sp/transpose-spelling s iv)))) (spelled-notes t))))\n a (sp/interval-of-semitones n false) d (sp/interval-of-semitones n true)]\n (if (< (alts d) (alts a)) d a))\n (sp/interval-of-semitones n))\n (number? n) nil\n :else (or (sp/interval n) (throw (js/Error. (str \"An interval is a number of semitones or a name like M3, -P5, A4: not \" (pr-str n))))))\n semis (if iv (second iv) n)\n ;; keys move with the notes (by a number with decimals, a microtone, they stay)\n keys-moved (fn keys-moved [x]\n (if-not (node? x)\n x\n (let [x (if (and iv (contains? (attrs x) :key)) (update-attrs x update :key sp/transpose-key iv) x)]\n (if (= :note (tag x)) x (with-kids x (mapv keys-moved (kids x)))))))]\n (keys-moved\n (walk-notes (fn [a]\n (if-let [s (and iv (spelling-of a))]\n (assoc a :pitch (sp/->name (sp/transpose-spelling s iv)))\n (if-let [m (midi-of a)] (set-midi a (+ m semis)) a)))\n t))))\n\n(defn invert\n \"Mirrors every pitch around a pivot (by default, the first pitch).\"\n ([tree] (invert nil tree))\n ([pivot tree]\n (let [t (expand tree)\n p (or (if (or (string? pivot) (keyword? pivot)) (sc/pitch pivot) pivot) (first-pitch t) 60)\n ;; a written pivot (or the first written note) mirrors names on the line of fifths too\n ps (or (when (or (string? pivot) (keyword? pivot)) (sp/parse pivot))\n (when (nil? pivot) (first (spelled-notes t))))]\n (walk-notes (fn [a] (if-let [m (midi-of a)]\n (cond-> (if-let [s (and ps (spelling-of a))]\n (assoc a :pitch (sp/->name (sp/invert-spelling s ps)))\n (set-midi a (- (* 2 p) m)))\n (:gliss a) (assoc :gliss (mapv (fn [[x c]] [x (- c)]) (:gliss a))))\n a))\n t))))\n\n(defn explicit\n \"Writes in every note, rest and chord of a sequence the duration it takes from the previous one.\"\n [n]\n (if-not (node? n)\n n\n (let [seqy (seq-tags (tag n))]\n (with-kids n\n (loop [ks (kids n) prev 1 out []]\n (if (empty? ks)\n out\n (let [k (first ks)\n durable (and (node? k) (#{:note :rest :chord} (tag k)) (not (:at (attrs k))) (not (:grace (attrs k))))\n d (when durable (or (:dur (attrs k)) prev))\n k (explicit (if (and durable seqy) (update-attrs k assoc :dur d) k))]\n (recur (rest ks) (if (and durable seqy) d prev) (conj out k)))))))))\n\n(defn with-meters\n \"Writes in every measure the meter (and groups) it takes from the previous one (4/4 at first); a\n meter written as \\\"5/8[2+3]\\\" becomes :meter [5 8] :groups [2 3]. A new meter without groups has none;\n groups without a meter keep the meter.\"\n [tree]\n (let [last-m (atom {:meter [4 4]})]\n (letfn [(go [n]\n (cond\n (not (node? n)) n\n (= :measure (tag n))\n (let [a (with-meter-attrs (attrs n))\n cur (cond (:meter a) (cond-> {:meter (:meter a)} (seq (:groups a)) (assoc :groups (vec (:groups a))))\n (seq (:groups a)) (assoc @last-m :groups (vec (:groups a)))\n :else @last-m)]\n (reset! last-m cur)\n (with-meta (make :measure (merge (dissoc a :groups) cur) (mapv go (kids n))) (meta n)))\n :else (with-kids n (mapv go (kids n)))))]\n (go tree))))\n\n(defn scale-meter\n \"The meter of a measure whose durations are multiplied by f: 4/4 × 2 = 8/4, 3/4 × 0.5 = 3/8.\"\n [[p q] f]\n (let [p2 (* p f) q2 (/ q f)]\n (cond (= p2 (js/Math.round p2)) [p2 q]\n (and (= q2 (js/Math.round q2)) (pos? q2)) [p q2]\n :else [p2 q])))\n\n(defn augment\n \"Multiplies every duration (and offset) by f: 2 doubles, 0.5 halves. Measures change their meter.\"\n [f tree]\n (letfn [(go [n]\n (if-not (node? n)\n n\n (let [a (attrs n)\n a (cond-> a\n (number? (:dur a)) (update :dur * f)\n (number? (:at a)) (update :at * f)\n (and (= :measure (tag n)) (vector? (:meter a))) (update :meter scale-meter f))\n ;; groups count units: they grow with the numerator\n a (let [p0 (first (:meter (attrs n))) p1 (first (:meter a))]\n (if (and (seq (:groups a)) (number? p0) (not= p0 p1))\n (update a :groups (fn [g] (mapv (fn [x] (* x (/ p1 p0))) g)))\n a))]\n (make (tag n) a (mapv go (kids n))))))]\n (go (with-meters (explicit (expand tree))))))\n\n(defn retrograde\n \"Plays it backwards: the children of every sequence in reverse order (glissandi too).\"\n [tree]\n (letfn [(go [n]\n (cond\n (not (node? n)) n\n (= :note (tag n)) (let [a (attrs n)]\n (if (:gliss a)\n (let [g (:gliss a) end (second (peek g))]\n (with-attrs n (-> (set-midi a (+ (midi-of a) (/ end 100)))\n (assoc :gliss (vec (reverse (mapv (fn [[x c]] [(- 1 x) (- c end)]) g)))))))\n n))\n (seq-tags (tag n)) (with-kids n (vec (reverse (mapv go (kids n)))))\n (block-tags (tag n)) (let [ks (mapv go (kids n))\n together? (fn [k] (or (not (node? k)) (#{:voice :par} (tag k)) (some? (:at (attrs k)))))\n slots (vec (keep-indexed (fn [i k] (when-not (together? k) i)) ks))\n moved (zipmap slots (reverse (map ks slots)))]\n (with-kids n (vec (map-indexed (fn [i k] (get moved i k)) ks))))\n :else (with-kids n (mapv go (kids n)))))]\n (go (with-meters (explicit (expand tree))))))\n\n(defn rotate\n \"Moves the first k elements of the top sequence to its end (negative k: the other way).\"\n [k tree]\n (let [t (with-meters (explicit (expand tree))) ks (kids t) n (count ks)]\n (if (zero? n) t (let [k (mod k n)] (with-kids t (vec (concat (drop k ks) (take k ks))))))))\n\n(declare measured? duration)\n\n(defn as-voice [t nm] (if (= :voice (tag t)) (update-attrs t assoc :name nm) [:voice {:name nm} t]))\n\n(defn- canon*\n \"The tree (the dux) against the comes, entering `delay` beats later. When the dux is written in measures and\n the delay is a whole number of them, the comes enters after rest bars.\"\n [delay t comes]\n (let [first-m (first (filter (fn [x] (and (node? x) (= :measure (tag x)))) (tree-seq node? kids t)))\n [p q] (when first-m (:meter (attrs first-m)))\n bar (when p (* p (/ 4 q)))\n bars (when bar (/ delay bar))]\n (if (and bars (pos? bars) (= bars (js/Math.round bars)))\n (let [v2 (as-voice comes \"comes\")\n rests (vec (repeat bars [:measure {:meter [p q]} [:rest {:dur bar}]]))]\n [:par {:name \"canon\"} (as-voice t \"dux\") (with-kids v2 (into rests (kids v2)))])\n [:par {:name \"canon\"} (as-voice t \"dux\") [:voice {:name \"comes\"} [:seq {:at delay} comes]]])))\n\n(defn canon\n \"The tree against itself, entering `delay` beats later and transposed by `interval`. When it is\n written in measures and the delay is a whole number of them, the second voice enters after rest bars.\n With a map, the words of the heads (discussion \\\"Heads on a span of time\\\"): {:d beats later, :k an\n interval (semitones or a name, M3, -P5), :speed of the comes (0.5 twice as slow, 2 twice as fast, −1\n backwards: a crab), :inversion (upside down, around the dux's first pitch)}.\"\n ([delay tree]\n (if (map? delay)\n (let [{:keys [d k speed inversion]} delay\n t (with-meters (explicit (expand tree)))\n s (if (and (number? speed) (not (zero? speed))) speed 1)\n comes (cond->> t\n inversion (invert nil)\n (neg? s) retrograde\n (not= 1 (js/Math.abs s)) (augment (/ 1 (js/Math.abs s)))\n true (transpose (or k 0)))]\n (canon* (or d 1) t comes))\n (canon delay 0 tree)))\n ([delay interval tree]\n (let [t (with-meters (explicit (expand tree)))]\n (canon* delay t (transpose interval t)))))\n\n(defn apply-ops\n \"The variations a [:use …] or a box can ask for, in a fixed order.\"\n [a tree]\n (cond->> tree\n (:transpose a) (transpose (:transpose a))\n (some? (:invert a)) (invert (if (true? (:invert a)) nil (:invert a)))\n (:retrograde a) retrograde\n (:augment a) (augment (:augment a))))\n\n;; ───────── expansion: strings and references ─────────\n\n(def op-keys #{:ref :transpose :invert :retrograde :augment})\n\n(defn- from [x src] (if (node? x) (with-meta x src) x))\n\n;; ───────── proportional rhythm (:rtm) ─────────\n;; A rhythm written as shares, as in the RTM trees of OpenMusic and PWGL (and Rastrum, for\n;; SuperCollider): a number is a share, a negative number a silence, and [weight [shares …]] divides a\n;; share further. Shares are relative (a common factor changes nothing); the :rtm lasts its :dur, or\n;; fills its measure. Note values and tuplets are not written: they follow from shares and meter. When\n;; the equal unit of a level is a written value (a power of two of a beat: 1, 1/2, 2…) the notes take\n;; it as it is; when not, the level becomes a tuplet of the smallest written value that is not shorter.\n;; Three shares of a 3/4 bar are quarters; three of a 4/4 bar, a 3:2 of halves.\n;; Pitches go to the notes in order and start again when they run out (talea and color).\n\n(defn- pow2? [d] (loop [d d] (cond (= d 1) true (or (< d 1) (odd? d)) false :else (recur (/ d 2)))))\n\n(defn- pow2-at-least\n \"The smallest power of two (of a beat) that is not shorter than the fraction [n d], as a fraction.\"\n [[n d]]\n (let [ge (fn [[a b]] (>= (* a d) (* n b)))]\n (if (ge [1 1])\n (loop [p [1 1]] (let [h [(first p) (* 2 (second p))]] (if (ge h) (recur h) p)))\n (loop [p [2 1]] (if (ge p) p (recur [(* 2 (first p)) 1]))))))\n\n(defn- read-shares [s] (if (string? s) (edn/read-string s) s))\n\n(defn- rtm-item [x]\n (cond\n (and (number? x) (not (zero? x))) {:w (js/Math.abs x) :rest (neg? x)}\n (and (sequential? x) (= 2 (count x)) (number? (first x)) (pos? (first x)) (sequential? (second x)))\n {:w (first x) :subs (second x)}\n :else (throw (js/Error. (str \"rtm: a share is a number (negative: a rest) or [weight [shares …]], not \" (pr-str x))))))\n\n(defn- integer-weights\n \"Weights as whole numbers without a common factor: [2 2 2] → [1 1 1], [0.5 1] → [1 2].\"\n [ws]\n (let [rs (mapv rat ws)\n l (reduce lcm 1 (map second rs))\n is (mapv (fn [[n d]] (* n (/ l d))) rs)\n g (reduce gcd 0 is)]\n (mapv (fn [i] (/ i g)) is)))\n\n(defn- rtm-nodes\n \"The nodes of shares that last total (a fraction of written beats); next-leaf makes each note.\"\n [shares total next-leaf depth]\n (let [shares (read-shares shares)]\n (when (> depth 16) (throw (js/Error. \"rtm: shares nested too deep\")))\n (when-not (and (sequential? shares) (seq shares))\n (throw (js/Error. (str \"rtm: :shares is a list of shares, like [1 [1 [1 1 1]] -1 2], not \" (pr-str shares)))))\n (let [items (mapv rtm-item shares)\n ws (integer-weights (map :w items))\n s (reduce + ws)\n unit (r-norm [(first total) (* (second total) s)])\n tup? (not (pow2? (second unit)))\n u (if tup? (pow2-at-least unit) unit)\n nodes (vec (mapcat (fn [it w]\n (let [d (r-norm [(* w (first u)) (second u)])\n beats (/ (first d) (second d))]\n (cond (:subs it) (rtm-nodes (:subs it) d next-leaf (inc depth))\n (:rest it) [[:rest {:dur beats}]]\n :else [(next-leaf beats)])))\n items ws))]\n (if tup?\n ;; s written units in the time of total: s:(total/u)\n (let [[a b] (r-norm [(* (first total) (second u)) (* (second total) (first u))])\n ratio (if (= b 1) [s a] (let [g (gcd (* s b) a)] [(/ (* s b) g) (/ a g)]))]\n [(into [:tuplet {:ratio ratio}] nodes)])\n nodes))))\n\n(defn- rtm-leaves\n \"A function that gives the next note of an :rtm, with a duration: its :pitches in turn (a melody\n string, or a list of pitches), starting again when they run out; \\\"r\\\" there is a rest.\"\n [a]\n (let [src (:pitches a)\n pool (vec (cond (string? src) (melody src)\n (sequential? src) (mapcat (fn [p] (cond (string? p) (melody p)\n (number? p) [[:note {:pitch p}]]\n (node? p) [p]\n :else []))\n src)\n :else []))\n default [:note {:pitch (or (:pitch a) \"c4\")}]\n i (volatile! 0)]\n (fn [beats]\n (let [n (if (seq pool) (nth pool (mod @i (count pool))) default)]\n (vswap! i inc)\n (update-attrs n assoc :dur beats)))))\n\n(defn- rtm-expand\n \"The nodes an :rtm stands for. Its notes remember the :rtm they come from ({:src path :rtm true}).\"\n [n path bar]\n (let [a (attrs n)\n total (cond (some? (:dur a)) (:dur a)\n bar (let [[p q] bar] (* p (/ 4 q)))\n :else 4)\n _ (when-not (and (number? total) (pos? total))\n (throw (js/Error. (str \"rtm: :dur is a positive number of beats, not \" (pr-str total)))))\n src (if path {:src path :rtm true} (meta n))\n mark (fn mark [x] (if (node? x) (from (with-kids x (mapv mark (kids x))) src) x))\n nodes (mapv mark (rtm-nodes (:shares a) (rat total) (rtm-leaves a) 0))\n extra (dissoc a :shares :pitches :pitch :dur)]\n (if (seq extra) [(from (into [:seq extra] nodes) src)] nodes)))\n\n;; ───────── proportional rhythm: cells (share lists → share lists) ─────────\n\n(defn cell-retrograde\n \"Shares backwards, at every level: [1 [2 [1 3]]] → [[2 [3 1]] 1].\"\n [shares]\n (vec (reverse (map (fn [x] (if (sequential? x) [(first x) (cell-retrograde (second x))] x)) (read-shares shares)))))\n\n(defn cell-rotate\n \"Moves the first k shares to the end (negative k: the other way).\"\n [k shares]\n (let [xs (vec (read-shares shares)) n (count xs)]\n (if (zero? n) xs (let [k (mod k n)] (vec (concat (drop k xs) (take k xs)))))))\n\n(defn cell-at\n \"The share at path: [i] is the i-th share; [i j] the j-th inside the i-th, when it is divided.\"\n [shares path]\n (loop [xs (read-shares shares) p (seq path)]\n (if (nil? p)\n xs\n (let [x (nth (vec xs) (first p) nil)]\n (cond (nil? (next p)) x\n (and (sequential? x) (sequential? (second x))) (recur (second x) (next p))\n :else nil)))))\n\n(defn cell-replace-at\n \"Divides the share at path into cell, keeping its weight: a cell can grow inside itself\n ((cell-replace-at seed [1] seed)).\"\n [shares path cell]\n (let [xs (vec (read-shares shares)) [i & more] path x (nth xs i nil)]\n (when (nil? x) (throw (js/Error. (str \"cell-replace-at: no share at \" (pr-str path)))))\n (assoc xs i\n (if (seq more)\n (if (and (sequential? x) (sequential? (second x)))\n [(first x) (cell-replace-at (second x) more cell)]\n (throw (js/Error. (str \"cell-replace-at: the share at \" (pr-str (vec (take 1 path))) \" is not divided\"))))\n [(if (sequential? x) (first x) (js/Math.abs x)) (vec (read-shares cell))]))))\n\n;; ───────── expansion ─────────\n\n(defn expand*\n \"Expands n; every node remembers where it was written: {:src path} (and {:sub [i …]} inside a\n melody string, {:rtm true} for what an :rtm stands for); nodes that come from :defs have no :src.\n ctx carries the meter in force (as :with-meters reads it) so that an :rtm can fill its measure.\"\n ([n defs depth] (expand* n defs depth nil))\n ([n defs depth path] (expand* n defs depth path {:meter (volatile! [4 4]) :bar nil}))\n ([n defs depth path ctx]\n (cond\n (string? n) (vec (map-indexed (fn [i x]\n (let [x (if (= :chord (tag x))\n (with-kids x (vec (map-indexed (fn [j k] (from k (when path {:src path :sub [i j]}))) (kids x))))\n x)]\n (from x (when path {:src path :sub [i]}))))\n (melody n)))\n (not (node? n)) []\n (= :use (tag n))\n (let [a (attrs n) r (:ref a) k (if (string? r) (keyword r) r) d (get defs k)]\n (when (> depth 24) (throw (js/Error. (str \"Fragments that use each other without end (\" r \")\"))))\n (when-not d (throw (js/Error. (str \"No fragment \" (pr-str r) \" in :defs\"))))\n (let [xs (expand* d defs (inc depth) nil ctx)\n body (if (= 1 (count xs)) (first xs) (into [:seq] xs))\n varied (apply-ops a body)\n extra (apply dissoc a op-keys)]\n [(from (if (seq extra) [:seq extra varied] varied) (if path {:src path :use true} (meta n)))]))\n (= :rtm (tag n)) (rtm-expand n path (:bar ctx))\n :else\n (let [measure? (= :measure (tag n))\n a (cond-> (attrs n) measure? with-meter-attrs)\n defs (merge defs (:defs a))\n _ (when (and measure? (vector? (:meter a))) (vreset! (:meter ctx) (:meter a)))\n ;; only the direct children of a measure fill it\n kctx (assoc ctx :bar (when measure? @(:meter ctx)))]\n [(from (make (tag n) (dissoc a :defs)\n (vec (apply concat (mapv (fn [i k] (expand* k defs depth (when path (conj path i)) kctx))\n (range) (kids n)))))\n (if path {:src path} (meta n)))]))))\n\n(defn- one-node [xs] (if (<= (count xs) 1) (first xs) (into [:seq] xs)))\n\n(defn expand\n \"Strings become notes, [:use …] the fragments they name, varied, and [:rtm …] its notes, rests and\n tuplets. A list of nodes becomes a :seq.\"\n [x]\n (cond\n (string? x) (into [:seq] (melody x))\n (and (sequential? x) (not (node? x))) (expand (into [:seq] x))\n :else (one-node (expand* x {} 0 nil))))\n\n(defn expand-source\n \"Expands a written tree remembering, in each node's metadata, where it was written ({:src path},\n {:sub [i]} inside a melody string), and in the root which box it comes from ({:from :b2}): a score\n that shows it can then edit the written tree.\"\n [t box-id]\n (vary-meta (one-node (expand* t {} 0 [])) assoc :from box-id))\n\n;; ───────── time: flattening ─────────\n\n(defn- add-ev [acc ev] (conj! acc ev))\n\n(defn place\n \"Places node n at t (beats) with a time scale; adds its events to acc and returns where it ends.\"\n [n t scale ctx acc]\n (let [tg (tag n) a (attrs n)]\n (cond\n ;; a grace note sounds briefly where it is, and the time goes on as if it were not there\n (and (= :note tg) (:grace a))\n (let [m (midi-of a)]\n (when m\n (add-ev acc (merge (dissoc a :pitch :hz :cents :dur :at :id)\n {:kind :note :t t :dur (* scale (or (:dur a) 0.125)) :pitch m :voice (:voice ctx) :path (:path ctx)}\n (when-let [w (spelling-of a)] {:name (sp/->name w)}))))\n t)\n\n (= :note tg)\n (let [d (* scale (or (:dur a) (:dur ctx) 1)) m (midi-of a)]\n (when m\n (add-ev acc (merge (dissoc a :pitch :hz :cents :dur :at :id)\n {:kind :note :t t :dur d :pitch m :voice (:voice ctx) :path (:path ctx)}\n (when (:id a) {:id (:id a)})\n (when-let [w (spelling-of a)] {:name (sp/->name w)}))))\n (+ t d))\n\n (= :rest tg) (+ t (* scale (or (:dur a) (:dur ctx) 1)))\n\n (mark-tags tg)\n (do (add-ev acc (merge (dissoc a :at) {:kind tg :t t :dur (* scale (or (:dur a) 0)) :voice (:voice ctx) :path (:path ctx)}))\n t)\n\n (= :chord tg)\n (let [d (* scale (or (:dur a) (:dur ctx) 1))]\n (doseq [[i k] (map-indexed vector (kids n)) :when (node? k)]\n (place k t 1 {:voice (:voice ctx) :dur d :path (conj (:path ctx) i)} acc))\n (+ t d))\n\n (block-tags tg)\n (let [ctx (cond-> ctx (:tempo a) (assoc :tempo (:tempo a)))]\n (loop [ks (map-indexed vector (kids n)) cur t end t]\n (if (empty? ks)\n (max cur end)\n (let [[i k] (first ks)]\n (if-not (node? k)\n (recur (rest ks) cur end)\n (let [ka (attrs k) c2 (assoc ctx :path (conj (:path ctx) i) :dur nil)]\n (cond\n (some? (:at ka)) (recur (rest ks) cur (max end (place k (+ t (* scale (:at ka))) scale c2 acc)))\n (#{:voice :par} (tag k)) (recur (rest ks) cur (max end (place k t scale c2 acc)))\n :else (let [e (place k cur scale c2 acc)] (recur (rest ks) e (max end e))))))))))\n\n (par-tags tg)\n (let [ctx ctx]\n (reduce (fn [end [i k]]\n (if (node? k)\n (let [at (:at (attrs k))\n s (+ t (* scale (or at 0)))\n e (place k s scale (assoc ctx :path (conj (:path ctx) i) :dur nil) acc)]\n (max end e))\n end))\n t (map-indexed vector (kids n))))\n\n (seq-tags tg)\n (let [scale (cond\n (and (= :tuplet tg) (vector? (:ratio a))) (let [[p q] (:ratio a)] (* scale (/ q p)))\n :else scale)\n voice (if (= :voice tg) (or (:name a) (:id a) (str \"v\" (count (:path ctx)) \"-\" (last (:path ctx)))) (:voice ctx))]\n (loop [ks (map-indexed vector (kids n)) cur t prev nil]\n (if (empty? ks)\n cur\n (let [[i k] (first ks)]\n (if-not (node? k)\n (recur (rest ks) cur prev)\n (let [ka (attrs k)\n durable (and (#{:note :rest :chord} (tag k)) (not (:grace ka)))\n prev (if (and durable (:dur ka)) (:dur ka) prev)\n c2 {:voice voice :dur (when durable prev) :path (conj (:path ctx) i) :tempo (:tempo ctx)}]\n (if (some? (:at ka))\n (do (place k (+ t (* scale (:at ka))) scale c2 acc) (recur (rest ks) cur prev))\n (recur (rest ks) (place k cur scale c2 acc) prev))))))))\n\n :else t)))\n\n(defn- join-ties\n \"Events in time order with every tied note (:tie) joined to the note it goes on in: the next note of\n its voice with the same pitch that starts where it ends. One sound, one event (it keeps the first's keys).\"\n [evs]\n (let [same? (fn [a b] (< (js/Math.abs (- a b)) 1e-6))]\n (loop [es evs out (transient []) open {}]\n (if (empty? es)\n (mapv (fn [e] (if (= :note (:kind e)) (dissoc e :tie) e)) (persistent! out))\n (let [e (first es)]\n (if-not (and (= :note (:kind e)) (not (:grace e)))\n (recur (rest es) (conj! out e) open)\n (let [k [(:voice e) (cv/round-to (:pitch e) 4)]\n [i end] (get open k)]\n (if (and i (same? end (:t e)))\n (let [prev (nth out i)\n joined (assoc prev :dur (cv/round-to (+ (:dur prev) (:dur e)) 6))]\n (recur (rest es) (assoc! out i joined)\n (if (:tie e) (assoc open k [i (+ (:t e) (:dur e))]) (dissoc open k))))\n (let [idx (count out)]\n (recur (rest es) (conj! out e)\n (if (:tie e) (assoc open k [idx (+ (:t e) (:dur e))]) (dissoc open k))))))))))))\n\n(defn events\n \"The flat list of events of a tree, in time order: {:kind :note|:param|:dyn|:text, :t :dur (beats),\n :pitch (MIDI) for notes, :voice, :path (where it is in the tree), and every other key of the node}.\"\n [tree]\n (let [t (expand tree) acc (transient [])]\n (place t 0 1 {:path [] :voice nil} acc)\n (->> (persistent! acc)\n (map (fn [e] (-> e (update :t cv/round-to 6) (update :dur cv/round-to 6))))\n (sort-by (juxt :t (fn [e] (- (or (:pitch e) 0)))))\n join-ties)))\n\n(defn duration \"How long a tree lasts, in beats.\" [tree]\n (let [t (expand tree) acc (transient [])] (cv/round-to (place t 0 1 {:path []} acc) 6)))\n\n(defn tempo-of [tree] (or (:tempo (attrs (expand tree))) 60))\n\n(defn notes [tree] (filterv (fn [e] (= :note (:kind e))) (events tree)))\n\n(defn pitches \"The pitches, in time order: as they are written (names), or names for whole numbers.\" [tree]\n (mapv (fn [e] (if (and (:name e) (== (:pitch e) (js/Math.round (:pitch e)))) (:name e) (pitch-name (:pitch e)))) (notes tree)))\n\n(defn summary [tree]\n (try\n (let [es (events tree) ns (filter (fn [e] (= :note (:kind e))) es)\n vs (count (distinct (keep :voice ns)))]\n (str (count ns) \" notes\" (when (> vs 1) (str \" · \" vs \" voices\")) \" · \" (cv/fmt (duration tree)) \" beats\"\n (let [k (count (remove (fn [e] (= :note (:kind e))) es))] (when (pos? k) (str \" · \" k \" marks\")))))\n (catch :default e (str \"error: \" (.-message e)))))\n\n;; ───────── checking ─────────\n\n(defn problems\n \"What is wrong in a tree (unknown tags, notes without pitch, measures that do not add up): a list of texts.\"\n [tree]\n (let [out (atom [])\n say (fn [& xs] (swap! out conj (apply str xs)))]\n (letfn [(go [n path]\n (cond\n (string? n) (try (melody n) (catch :default e (say (.-message e))))\n (not (node? n)) (say \"not a node at \" (pr-str path) \": \" (pr-str n))\n :else\n (let [tg (tag n)\n a (if (= :measure tg)\n (try (with-meter-attrs (attrs n))\n (catch :default e (say (.-message e) \" at \" (pr-str path)) (dissoc (attrs n) :meter)))\n (attrs n))]\n (when-not (known-tags tg) (say \"unknown tag \" tg \" at \" (pr-str path)))\n (when (and (= :note tg) (nil? (midi-of a))) (say \"a note without a pitch I understand at \" (pr-str path) \": \" (pr-str a)))\n (when (and (:dur a) (not (and (number? (:dur a)) (>= (:dur a) 0)))) (say \"a duration is a number of beats at \" (pr-str path)))\n (when (and (= :measure tg) (vector? (:meter a)))\n (let [[p q] (:meter a) want (* p (/ 4 q))\n ;; the measure itself, so that an :rtm in it fills its meter\n got (try (duration (make :measure (dissoc a :at) (kids n))) (catch :default _ nil))]\n (when (and got (> (js/Math.abs (- got want)) 1e-6))\n (say \"measure \" (pr-str path) \" lasts \" (cv/fmt got) \" beats; its meter \" p \"/\" q \" asks for \" (cv/fmt want)))))\n (doseq [[i k] (map-indexed vector (kids n))] (go k (conj path i))))))]\n (go tree [])\n ;; groups must add up to the meter they group (inherited meters included)\n (letfn [(gs [n path]\n (when (node? n)\n (let [{[p q] :meter g :groups} (attrs n)]\n (when (and (= :measure (tag n)) (seq g))\n (cond (not (every? (fn [x] (and (number? x) (pos? x) (== x (js/Math.round x)))) g))\n (say \"groups are whole numbers of units, at \" (pr-str path) \": \" (pr-str g))\n (not= p (reduce + g))\n (say \"groups \" (pr-str g) \" at \" (pr-str path) \" add up to \" (reduce + g) \"; the meter \" p \"/\" q \" has \" p \" units\"))))\n (doseq [[i k] (map-indexed vector (kids n))] (gs k (conj path i)))))]\n (when (empty? @out) (try (gs (with-meters tree) []) (catch :default e (say (.-message e))))))\n (when (empty? @out)\n (try (expand tree) (catch :default e (say (.-message e))))))\n @out))\n\n(defn warning? \"A problem that does not stop the tree from being read and played (a measure that does not add up).\" [msg]\n (str/starts-with? msg \"measure \"))\n\n(defn errors \"The problems that make a tree unusable.\" [t] (vec (remove warning? (problems t))))\n(defn warnings \"The problems a tree can live with while it is being written.\" [t] (vec (filter warning? (problems t))))\n\n;; ───────── reading (EDN text → tree) and writing (tree → text) ─────────\n\n(defn read-tree\n \"EDN text → tree (one form; several become a :seq). Only reads data: nothing is evaluated.\"\n [text]\n (let [forms (edn/read-string (str \"[\" text \"\\n]\"))]\n (cond (empty? forms) nil\n (= 1 (count forms)) (first forms)\n :else (into [:seq] forms))))\n\n(defn pp\n \"A tree as text, one container per line, indented.\"\n ([tree] (pp tree 0))\n ([n depth]\n (if-not (node? n)\n (pr-str n)\n (let [a (attrs n) ks (kids n)\n head (str \"[\" (pr-str (tag n)) (when (seq a) (str \" \" (pr-str a))))\n nested? (some (fn [k] (and (node? k) (seq (kids k)))) ks)]\n (if (or (not nested?) (empty? ks))\n (str head (apply str (map (fn [k] (str \" \" (pp k 0))) ks)) \"]\")\n (str head\n (apply str (map (fn [k] (str \"\\n\" (apply str (repeat (inc depth) \" \")) (pp k (inc depth)))) ks))\n \"]\"))))))\n\n;; ───────── conversions: canvas, freqt, score ─────────\n\n(defn ->strokes\n \"A tree as freqt data: one stroke per note (Hz over beats), with its glissando and its :look (weight,\n gradient, texture, colour), if the note has one.\"\n [tree]\n (let [ns (notes tree)]\n {:strokes (into {}\n (for [[i e] (map-indexed vector ns)\n :let [t0 (:t e) d (max 0.01 (:dur e)) hz (cv/midi->hz (:pitch e))\n g (or (:gliss e) [[0 0] [1 0]])\n g (if (< (count g) 2) [[0 0] [1 0]] g)]]\n [(keyword (str \"t\" (inc i)))\n (cv/with-look {:pts (mapv (fn [[x c]] [(cv/round-to (+ t0 (* d x)) 4) (cv/round-to (cv/cents->hz c hz) 3)]) g)}\n (:look e))]))\n :gx nil :gy nil}))\n\n(defn ->canvas\n \"A tree as data for a generic canvas: time along X, pitch along a log Y.\"\n [tree]\n (let [d (->strokes tree)\n ys (mapcat (fn [[_ s]] (map second (:pts s))) (:strokes d))\n lo (if (seq ys) (/ (apply min ys) 1.2) 100) hi (if (seq ys) (* (apply max ys) 1.2) 1000)]\n (assoc d :ax {:x {:lo 0 :hi (max 1 (duration tree)) :log false} :y {:lo lo :hi hi :log true}})))\n\n(defn <-strokes\n \"Freqt (or canvas) data as a tree: one note per stroke, placed with :at; bends become :gliss.\"\n [d]\n (into [:voice {:name \"strokes\"}]\n [(into [:par]\n (for [[_ s] (cv/sorted-strokes d)\n :let [pts (:pts s) [t0 f0] (first pts) [t1 _] (peek pts)\n m (cv/hz->midi f0) mr (js/Math.round m)\n dur (max 0.01 (- t1 t0))\n g (mapv (fn [[t f]] [(cv/round-to (/ (- t t0) dur) 3) (cv/round-to (cv/hz->cents f (cv/midi->hz mr)) 1)]) pts)\n flat? (every? (fn [[_ c]] (< (js/Math.abs (- c (second (first g)))) 1)) g)]]\n [:note (cond-> {:at (cv/round-to t0 4) :dur (cv/round-to dur 4)\n :pitch (if (< (js/Math.abs (- m mr)) 0.02) (pitch-name mr) (cv/round-to m 2))}\n (not flat?) (assoc :pitch (pitch-name mr) :gliss g))]))]))\n\n(defn ->voice\n \"A tree as the voice data kairotic.score draws approximately (a sixteenth grid).\"\n [tree]\n (let [ns (notes tree)]\n {:tempo (tempo-of tree) :meter [4 4]\n :events (into {} (for [[i e] (map-indexed vector ns)\n :let [m (:pitch e) mr (js/Math.round m) dv (js/Math.round (* 100 (- m mr)))]]\n [(keyword (str \"e\" (inc i)))\n (cond-> {:t (:t e) :pitch (max 0 (min 127 mr)) :dur (max 0.25 (:dur e))}\n (>= (js/Math.abs dv) 5) (assoc :txt (str (when (pos? dv) \"+\") dv)))]))}))\n\n;; ───────── measured notation (MEI) ─────────\n;; When a voice is written in :measure nodes, each one becomes a bar: notes, rests, chords and tuplets\n;; as written, with dynamics, articulations and texts. Outside tuplets each value is written where the\n;; beats can be seen (metric-split); :tie and :grace notes are written as ties and grace notes. A tree\n;; without measures (or a freqt's strokes) is first quantized into measures by kairotic.quantize.\n\n(def mei-durs [[8 \"breve\" 0] [6 \"1\" 1] [4 \"1\" 0] [3 \"2\" 1] [2 \"2\" 0] [1.5 \"4\" 1] [1 \"4\" 0] [0.75 \"8\" 1] [0.5 \"8\" 0]\n [0.375 \"16\" 1] [0.25 \"16\" 0] [0.1875 \"32\" 1] [0.125 \"32\" 0] [0.0625 \"64\" 0]])\n\n(declare split-dur)\n\n(defn written-value\n \"The single written value (plain or dotted) that lasts d beats, as [beats mei-dur dots], or nil.\"\n [d]\n (first (filter (fn [[b]] (< (js/Math.abs (- b d)) 1e-6)) mei-durs)))\n\n(defn metric-split\n \"How a note (or a rest) of d beats that starts at pos (beats from the start of its bar) is written:\n written values [beats mei-dur dots] …, tied, cut where the meter has to be seen. bounds are where the\n beats (or groups) of the bar start, from its start. A note may run over a beat when it starts at least\n as strong as every beat it covers (a half note on the downbeat of 4/4, a dotted quarter on beat 2 of\n 3/4) or, not a rest, as a syncopation centred on one beat and as long as that beat's unit (eighth –\n quarter – eighth; quarter – half – quarter). Inside a beat any written value goes (a sixteenth and a\n dotted eighth). In a simple meter a rest over a beat is not dotted.\"\n [meter bounds pos d rest?]\n (let [{[p q] :meter g :groups :as m} (meter-of meter)\n bar (* p (/ 4 q))\n eps 1e-6\n lv (fn [x] (meter-level m x))\n bs (vec (sort (filter (fn [b] (< eps b (- bar eps))) bounds)))\n ends (conj bs bar)\n unit-at (fn [b] (- (or (first (filter (fn [x] (and (> x (+ b eps)) (<= (lv x) (lv b)))) ends)) bar) b))\n simple? (and (<= q 4) (empty? g))\n allowed? (fn [a e]\n (let [wv (written-value (- e a))\n crossed (filter (fn [b] (< (+ a eps) b (- e eps))) bs)]\n (and wv\n (or (empty? crossed)\n (and (every? (fn [b] (<= (lv a) (lv b))) crossed)\n (not (and rest? simple? (pos? (nth wv 2)))))\n (and (not rest?) (= 1 (count crossed))\n (let [b (first crossed)]\n (and (< (js/Math.abs (- (- b a) (- e b))) eps)\n (< (js/Math.abs (- (- e a) (unit-at b))) eps))))))))]\n (if (or (> (+ pos d) (+ bar eps)) (neg? pos))\n (split-dur d)\n (loop [a pos out []]\n (let [left (- (+ pos d) a)]\n (if (or (< left 0.03) (> (count out) 16))\n (if (empty? out) (split-dur d) out)\n (let [e (+ a left)\n hit (first (filter (fn [x] (allowed? a x))\n (cons e (reverse (filter (fn [b] (< (+ a eps) b (- e eps))) bs)))))]\n (if hit\n (recur hit (conj out (written-value (- hit a))))\n ;; nothing written reaches a beat: the longest value that fits before the next one\n (let [nb (min e (or (first (filter (fn [b] (> b (+ a eps))) bs)) e))\n [b du dots] (or (first (filter (fn [[b]] (<= b (+ (- nb a) eps))) mei-durs)) (peek mei-durs))]\n (recur (+ a b) (conj out [b du dots])))))))))))\n\n(defn split-dur\n \"A duration in beats as written values ([beats mei-dur dots] …), tied when it needs more than one.\"\n [d]\n (loop [left d out []]\n (if (or (< left 0.03) (> (count out) 8))\n (if (empty? out) [[d \"64\" 0]] out)\n (let [[b du dots] (or (first (filter (fn [[b]] (<= b (+ left 1e-6))) mei-durs)) (peek mei-durs))]\n (recur (- left b) (conj out [b du dots]))))))\n\n(def artic-names {:staccato \"stacc\" :accent \"acc\" :tenuto \"ten\" :marcato \"marc\" :staccatissimo \"stacciss\"\n :fermata nil :spiccato \"spicc\" :up-bow \"upbow\" :down-bow \"dnbow\"})\n\n(defn esc-xml [s] (-> (str s) (str/replace \"&\" \"&\") (str/replace \"<\" \"<\") (str/replace \"\\\"\" \""\")))\n\n(defn measured? [tree] (boolean (some (fn [x] (and (node? x) (= :measure (tag x)))) (tree-seq node? kids (expand tree)))))\n\n(defn voices-of\n \"The voices of a tree: its :voice nodes, or the whole tree as one voice.\"\n [t]\n (let [vs (filter (fn [x] (and (node? x) (= :voice (tag x)))) (tree-seq node? kids t))]\n (if (seq vs) (vec vs) [[:voice t]])))\n\n(defn measures-of [v]\n (letfn [(go [n] (cond (not (node? n)) []\n (= :measure (tag n)) [n]\n :else (mapcat go (kids n))))]\n (vec (go v))))\n\n;; ───────── spelling: names for notes written as numbers (issue #88) ─────────\n\n(declare update-at node-at)\n\n(defn key-times\n \"Where a tree says its key: [[beat key] …] — the :key of the tree (or of a section or voice) from 0,\n and a measure's :key from where that measure starts (in the first voice).\"\n [t]\n (let [t (with-meters t)\n root (some (fn [x] (when (and (node? x) (not= :measure (tag x)) (some? (:key (attrs x)))) (:key (attrs x))))\n (tree-seq node? kids t))\n ms (measures-of (first (voices-of t)))\n starts (reductions + 0 (map (fn [m] (let [[p q] (or (:meter (attrs m)) [4 4])] (* p (/ 4 q)))) ms))]\n (vec (concat (when (some? root) [[0 root]])\n (keep (fn [[m st]] (when (some? (:key (attrs m))) [st (:key (attrs m))])) (map vector ms starts))))))\n\n(defn- note-base\n \"The integer pitch a note is written from, and what is left in cents: 60.5 → [60 50] (a quarter tone\n above), 60.3 → [60 30], 60.7 → [61 -30].\"\n [m]\n (let [f (js/Math.floor m) frac (- m f)\n b (if (< (js/Math.abs (- frac 0.5)) 0.08) f (js/Math.round m))]\n [b (js/Math.round (* 100 (- m b)))]))\n\n(defn spellings-for\n \"Names for the notes of an expanded tree that have none (numbers, Hz), chosen by kairotic.spell:\n {path spelling} (paths as mt/events gives them). The key is the tree's (key-times) where it says it;\n where not, it is estimated bar by bar (or every 4 beats) from the notes around.\"\n [t]\n (let [evs (filterv (fn [e] (= :note (:kind e))) (events t))]\n (if (empty? evs)\n {}\n (let [kt (key-times t)\n bar-len (if-let [m (first (measures-of (first (voices-of (with-meters t)))))]\n (let [[p q] (or (:meter (attrs m)) [4 4])] (* p (/ 4 q)))\n 4)\n ;; a key is only estimated from four pitch classes or more that fit one clearly: around the bar,\n ;; else the whole tree, else none (C)\n;; each note counts once, however long (Temperley's flat input)\n weights (fn [es] (reduce (fn [v e] (update v (mod (first (note-base (:pitch e))) 12) + 1))\n (vec (repeat 12 0)) es))\n enough? (fn [w] (>= (count (filter pos? w)) 4))\n whole (let [w (weights evs)] (if (enough? w) (or (sp/estimate-sig w) 0) 0))\n estimated (fn [t0]\n (let [w (weights (filter (fn [e] (and (< (:t e) (+ t0 (* 1.5 bar-len))) (> (+ (:t e) (:dur e)) (- t0 (* 0.5 bar-len))))) evs))]\n (if (enough? w) (or (sp/estimate-sig w) whole) whole)))\n sig-at (memoize (fn [bar]\n (let [t0 (* bar bar-len)\n k (last (filter (fn [[b _]] (<= b (+ t0 1e-6))) kt))]\n (if k (or (:sig (sp/parse-key (second k))) 0) (estimated t0)))))\n steps (->> evs\n (group-by (fn [e] (cv/round-to (:t e) 4)))\n (sort-by key)\n (mapv (fn [[t0 es]]\n {:sig (sig-at (js/Math.floor (/ (+ t0 1e-6) bar-len)))\n :notes (mapv (fn [e] (let [a (attrs (node-at t (:path e)))]\n {:id (:path e) :voice (:voice e)\n :midi (first (note-base (:pitch e)))\n :fixed (spelling-of a)}))\n es)})))]\n (into {} (remove (fn [[p _]] (spelling-of (attrs (node-at t p)))) (sp/spell-steps steps)))))))\n\n(defn spell\n \"The tree with names for its notes written as numbers: 61 → \\\"c#4\\\" or \\\"db4\\\", by the key and the line\n (kairotic.spell); a quarter tone keeps it as :cents (60.5 → \\\"c4\\\" :cents 50). Names already written,\n and notes in Hz, stay as they are.\"\n [tree]\n (let [t (expand tree)\n names (spellings-for t)]\n (reduce (fn [t [path s]]\n (update-at t path (fn [n] (let [a (attrs n)]\n (if (number? (:pitch a))\n (let [[_ c] (note-base (:pitch a))]\n (with-attrs n (cond-> (assoc a :pitch (sp/->name s)) (not (zero? c)) (assoc :cents c))))\n n)))))\n t names)))\n\n(defn ->mei\n \"Measured notation of a tree. Returns {:mei text :pieces [{:id :t :staff}]} (ids → beats, for cursors).\"\n [tree pre]\n (let [t (with-meters (explicit (expand tree)))\n ;; names for the notes written as numbers (kairotic.spell), beside their pitch: :spelled\n t (reduce (fn [t [path s]] (update-at t path (fn [n] (update-attrs n assoc :spelled (sp/->name s)))))\n t (spellings-for t))\n ;; the work in sections (or one), each with its voices; a voice is a staff, by name, across sections\n sections (letfn [(go [n] (cond (not (node? n)) []\n (= :section (tag n)) [n]\n :else (mapcat go (kids n))))]\n (let [ss (vec (go t))] (if (seq ss) ss [t])))\n sec-voices (mapv (fn [sc] (vec (map-indexed (fn [i v] [(or (:name (attrs v)) (str \"voice \" (inc i))) v]) (voices-of sc))))\n sections)\n ;; a voice is a staff, or a layer of one: voices with the same :staff share it (layer 1, 2 …)\n voice-staff (reduce (fn [m [k v]] (if (contains? m k) m (assoc m k (str (or (:staff (attrs v)) k)))))\n {} (apply concat sec-voices))\n voice-order (vec (distinct (mapcat (fn [vs] (map first vs)) sec-voices)))\n staves (vec (distinct (map voice-staff voice-order)))\n layers-of (into {} (for [sk staves] [sk (filterv (fn [k] (= sk (voice-staff k))) voice-order)]))\n staff-of (zipmap staves (map inc (range)))\n cur-layer (atom 1)\n bar-list (vec (mapcat (fn [si vs]\n (let [mss (mapv (fn [[k v]] [k (measures-of v)]) vs)\n n (reduce max 1 (map (comp count second) mss))]\n (for [i (range n)]\n {:cells (into {} (for [[k ms] mss :let [m (get ms i)] :when m] [k m]))\n :label (when (and (zero? i) (> (count sections) 1)) (:name (attrs (nth sections si))))\n :end (and (= i (dec n)) (< si (dec (count sections))))})))\n (range) sec-voices))\n nbars (count bar-list)\n ;; [meter groups] of a bar (every measure carries them: with-meters)\n mg-at (fn [i] (or (some (fn [j] (some (fn [m] (let [a (attrs m)] (when (:meter a) [(:meter a) (seq (:groups a))])))\n (vals (:cells (nth bar-list j)))))\n (reverse (range (inc (max 0 (min i (dec nbars)))))))\n [[4 4] nil]))\n meter-at (fn [i] (first (mg-at i)))\n ;; the key of a bar: a measure's :key from there on, else the tree's (or a section's, a voice's);\n ;; :none, or :accidentals :every anywhere above the measures, writes every accidental\n root-key (some (fn [x] (when (and (node? x) (not= :measure (tag x)) (some? (:key (attrs x)))) (:key (attrs x))))\n (tree-seq node? kids t))\n every-all (boolean (some (fn [x] (and (node? x) (#{:every \"every\"} (:accidentals (attrs x))))) (tree-seq node? kids t)))\n key-at (memoize (fn [i] (let [raw (or (some (fn [j] (some (fn [m] (:key (attrs m))) (vals (:cells (nth bar-list j)))))\n (reverse (range (inc (max 0 (min i (dec nbars)))))))\n root-key)\n k (sp/parse-key raw)]\n {:sig (or (:sig k) 0) :every (or every-all (boolean (:none k)))})))\n ;; a grouped meter is written as its groups: 2+3/8\n meter-count (fn [i] (let [[[p _] g] (mg-at i)] (if g (str/join \"+\" g) p)))\n counter (atom 0)\n nid (fn [] (str \"m-\" pre (swap! counter inc)))\n pieces (atom [])\n ctrl (atom {}) ; bar → control events (dynam, dir, hairpin, tie)\n ctl! (fn [bar x] (swap! ctrl update bar (fnil conj []) x))\n acc-mem (atom {}) ; [staff bar] → {[step oct] alteration shown}\n open-gliss (atom {}) ; [staff layer] → {:id :bar :end :c} of a note that bends into the next\n gliss-dir (fn [staff gl] (str \"<dir staff=\\\"\" staff \"\\\" startid=\\\"#\" (:id gl) \"\\\" place=\\\"above\\\"><rend fontstyle=\\\"italic\\\">gliss. \"\n (if (pos? (:c gl)) \"↗ +\" \"↘ \") (js/Math.round (:c gl)) \"¢</rend></dir>\"))\n open-ties (atom {}) ; [staff layer pitch] → [id bar] of a note tied (:tie) to the next one\n bar-start (atom {})\n _ (reduce (fn [acc i] (swap! bar-start assoc i acc) (let [[p q] (meter-at i)] (+ acc (* p (/ 4 q))))) 0 (range (inc nbars)))\n tstamp (fn [bar beat] (let [[_ q] (meter-at bar)] (cv/round-to (inc (* beat (/ q 4))) 4)))\n ;; where beams may run in a bar: its groups, or its beats (dotted in 6/8, 9/8, 12/8; the whole\n ;; bar in 2/8 and 3/8), as [start end] in absolute beats\n beam-spans (fn [i]\n (let [[[p q] g] (mg-at i) u (/ 4 q) len (* p u)\n lens (cond g (map (fn [k] (* k u)) g)\n (<= q 4) (repeat (js/Math.ceil len) 1)\n (and (zero? (mod p 3)) (> p 3)) (repeat (quot p 3) (* 3 u))\n (<= p 3) [len]\n :else (concat (repeat (js/Math.floor len) 1)\n (let [r (- len (js/Math.floor len))] (when (> r 1e-9) [r]))))\n starts (reductions + (get @bar-start i) lens)]\n (vec (map vector starts (rest starts)))))\n ;; consecutive notes and chords of an eighth or shorter, inside one span, under one <beam>\n beam-join (fn [items spans]\n (let [inside (fn [x] (if (= spans :all)\n 0\n (first (keep-indexed (fn [i [s0 e0]]\n (when (and (> (:t0 x) (- s0 1e-6)) (< (:t0 x) (- e0 1e-6))\n (<= (:t1 x) (+ e0 1e-6)))\n i))\n spans))))\n flush-run (fn [out run] (if (>= (count run) 2)\n (str out \"<beam>\" (apply str (map :xml run)) \"</beam>\")\n (str out (apply str (map :xml run)))))]\n (loop [xs items run [] sp nil out \"\"]\n (if (empty? xs)\n (flush-run out run)\n (let [x (first xs) i (when (:beam x) (inside x))]\n (cond\n (nil? i) (recur (rest xs) [] nil (str (flush-run out run) (:xml x)))\n (or (empty? run) (= i sp)) (recur (rest xs) (conj run x) i out)\n :else (recur (rest xs) [x] i (flush-run out run))))))))\n where (fn [abs] ; absolute beat → [bar beat-in-bar]\n (let [bar (or (last (filter (fn [i] (<= (get @bar-start i) (+ abs 1e-6))) (range nbars))) 0)]\n [bar (- abs (get @bar-start bar))]))\n note-xml (fn [a staff abs id durattr art? src]\n (let [m (midi-of a)\n [b _] (where abs)\n {:keys [sig every]} (key-at b)\n ;; the written name (or the one spell chose), and what is left of the pitch in cents\n written (or (spelling-of a) (sp/parse (:spelled a)))\n [base dv] (if written\n [written (js/Math.round (* 100 (- m (sp/->midi written))))]\n (let [[bm c] (note-base m)]\n [(first (sort-by (fn [x] (js/Math.abs (- (sp/fifths x) (sp/key-center sig)))) (sp/spellings bm))) c]))\n ;; half-way between two semitones (± 8 cents): a quarter-tone accidental\n qtr (cond (< (js/Math.abs (- dv 50)) 8) 1 (< (js/Math.abs (+ dv 50)) 8) -1)\n dv (- dv (* 50 (or qtr 0)))\n alter (:alter base)\n sym (if qtr\n (get {[0 1] \"1qs\" [1 1] \"3qs\" [-1 1] \"1qf\" [-2 1] \"3qf\" [0 -1] \"1qf\" [-1 -1] \"3qf\" [1 -1] \"1qs\" [2 -1] \"3qs\"} [alter qtr])\n (get {2 \"x\" 1 \"s\" 0 \"n\" -1 \"f\" -2 \"ff\"} alter))\n ;; an accidental lasts to the end of the bar, for its staff, step and octave: shown when\n ;; it changes what the key (or the bar so far) says, and as a courtesy after a bar that\n ;; changed it; not on a note a tie goes on into\n k [(:step base) (:oct base)]\n cont? (or (not art?) (contains? @open-ties [staff @cur-layer (cv/round-to m 3)]))\n here (get-in @acc-mem [[staff b] k])\n before (get-in @acc-mem [[staff (dec b)] k])\n state (if qtr [alter qtr] alter)\n expected (if (some? here) here (sp/key-alter sig (:step base)))\n show? (cond cont? false\n qtr true\n every (or (not (zero? alter)) (not= alter (sp/key-alter sig (:step base))))\n (not= state expected) true\n (and (nil? here) (some? before) (not= before state)) true\n :else false)\n _ (swap! acc-mem assoc-in [[staff b] k] state)\n arts (when art? (let [x (:art a) xs (if (sequential? x) x (when x [x]))]\n (seq (keep (fn [k] (get artic-names (keyword k))) xs))))]\n (swap! pieces conj {:id id :t abs :staff staff :src src :midi m :name (sp/->name base)})\n (str \"<note xml:id=\\\"\" id \"\\\" pname=\\\"\" (sp/letters (:step base)) \"\\\" oct=\\\"\" (:oct base) \"\\\"\"\n (cond show? (str \" accid=\\\"\" sym \"\\\"\")\n (and sym (not= sym \"n\")) (str \" accid.ges=\\\"\" sym \"\\\"\"))\n durattr\n (when arts (str \" artic=\\\"\" (str/join \" \" arts) \"\\\"\"))\n (if (>= (js/Math.abs dv) 5)\n (str \"><verse n=\\\"1\\\"><syl>\" (when (pos? dv) \"+\") dv \"</syl></verse></note>\")\n \"/>\"))))\n marks! (fn [a staff bar id]\n (when-let [d (:dyn a)] (ctl! bar (str \"<dynam staff=\\\"\" staff \"\\\" startid=\\\"#\" id \"\\\">\" (esc-xml d) \"</dynam>\")))\n (when-let [x (:text a)] (ctl! bar (str \"<dir staff=\\\"\" staff \"\\\" startid=\\\"#\" id \"\\\"><rend fontstyle=\\\"italic\\\">\" (esc-xml x) \"</rend></dir>\"))))\n ;; writes the children of a container; scale converts written beats to sounding beats (tuplets);\n ;; spans: where beams may run (:all inside a tuplet)\n layer (fn layer [ks staff bar abs scale spans]\n (loop [ks ks abs abs items []]\n (if (empty? ks)\n [(beam-join items spans) abs]\n (let [k (first ks) a (attrs k) tg (tag k)]\n (cond\n (not (node? k)) (recur (rest ks) abs items)\n (mark-tags tg)\n (let [[b beat] (where abs)]\n (case tg\n :dyn (let [mk (str (:mark a))]\n (if (#{\"<\" \">\"} mk)\n (let [[b2 beat2] (where (+ abs (* scale (or (:dur a) 1))))]\n (ctl! b (str \"<hairpin staff=\\\"\" staff \"\\\" form=\\\"\" (if (= \"<\" mk) \"cres\" \"dim\") \"\\\" tstamp=\\\"\" (tstamp b beat)\n \"\\\" tstamp2=\\\"\" (- b2 b) \"m+\" (tstamp b2 beat2) \"\\\"/>\")))\n (ctl! b (str \"<dynam staff=\\\"\" staff \"\\\" tstamp=\\\"\" (tstamp b beat) \"\\\">\" (esc-xml mk) \"</dynam>\"))))\n :text (ctl! b (str \"<dir staff=\\\"\" staff \"\\\" tstamp=\\\"\" (tstamp b beat) \"\\\"><rend fontstyle=\\\"italic\\\">\" (esc-xml (:text a)) \"</rend></dir>\"))\n nil)\n (recur (rest ks) abs items))\n (= :tuplet tg)\n (let [[p q] (or (:ratio a) [3 2])\n [inner end] (layer (kids k) staff bar abs (* scale (/ q p)) :all)]\n (recur (rest ks) end\n (conj items {:t0 abs :t1 end\n :xml (str \"<tuplet num=\\\"\" p \"\\\" numbase=\\\"\" q \"\\\" bracket.visible=\\\"true\\\" num.visible=\\\"true\\\">\" inner \"</tuplet>\")})))\n (#{:seq :section :voice} tg)\n (let [[inner end] (layer (kids k) staff bar abs scale spans)]\n (recur (rest ks) end (conj items {:t0 abs :t1 end :xml inner})))\n ;; a grace note: small, before the next note, and it takes no time\n (and (= :note tg) (:grace a) (midi-of a))\n (let [id (nid)\n x (note-xml (dissoc a :art) staff abs id \" dur=\\\"8\\\" grace=\\\"unacc\\\"\" true (meta k))]\n (recur (rest ks) abs (conj items {:t0 abs :t1 abs :xml x})))\n ;; a rest that fills its bar: a bar rest\n (and (= :rest tg) (not= spans :all)\n (let [[b beat] (where abs) [[p q]] (mg-at b)]\n (and (< (js/Math.abs beat) 1e-6) (< (js/Math.abs (- (* scale (or (:dur a) 1)) (* p (/ 4 q)))) 1e-6))))\n (let [id (nid)]\n (swap! pieces conj {:id id :t abs :staff staff :src (meta k)})\n (recur (rest ks) (+ abs (* scale (or (:dur a) 1)))\n (conj items {:t0 abs :t1 abs :xml (str (if (> @cur-layer 1) \"<mSpace xml:id=\\\"\" \"<mRest xml:id=\\\"\") id \"\\\"/>\")})))\n (#{:note :rest :chord} tg)\n (let [d (or (:dur a) 1)\n [b beat] (where abs)\n ;; outside a tuplet a note is cut where the meter has to be seen\n parts (if (not= spans :all)\n (let [[mtr g] (mg-at b)]\n (metric-split (cond-> {:meter mtr} g (assoc :groups (vec g)))\n (map (fn [[s _]] (- s (get @bar-start b))) (beam-spans b))\n beat (* scale d) (= :rest tg)))\n (split-dur d))\n chord-ns (when (= :chord tg)\n (vec (filter (fn [n] (and (node? n) (= :note (tag n)) (midi-of (attrs n)))) (kids k))))\n ;; the notes of this one, with their pitches: a tie may come into them, or go on from them\n members (case tg :note [a] :chord (mapv attrs chord-ns) [])\n tie-key (fn [m] [staff @cur-layer (cv/round-to (midi-of m) 3)])\n part-items\n (loop [ps parts pabs abs prev-ids nil acc []]\n (if (empty? ps)\n (do (when prev-ids\n (doseq [[m id] (map vector members prev-ids)]\n (if (or (:tie a) (:tie m))\n (swap! open-ties assoc (tie-key m) [id b])\n (swap! open-ties dissoc (tie-key m))))\n ;; a note that bends (:gliss, more than 30 cents) glides into the next one\n (when-let [g (and (= :note tg) (not (:tie a)) (seq (:gliss a)))]\n (let [c0 (second (first g)) c1 (second (last g))]\n (when (>= (js/Math.abs (- c1 c0)) 30)\n (swap! open-gliss assoc [staff @cur-layer]\n {:id (last prev-ids) :bar b :end (+ (midi-of a) (/ c1 100)) :c (- c1 c0)})))))\n acc)\n (let [[pb du dots] (first ps)\n durattr (str \" dur=\\\"\" du \"\\\"\" (when (pos? dots) \" dots=\\\"1\\\"\"))\n first? (nil? prev-ids)\n [x ids] (case tg\n :rest (let [id (nid)] (swap! pieces conj {:id id :t pabs :staff staff :src (meta k)})\n [(str \"<rest xml:id=\\\"\" id \"\\\"\" durattr \"/>\") nil])\n :note (let [id (nid)] [(note-xml a staff pabs id durattr first? (meta k)) [id]])\n :chord (let [cid (nid)\n ns chord-ns\n ids (mapv (fn [_] (nid)) ns)]\n [(str \"<chord xml:id=\\\"\" cid \"\\\"\" durattr\n (let [x (:art a) xs (if (sequential? x) x (when x [x]))\n arts (seq (keep (fn [kk] (get artic-names (keyword kk))) xs))]\n (when (and first? arts) (str \" artic=\\\"\" (str/join \" \" arts) \"\\\"\")))\n \">\"\n (apply str (map (fn [n id] (note-xml (attrs n) staff pabs id \"\" first? (meta n))) ns ids))\n \"</chord>\")\n ids]))]\n (when (and first? (seq ids)) (marks! a staff b (first ids)))\n ;; a tie from the note before (:tie), across a barline or into a tuplet\n (when first?\n (when-let [gl (get @open-gliss [staff @cur-layer])]\n (let [hit (and (= :note tg) (seq ids) (< (js/Math.abs (- (midi-of a) (:end gl))) 0.5))]\n (ctl! (:bar gl) (if hit\n (str \"<gliss startid=\\\"#\" (:id gl) \"\\\" endid=\\\"#\" (first ids) \"\\\"/>\")\n (gliss-dir staff gl)))\n (swap! open-gliss dissoc [staff @cur-layer])))\n (doseq [[m id] (map vector members (or ids []))]\n (when-let [[s sb] (get @open-ties (tie-key m))]\n (ctl! sb (str \"<tie startid=\\\"#\" s \"\\\" endid=\\\"#\" id \"\\\"/>\"))))\n ;; a tie only goes into the very next note of its staff\n (swap! open-ties (fn [o] (into {} (remove (fn [[[st ly _] _]] (and (= st staff) (= ly @cur-layer))) o)))))\n (when (and prev-ids ids)\n (doseq [[s e] (map vector prev-ids ids)]\n (ctl! b (str \"<tie startid=\\\"#\" s \"\\\" endid=\\\"#\" e \"\\\"/>\"))))\n (recur (rest ps) (+ pabs (* scale pb)) ids\n (conj acc {:t0 pabs :t1 (+ pabs (* scale pb)) :xml x\n :beam (and (not= :rest tg) (contains? #{\"8\" \"16\" \"32\" \"64\"} du))})))))]\n (recur (rest ks) (+ abs (* scale d)) (into items part-items)))\n :else (recur (rest ks) abs items))))))\n clefs (mapv (fn [k] (let [ps (for [vs sec-voices [kk v] vs :when (= (voice-staff kk) k)\n n (tree-seq node? kids v) :when (= :note (tag n))\n :let [m (midi-of (attrs n))] :when m] m)\n mean (if (seq ps) (/ (reduce + ps) (count ps)) 64)]\n (if (< mean 57) [\"F\" 4] [\"G\" 2])))\n staves)\n ;; every bar's staves first, then the measures with their control events: a tie into the next\n ;; bar is written in the bar where it starts, once that one is done\n staff-xmls (vec (for [i (range nbars)\n :let [{:keys [cells]} (nth bar-list i)]]\n (apply str\n (for [sk staves\n :let [staff (staff-of sk)]]\n (str \"<staff n=\\\"\" staff \"\\\">\"\n (apply str\n (for [[li k] (map-indexed vector (get layers-of sk))\n :let [m (get cells k)\n _ (reset! cur-layer (inc li))\n [xml _] (if m (layer (kids m) staff i (get @bar-start i) 1 (beam-spans i)) [\"\" 0])]\n ;; a second layer with nothing in this bar is not written\n :when (or (zero? li) (seq xml))]\n (str \"<layer n=\\\"\" (inc li) \"\\\">\"\n (if (seq xml) xml (str \"<mRest xml:id=\\\"\" (nid) \"\\\"/>\"))\n \"</layer>\")))\n \"</staff>\")))))\n ;; a bend at the very end goes nowhere: a text says it\n _ (doseq [[[st _] gl] @open-gliss] (ctl! (:bar gl) (gliss-dir st gl)))\n bars (vec (for [i (range nbars)\n :let [{:keys [label end]} (nth bar-list i)]]\n (do (when (seq label)\n (ctl! i (str \"<dir staff=\\\"1\\\" tstamp=\\\"1\\\" place=\\\"above\\\"><rend fontweight=\\\"bold\\\">\" (esc-xml label) \"</rend></dir>\")))\n (str \"<measure n=\\\"\" (inc i) \"\\\"\" (when end \" right=\\\"dbl\\\"\") \">\"\n (nth staff-xmls i)\n (apply str (get @ctrl i))\n \"</measure>\"))))\n [_ q0] (meter-at 0)]\n {:mei (str \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\"\n \"<mei xmlns=\\\"http://www.music-encoding.org/ns/mei\\\" meiversion=\\\"5.0\\\">\"\n \"<meiHead><fileDesc><titleStmt><title>Kairotic</title></titleStmt><pubStmt/></fileDesc></meiHead>\"\n \"<music><body><mdiv><score>\"\n \"<scoreDef meter.count=\\\"\" (meter-count 0) \"\\\" meter.unit=\\\"\" q0 \"\\\" key.sig=\\\"\" (sp/mei-key-sig (:sig (key-at 0))) \"\\\">\"\n \"<staffGrp\" (when (> (count staves) 1) \" bar.thru=\\\"false\\\"\") \">\"\n (apply str (for [[i [shape line]] (map-indexed vector clefs)\n :let [k (nth staves i)]]\n (str \"<staffDef n=\\\"\" (inc i) \"\\\" lines=\\\"5\\\" clef.shape=\\\"\" shape \"\\\" clef.line=\\\"\" line \"\\\"\"\n (when (or (> (count staves) 1) (not (str/starts-with? k \"voice \"))) (str \" label=\\\"\" (esc-xml k) \"\\\"\"))\n \"/>\")))\n \"</staffGrp></scoreDef><section>\"\n (apply str\n (map-indexed (fn [i x]\n ;; a change of meter or key is written before its bar\n (let [mc (and (pos? i) (not= (mg-at i) (mg-at (dec i))))\n kc (and (pos? i) (not= (:sig (key-at i)) (:sig (key-at (dec i)))))]\n (if (or mc kc)\n (let [[_ q] (meter-at i)]\n (str \"<scoreDef\" (when mc (str \" meter.count=\\\"\" (meter-count i) \"\\\" meter.unit=\\\"\" q \"\\\"\"))\n (when kc (str \" key.sig=\\\"\" (sp/mei-key-sig (:sig (key-at i))) \"\\\"\")) \"/>\" x))\n x)))\n bars))\n \"</section></score></mdiv></body></music></mei>\")\n :pieces (vec (sort-by :t @pieces))}))\n\n(defn ->score\n \"MEI for a tree: measured when it has measures, an approximation on a sixteenth grid if not (kept for\n older code: kairotic.quantize/->score quantizes a tree without measures, and the page uses that one).\"\n [tree pre]\n (if (measured? tree) (->mei tree pre) (sc/->mei-voice (->voice tree) pre)))\n\n;; ───────── playing: change points for a synth and parameters ─────────\n\n(defn schedule\n \"What a player sends, in seconds: [[sec [[outlet value] …]] …]. Outlet 0: the Hz of the notes sounding\n (a list), sent after outlet 1: their ids (one voice per note, for synth~); outlet 2: parameters\n [name value] (ramps in small steps); outlet 3: marks [:dyn \\\"mf\\\"] [:text \\\"…\\\"].\"\n [tree]\n (let [k (/ 60 (tempo-of tree))\n es (events tree)\n ns (filter (fn [e] (= :note (:kind e))) es)\n nid (into {} (map-indexed (fn [i e] [e (keyword (str \"n\" (inc i)))]) ns))\n hz-at (fn [e t] (let [u (if (pos? (:dur e)) (/ (- t (:t e)) (:dur e)) 0)\n g (:gliss e)\n c (if (and g (>= (count g) 2))\n (let [[[x0 c0] [x1 c1]] (or (first (filter (fn [[[a] [b]]] (<= a u b)) (partition 2 1 g)))\n [(first g) (peek g)])]\n (if (= x0 x1) c1 (+ c0 (* (- c1 c0) (/ (- u x0) (- x1 x0))))))\n 0)]\n (cv/round-to (cv/cents->hz c (cv/midi->hz (:pitch e))) 3)))\n points (sort (distinct (concat (mapcat (fn [e] (concat [(:t e) (+ (:t e) (:dur e))]\n (when (:gliss e) (map (fn [[x]] (+ (:t e) (* x (:dur e)))) (:gliss e)))))\n ns)\n [0])))\n sound (for [t points\n :let [on (filter (fn [e] (and (<= (:t e) (+ t 1e-9)) (< (+ t 1e-9) (+ (:t e) (:dur e))))) ns)]]\n [(* k t) [[1 (mapv nid on)] [0 (mapv (fn [e] (hz-at e t)) on)]]])\n params (mapcat (fn [e]\n (let [nm (:name e) v0 (:value e) v1 (:to e) d (:dur e)]\n (if (and (number? v0) (number? v1) (pos? d))\n (for [i (range 21)] [(* k (+ (:t e) (* d (/ i 20)))) [[2 [nm (cv/round-to (+ v0 (* (- v1 v0) (/ i 20))) 4)]]]])\n [[(* k (:t e)) [[2 [nm v0]]]]])))\n (filter (fn [e] (= :param (:kind e))) es))\n marks (for [e es :when (#{:dyn :text} (:kind e))]\n [(* k (:t e)) [[3 [(:kind e) (or (:mark e) (:text e))]]]])]\n (->> (concat sound params marks)\n (group-by first)\n (sort-by key)\n (mapv (fn [[t xs]] [t (vec (mapcat second xs))])))))\n\n;; ───────── editing: operations on paths, and the difference between two trees ─────────\n;; A path is the list of child indices from the root ([] is the root; attributes are not counted).\n;; These operations are the events of a tree box's history (Study 20), so an edit is one node:\n;; [:set path x] replaces the node (or string) at path\n;; [:attrs path {…}] replaces its attributes\n;; [:insert path x] inserts x so that it ends up at path\n;; [:remove path] removes the node at path\n\n(defn node-at \"The node (or string) at path, or nil.\" [t path]\n (reduce (fn [n i] (when (and (node? n) (integer? i)) (get (kids n) i))) t path))\n\n(defn- update-at [t path f]\n (if (empty? path)\n (f t)\n (let [i (first path) ks (kids t)]\n (if (and (node? t) (integer? i) (< -1 i (count ks)))\n (with-kids t (assoc ks i (update-at (get ks i) (rest path) f)))\n (throw (js/Error. (str \"no node at \" (pr-str path))))))))\n\n(defn apply-op\n \"The tree after one edit operation (or an error if its path does not exist).\"\n [t [op path x]]\n (let [path (vec path)]\n (case op\n :set (update-at t path (constantly x))\n :attrs (update-at t path (fn [n] (if (node? n) (with-attrs n (or x {})) n)))\n :insert (do (when (empty? path) (throw (js/Error. \"insert needs a parent\")))\n (update-at t (pop path)\n (fn [n] (let [ks (kids n) i (max 0 (min (peek path) (count ks)))]\n (with-kids n (into (conj (subvec ks 0 i) x) (subvec ks i)))))))\n :remove (do (when (empty? path) (throw (js/Error. \"the root cannot be removed\")))\n (update-at t (pop path)\n (fn [n] (let [ks (kids n) i (peek path)]\n (if (< -1 i (count ks)) (with-kids n (into (subvec ks 0 i) (subvec ks (inc i)))) n)))))\n (throw (js/Error. (str \"unknown edit \" (pr-str op)))))))\n\n(defn- lcs-pairs\n \"Pairs [i j] of equal elements of a and b, in order (longest common subsequence).\"\n [a b]\n (let [n (count a) m (count b)\n dp (make-array (* (inc n) (inc m)))\n at (fn [i j] (or (aget dp (+ (* i (inc m)) j)) 0))]\n (doseq [i (range (dec n) -1 -1) j (range (dec m) -1 -1)]\n (aset dp (+ (* i (inc m)) j)\n (if (= (nth a i) (nth b j)) (inc (at (inc i) (inc j))) (max (at (inc i) j) (at i (inc j))))))\n (loop [i 0 j 0 out []]\n (cond (or (>= i n) (>= j m)) out\n (= (nth a i) (nth b j)) (recur (inc i) (inc j) (conj out [i j]))\n (>= (at (inc i) j) (at i (inc j))) (recur (inc i) j out)\n :else (recur i (inc j) out)))))\n\n(declare diff)\n\n(defn- diff-kids [a b path]\n (let [anchors (lcs-pairs a b)\n bounds (concat [[-1 -1]] anchors [[(count a) (count b)]])\n segments (map (fn [[[i0 j0] [i1 j1]]] [(inc i0) i1 (inc j0) j1]) (partition 2 1 bounds))]\n ;; from right to left, so that the indices of what is still to do do not move\n (vec (mapcat (fn [[os oe ns ne]]\n (let [olds (subvec a os oe) news (subvec b ns ne) k (min (count olds) (count news))]\n (concat\n (for [i (range (dec (count olds)) (dec k) -1)] [:remove (conj path (+ os i))])\n (for [i (range k (count news))] [:insert (conj path (+ os i)) (nth news i)])\n (mapcat (fn [i] (diff (nth olds i) (nth news i) (conj path (+ os i)))) (range (dec k) -1 -1)))))\n (reverse segments)))))\n\n(defn diff\n \"The edit operations that turn tree a into tree b, node by node (as few as it reasonably can).\"\n ([a b] (diff a b []))\n ([a b path]\n (cond\n (= a b) []\n (and (node? a) (node? b) (= (tag a) (tag b)))\n (vec (concat (diff-kids (kids a) (kids b) path)\n (when (not= (attrs a) (attrs b)) [[:attrs path (attrs b)]])))\n :else [[:set path b]])))\n\n(defn ops-summary \"A short description of an edit, for the history and the REPL.\" [[op path x]]\n (str (name op) \" \" (pr-str path)\n (case op\n (:set :insert) (str \" \" (let [t (pr-str x)] (if (> (count t) 60) (str (subs t 0 57) \"…\") t)))\n :attrs (str \" \" (pr-str x))\n \"\")))\n\n;; ───────── metric weight in a tree ─────────\n\n(defn- leaf-onsets\n \"[[path onset] …] of the notes and chords of a measure (onsets in beats from its start).\"\n [m]\n (let [acc (transient [])]\n (place m 0 1 {:path [] :voice nil} acc)\n (->> (persistent! acc)\n (filter (fn [e] (= :note (:kind e))))\n (map (fn [e] (let [p (:path e)] [(if (= :chord (tag (node-at m (pop p)))) (pop p) p) (:t e)])))\n distinct\n vec)))\n\n(defn- thin-measure [amount m]\n (let [ls (leaf-onsets m)\n n (count ls)\n k (if (< amount 1) (js/Math.round (* amount n)) (min n (js/Math.round amount)))\n {[_ q] :meter :as mtr} (meter-of (attrs m))\n unit (/ 4 q)\n ;; the coarsest pulse (the unit, halved up to six times) that holds every onset: Barlow ranks there\n pulse (first (filter (fn [pb] (every? (fn [[_ t]] (let [x (/ t pb)] (< (js/Math.abs (- x (js/Math.round x))) 1e-6))) ls))\n (map (fn [e] (/ unit (js/Math.pow 2 e))) (range 7))))\n ranks (when pulse (indispensability mtr pulse))\n weight (fn [[_ t]] [(meter-level mtr t)\n (- (if ranks (nth ranks (js/Math.round (/ t pulse)) -1) -1))\n t])\n kept (set (map first (take k (sort-by weight ls))))]\n (reduce (fn [mm [path _]]\n (if (kept path)\n mm\n (apply-op mm [:set path [:rest {:dur (:dur (attrs (node-at mm path)))}]])))\n m ls)))\n\n(defn thin\n \"Keeps, in every measure, the notes on its strongest positions (metric level, then Barlow's\n indispensability) and turns the others into rests: amount is a share of the notes (0.5) or how many\n (3). Without measures, the whole tree is weighed as one bar of quarters.\"\n [amount tree]\n (let [t (with-meters (explicit (expand tree)))\n measured (some (fn [x] (and (node? x) (= :measure (tag x)))) (tree-seq node? kids t))]\n (letfn [(go [n]\n (cond (not (node? n)) n\n (= :measure (tag n)) (thin-measure amount n)\n :else (with-kids n (mapv go (kids n)))))]\n (if measured\n (go t)\n (first (kids (thin-measure amount [:measure {:meter [(max 1 (js/Math.ceil (duration t))) 4]} t])))))))\n","kairotic/mtboxes.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · boxes for musical trees (Study 19)\n;; tree a tree in EDN (kairotic.mt), seen as a score or a roll, its text in the code window: a bang sends it\n;; mt operations on trees: mt transpose 7 · mt invert c4 · mt retrograde · mt augment 2 ·\n;; mt rotate 1 · mt canon 2 7 · mt thin 0.5 · mt seq · mt par · mt events · mt pitches · mt duration · mt play\n;; A canvas, freqt or score that receives a tree shows it (kairotic.components/canvas-box).\n\n(ns kairotic.mtboxes\n (:require [clojure.string :as str]\n [kairotic.components :as comp]\n [kairotic.code :as cbox]\n [kairotic.mt :as mt]\n [kairotic.quantize :as qz]\n [kairotic.treecanvas :as tc]))\n\n;; ───────── tree: EDN data in the patch ─────────\n;; Reading EDN evaluates nothing, so a tree box is safe in a shared room (no trust needed).\n\n;; a canvas, freqt or score that shows a tree gives it as its buffer (a reader~ plays it): Study 23\n(reset! comp/tree-buffer mt/->strokes)\n\n(cbox/register-language! \"edn\"\n (fn [source]\n (js/Promise.\n (fn [res rej]\n (try\n (let [t (mt/read-tree source) ps (when t (mt/errors t)) ws (when t (mt/warnings t))]\n (cond (nil? t) (rej (js/Error. \"empty\"))\n (seq ps) (rej (js/Error. (str (first ps) (when (> (count ps) 1) (str \" (+\" (dec (count ps)) \" more)\")))))\n :else (res {:value (mt/expand t)\n :info {:summary (str (mt/summary t) (when (seq ws) (str \" · ⚠ \" (first ws))))}})))\n (catch :default e (rej e)))))))\n\n;; The data of a tree box is the tree itself: {:tree t :source text}. Its history events are edits of\n;; nodes ([:edit [[:attrs [0 1 2] {…}] …]], kairotic.mt/apply-op), so two branches that change different\n;; measures can be merged; the text is only how it is shown (and edited: an edit of the text becomes\n;; the node operations that make the difference, kairotic.mt/diff).\n\n(defn- parse [text] (try (mt/read-tree text) (catch :default _ nil)))\n\n(defn tree-of \"The tree of a tree box's data (older works kept only its text).\" [d]\n (or (:tree d) (parse (:source d))))\n\n(defn- with-tree [t] {:tree t :source (if (some? t) (mt/pp t) \"\")})\n\n(defn step [d [op & args]]\n (let [d (or d {:tree nil :source \"\"})]\n (case op\n :source (let [[text] args t (parse text)] (if (some? t) {:tree t :source (str text)} (assoc d :source (str text))))\n :load (let [[x] args]\n (cond (and (map? x) (contains? x :tree)) (with-tree (:tree x))\n (and (map? x) (string? (:source x))) (step nil [:source (:source x)])\n :else d))\n :edit (let [[ops] args]\n (try (with-tree (reduce mt/apply-op (tree-of d) ops))\n (catch :default _ d)))\n d)))\n\n(def model\n {:empty {:tree nil :source \"\"}\n :step step\n :load (fn [x] (step nil [:load x]))\n ;; in the Code tab, the tree as one call: (tree! :b2 [:voice …])\n :code (fn [id d] (when-let [t (tree-of d)]\n (concat [(str \"(tree! \" id)] (map (fn [l] (str \" \" l)) (str/split-lines (mt/pp t))) [\")\"])))})\n\n(comp/define! \"tree\"\n {:doc \"A musical tree written in EDN (hiccup style: [:voice [:measure {:meter [4 4]} \\\"c4/1 e4 g4/2\\\"]]), seen as a score or as a roll of frequency over time (⇄ in its header), its text in the code window ({ } in its header) — one tree, two views (discussion #92): drawing on its roll writes notes into the tree (free time without measures, quantized bars with them). It sends its tree, expanded, whenever it changes (and again on a bang); `tree manual` only on a bang. Its second outlet is its notes as a buffer, for a reader~. On its inlet it takes edits [:edit [[:attrs path {…}] …]] (from a score's edits outlet) and whole trees, which change it.\"\n :usage \"tree\"\n ;; two views (score, roll); its text opens in the code window from { }. Works that showed it as code\n ;; or as a canvas open it as a score or a roll\n :display :score :views [:score :roll] :view-as {:roll :canvas} :view-aliases {:canvas :roll :code :score}\n :language \"edn\" :model model\n :io [1 2]\n :template \"[:voice {:name \\\"motif\\\"}\\n [:measure {:meter [4 4]} \\\"c4/1 d4/.5 e4 g4/1 e4\\\"]\\n [:measure \\\"f4/.5 e4 d4 c4 d4/2\\\"]]\"\n :receive (fn [m]\n (let [t (tree-of (:data m)) v (:value m)]\n (cond\n ;; edits and trees change the box: that is a gesture of the work, done by the page\n (and (vector? v) (= :edit (first v))) {:effects [[:tree-edit (second v)]]}\n ;; its own tree come back (through mt boxes): a loop that would rewrite it for ever\n (and (mt/node? v) (= (:from (meta v)) (:id m)))\n {:effects [[:print (str \"loop: \" (name (:id m)) \" received its own tree back; it does not change\")]]}\n (mt/node? v) {:effects [[:tree-set v]]}\n (some? t)\n (try {:out [[0 (mt/expand-source t (:id m))]] :show :bang}\n (catch :default e {:effects [[:print (str \"tree: \" (.-message e))]]}))\n :else {:effects [[:print \"tree: empty, or text that does not read as EDN\"]]})))})\n\n;; ───────── quantize: free time written in measures, by hand ─────────\n;; The material is the freqt on its right inlet (what transcribe or a drawing wrote), or a tree that came on the\n;; left (free time, or measured: it is first made free again); the options are kept as they come; only a bang\n;; quantizes and sends — a tree into a tree box is an event of the work's history, so nothing goes out while the\n;; options are being tried.\n\n(def quantize-keys #{:meter :meters :divs :merge :grace :chord :legato :voices :overlap :nest :key :tempo :time :ref-bpm :w :spell})\n\n(defn quantize-report\n \"What a quantization found: its bars, its meter, its tempo, its notes and its voices.\"\n [t]\n (let [xt (mt/expand t)\n ms (filter (fn [x] (and (mt/node? x) (= :measure (mt/tag x)))) (tree-seq mt/node? mt/kids xt))\n vs (filter (fn [x] (and (mt/node? x) (= :voice (mt/tag x)))) (tree-seq mt/node? mt/kids xt))\n m0 (some (fn [m] (:meter (mt/attrs m))) ms)]\n {:bars (if (seq vs) (quot (count ms) (max 1 (count vs))) (count ms))\n :meter (when m0 (str/join \"/\" m0))\n :tempo (:tempo (mt/attrs xt))\n :notes (count (filter (fn [e] (= :note (:kind e))) (mt/events xt)))\n :voices (max 1 (count vs))}))\n\n(comp/define! \"quantize\"\n {:doc \"Free time written in measures, when you ask: what transcribe or a drawing left in a freqt (connect the freqt's second outlet to its right inlet), or a tree in free time that comes on the left (a measured one is made free first), becomes a measured tree — measures, tuplets, ties, grace notes, voices —, for a tree box. Only a bang quantizes and sends it, so its options can be tried first: [:meter \\\"6/8\\\"], [:meter \\\"7/8[2+2+3]\\\"], [:meters [\\\"3/4\\\" \\\"5/8\\\"]], [:divs [1 2 3 4]] (the divisions a beat may take), [:merge []] (no beats joined into a tuplet), [:legato 0.25] (the largest gap that is not a rest, in beats), [:chord 0.04] (starts that close are one chord), [:voices 1], [:grace false], [:key \\\"eb\\\"], [:tempo 72], [:time :track] (find the beats of what was played freely, as track), or a map of them; [:meter nil] forgets one, :reset all of them. With the word track it finds the beats from the start. It is the quantization a freqt shown as a score uses (that is a preview); here it is a step of the patch, with its options in view, and two quantize boxes can write the same take two ways.\"\n :usage \"quantize [track]\"\n :io [2 2]\n :reads-buffer true\n :receive (fn [{:keys [inlet value state args buffer buffer-id]}]\n (let [st (or state {:opts (if (some #{:track} args) {:time :track} {})})\n show (fn [st extra] (merge {:opts (:opts st) :from (cond (:tree st) \"a tree\" buffer-id (name buffer-id) :else nil)} extra))]\n (cond\n ;; the right inlet: the freqt is read when the bang comes (nothing to keep)\n (= inlet 1) {}\n ;; an option, or several; nil forgets it\n (and (vector? value) (= 2 (count value)) (quantize-keys (first value)))\n (let [[k v] value st (if (nil? v) (update st :opts dissoc k) (assoc-in st [:opts k] v))] {:state st :show (show st nil)})\n (and (map? value) (seq value) (every? quantize-keys (keys value)))\n (let [st (update st :opts merge value)] {:state st :show (show st nil)})\n (#{:reset} value) (let [st (assoc st :opts {})] {:state st :show (show st nil)})\n ;; a tree: the material, kept until the next bang\n (mt/node? value) (let [st (assoc st :tree value)] {:state st :show (show st {:waiting true})})\n (#{:clear} value) (let [st (dissoc st :tree)] {:state st :show (show st nil)})\n ;; a bang: quantized now, and sent\n (= value :bang)\n (let [t (:tree st)\n free (fn [t] (if (mt/measured? t) (tc/free-form t) t))]\n (try\n (let [q (cond t (qz/quantize-tree (free t) (:opts st))\n (and (map? buffer) (seq (:strokes buffer))) (qz/quantize buffer (merge (:quant buffer) (:opts st)))\n :else nil)]\n (if q\n (let [r (quantize-report q)] {:state st :show (show st r) :out [[1 r] [0 q]]})\n {:show (show st {:error \"nothing to quantize: a freqt on the right, or a tree on the left\"})}))\n (catch :default e {:show (show st {:error (.-message e)})\n :effects [[:print (str \"quantize: \" (.-message e))]]})))\n :else {})))\n :size [190 40]\n :derive (fn [{:keys [shown]}]\n {:main (str \"quantize\" (when-let [m (get-in shown [:opts :meter])] (str \" · \" m)) (when (= :track (get-in shown [:opts :time])) \" · track\"))\n :sub (cond (:error shown) (str \"✗ \" (:error shown))\n (:notes shown) (str (:bars shown) \" bars of \" (:meter shown) \" · \" (:notes shown) \" notes\" (when (:tempo shown) (str \" · ♩ \" (:tempo shown))))\n (:waiting shown) \"a tree is here: bang to quantize it\"\n :else \"bang: quantize and send\")})\n :view [[:rect {:x 2 :y 2 :w 186 :h 36 :r 3 :stroke :grid :fill :bg}]\n [:text {:x 10 :y 18 :size 12} :$main]\n [:text {:x 10 :y 32 :size 9 :fill :soft} :$sub]]})\n\n;; ───────── mt: operations ─────────\n\n(defn op-of [args] (some-> (first args) name))\n\n(def two-inlets #{\"transpose\" \"invert\" \"augment\" \"rotate\" \"canon\" \"thin\" \"seq\" \"par\"})\n\n(defn num-arg [x d] (if (number? x) x d))\n\n(defn transform\n \"What `mt <op> args` does to a tree (with the right inlet's value r, if it came).\"\n [op args r t]\n (let [[a b] args]\n (case op\n \"transpose\" (mt/transpose (let [x (or r a)] (cond (number? x) x (or (symbol? x) (keyword? x) (string? x)) (name x) :else 0)) t)\n \"invert\" (mt/invert (or r (when (some? a) (if (keyword? a) (name a) a))) t)\n \"retrograde\" (mt/retrograde t)\n \"augment\" (mt/augment (num-arg (or r a) 2) t)\n \"rotate\" (mt/rotate (num-arg (or r a) 1) t)\n \"thin\" (mt/thin (num-arg (or r a) 0.5) t)\n ;; mt canon 2 7 · or with the heads' words: mt canon d 2 k P5 speed 0.5 inversion\n \"canon\" (if (some #{:d :k :speed :inversion} args)\n (let [after (fn [w] (second (drop-while #(not= w %) args)))\n k (after :k)]\n (mt/canon {:d (num-arg (or r (after :d)) 1)\n :k (cond (number? k) k (or (keyword? k) (symbol? k) (string? k)) (name k) :else 0)\n :speed (num-arg (after :speed) 1) :inversion (boolean (some #{:inversion} args))}\n t))\n (mt/canon (num-arg (or r a) 1) (num-arg b 0) t))\n \"seq\" [:seq (mt/expand t) (if (mt/tree? r) (mt/expand r) [:seq])]\n \"par\" [:par (mt/expand t) (if (mt/tree? r) (mt/expand r) [:seq])]\n \"expand\" (mt/expand t)\n \"events\" (mt/events t)\n \"pitches\" (mt/pitches t)\n \"duration\" (mt/duration t)\n (throw (js/Error. (str \"mt: unknown operation \" (pr-str op)))))))\n\n(defn play-speed\n \"The speed of mt play: its words (mt play speed 0.5), or what a [:speed s] message set.\"\n [st args]\n (or (:speed st) (let [x (second (drop-while #(not= :speed %) args))] (when (and (number? x) (not (zero? x))) x)) 1))\n\n(defn play-schedule\n \"What mt play plays at speed s: the times divided by |s|, and backwards (the tree's retrograde) when s < 0.\"\n [tree s]\n (let [t (if (neg? s) (mt/retrograde tree) tree) a (js/Math.abs s)]\n {:sch (mapv (fn [[sec outs]] [(/ sec a) outs]) (mt/schedule t))\n :len (/ (* (/ 60 (mt/tempo-of t)) (mt/duration t)) a)}))\n\n(defn play [{:keys [state args inlet value at]}]\n (let [st (or state {:gen 0})\n tick? (and (vector? value) (= :tick (first value)))\n loop? (some #{:loop} (rest args))]\n (cond\n tick?\n (let [[_ g i] value sch (:sch st)]\n (if (and (= g (:gen st)) sch (< i (count sch)))\n (let [[_ outs] (nth sch i)\n nxt (inc i)]\n (cond\n (< nxt (count sch)) {:state st :out outs :show i\n :later [[(+ (:t0 st) (first (nth sch nxt))) 0 [:tick g nxt]]]}\n loop? (let [t0 (+ (:t0 st) (:len st))]\n {:state (assoc st :t0 t0) :out outs :later [[t0 0 [:tick g 0]]]})\n :else {:state (assoc st :playing false) :out outs}))\n {:state st}))\n\n ;; another speed (msg :speed 0.5, −1 backwards): from the next start, or now for what is playing\n (and (vector? value) (= :speed (first value)) (number? (second value)) (not (zero? (second value))))\n (let [st (assoc st :speed (second value))]\n (if-let [t (:tree st)]\n (let [{:keys [sch len]} (play-schedule t (second value)) st (assoc st :sch sch :len len)]\n ;; playing: it starts again, at the new speed\n (if (and (:playing st) (seq sch))\n (let [g (inc (:gen st))]\n {:state (assoc st :gen g :t0 at) :later [[(+ at (first (first sch))) 0 [:tick g 0]]]})\n {:state st}))\n {:state st}))\n\n (mt/tree? value)\n (let [{:keys [sch len]} (play-schedule value (play-speed st args))]\n (cond\n ;; the same music again (a tree box re-sends its tree when the patch around it changes, e.g. a\n ;; knob that keeps its value in its text): nothing changes, and what is playing goes on\n (= sch (:sch st)) {:state st}\n ;; other music while playing: it goes on with the new one, from its beginning\n (and (:playing st) (seq sch))\n (let [g (inc (:gen st))]\n {:state (assoc st :tree value :sch sch :len len :gen g :t0 at) :later [[(+ at (first (first sch))) 0 [:tick g 0]]]})\n :else {:state (assoc st :tree value :sch sch :len len :gen (inc (:gen st)))}))\n\n (= value :stop)\n {:state (-> st (update :gen inc) (assoc :playing false)) :out [[1 []] [0 []]]}\n\n (or (= value :bang) (= value :start) (number? value))\n (if (seq (:sch st))\n (let [g (inc (:gen st))]\n {:state (assoc st :gen g :t0 at :playing true) :later [[(+ at (first (first (:sch st)))) 0 [:tick g 0]]]})\n {:state st})\n\n :else {:state st})))\n\n(comp/define! \"mt\"\n {:doc \"Operations on musical trees: a tree on the left comes out transformed. transpose n (semitones, or an interval: M3, -P5, A4) · invert [pivot] · retrograde · augment f · rotate k · canon delay [interval], or with the words of a reader on a ring: canon d 2 k P5 speed 0.5 inversion (the comes d beats later, k away, at a speed — 0.5 twice as slow, −1 backwards —, upside down) · thin amount (keeps the notes on the strongest positions of each measure: a share, 0.5, or how many, 3) · seq / par (joins the left tree with the one on the right) · events · pitches · duration · play [loop] [speed s] (a bang plays the last tree: Hz and voice ids for synth~, parameters and marks; at a speed, 0.5 twice as slow, −1 the tree backwards — msg :speed −1 —: the reader of a tree on its own clock, as a reader on a ring follows its head).\"\n :usage \"mt <operation> [arguments]\"\n :io (fn [b] (let [op (op-of (:args b))]\n (cond (= op \"play\") [1 4]\n (two-inlets op) [2 1]\n :else [1 1])))\n :dynamic-io true\n :receive (fn [{:keys [state args inlet value] :as m}]\n (let [op (op-of args)]\n (cond\n (= op \"play\") (play m)\n (= inlet 1) {:state (assoc state :r value)}\n (mt/tree? value)\n (try {:state state\n ;; the result remembers which tree box the tree comes from (a loop back to it is seen)\n :out [[0 (let [x (transform op (rest args) (:r state) value)]\n (if (and (mt/node? x) (:from (meta value))) (vary-meta x assoc :from (:from (meta value))) x))]]}\n (catch :default e {:state state :effects [[:print (str \"mt \" op \": \" (.-message e))]]}))\n :else {:state state})))})\n","kairotic/patterns.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · patterns\n;; Patterns after SuperCollider's (Pbind, Pseq, Pwhite…), on Clojure's lazy sequences as Overtone does\n;; (discussion #84). A pattern is a (possibly infinite) lazy sequence of event maps:\n;; {:degree 2 :dur 1/2 :amp 0.3} → played by a `player` box (@kairotic/patterns)\n;;\n;; Two layers, because the history, rooms and links of a work travel as data and a lazy seq does not:\n;; · the source travels: the text of a `pbind` (EDN) or a `pattern` (code) box, and a seed;\n;; · the stream is local: each tab makes the sequence from the source. The same seed gives the same\n;; music everywhere, and going back in the history plays the same again.\n;; What goes along a line is a pattern value, a factory of streams ({:kairotic/pattern true :make (fn [] …)}),\n;; never the sequence itself, so nothing infinite is printed or kept.\n;;\n;; A pbind is a map: a plain value is a constant, a vector a sequence (the shorter ones start again until\n;; the longest ends; all of them, `repeat` times), and an EDN tagged literal #pat/… a generator:\n;; #pat/seq [a b c] the same as a vector #pat/choose [a b c] one at random, each time\n;; #pat/shuffle [a b c] every pass in a new order #pat/white [lo hi] random between lo and hi\n;; #pat/walk [x step lo hi] a random walk #pat/series [x step] or [x step n]\n;; #pat/hold [beats [a b]] one value per `beats` #pat/chord [0 4 7] a vector as one value\n;; A generator can be an element of a vector: [1 #pat/choose [2 3]]. Each key has its own seed, made of\n;; the box's seed and its name, so changing :dur does not change the randomness of :amp.\n\n(ns kairotic.patterns\n (:require [clojure.string :as str]\n [clojure.edn :as edn]\n [kairotic.score :as sc]\n [kairotic.canvas :as cv]\n [kairotic.code :as code]))\n\n(def max-period\n \"The longest finite sequence a pattern treats as one (a lazy seq longer than this is a stream).\"\n 4096)\n\n;; ───────── seeded randomness ─────────\n\n(defn rng\n \"A generator of numbers in [0, 1) from a seed (any value): the same seed gives the same numbers in\n every tab (mulberry32 over the hash of the seed).\"\n [seed]\n (let [s (volatile! (bit-or (hash seed) 0))]\n (fn []\n (let [a (vswap! s (fn [a] (bit-or (+ a 0x6D2B79F5) 0)))\n t (js/Math.imul (bit-xor a (unsigned-bit-shift-right a 15)) (bit-or a 1))\n t (bit-xor (+ t (js/Math.imul (bit-xor t (unsigned-bit-shift-right t 7)) (bit-or t 61))) t)]\n (/ (unsigned-bit-shift-right (bit-xor t (unsigned-bit-shift-right t 14)) 0) 4294967296)))))\n\n(defn whole? [x] (and (number? x) (== x (js/Math.floor x))))\n\n(defn rand-in\n \"A random number between lo and hi from r: a whole one (both ends included) when both are whole.\"\n [r lo hi]\n (if (and (whole? lo) (whole? hi))\n (+ (min lo hi) (js/Math.floor (* (r) (inc (js/Math.abs (- hi lo))))))\n (+ lo (* (r) (- hi lo)))))\n\n(defn pick \"One element of the vector xs, at random.\" [r xs] (nth xs (js/Math.floor (* (r) (count xs)))))\n\n(defn shuffled \"The vector xs in a random order (Fisher–Yates).\" [r xs]\n (loop [v (vec xs) i (dec (count xs))]\n (if (pos? i)\n (let [j (js/Math.floor (* (r) (inc i)))]\n (recur (assoc v i (nth v j) j (nth v i)) (dec i)))\n v)))\n\n;; ───────── generators: #pat/… in EDN ─────────\n\n(def gen-names #{:seq :choose :shuffle :white :walk :series :hold :chord})\n\n(defn gen \"A generator as data.\" [g args] {:pat/gen g :pat/args args})\n(defn gen? [x] (and (map? x) (contains? x :pat/gen)))\n\n(def readers (into {} (for [g gen-names] [(symbol \"pat\" (name g)) (fn [x] (gen g x))])))\n\n(defn read-spec\n \"The text of a pbind as data: #pat/… become generators. Throws on bad EDN or an unknown tag.\"\n [source]\n (edn/read-string {:readers readers\n :default (fn [tag _]\n (throw (js/Error. (str \"unknown tag #\" tag \" (the generators are \"\n (str/join \" \" (map (fn [g] (str \"#pat/\" (name g))) (sort gen-names))) \")\"))))}\n (str source)))\n\n(defn- nums? [xs n] (and (sequential? xs) (= n (count xs)) (every? number? xs)))\n\n(defn gen-problem\n \"What is wrong with a generator's arguments, or nil.\"\n [{g :pat/gen a :pat/args}]\n (let [tag (str \"#pat/\" (name g))]\n (case g\n (:seq :choose :shuffle :chord) (when-not (and (sequential? a) (seq a)) (str tag \" takes a vector of values: \" tag \" [0 2 4]\"))\n :white (when-not (nums? a 2) (str tag \" takes [lo hi]: \" tag \" [0 7]\"))\n :walk (when-not (nums? a 4) (str tag \" takes [start step lo hi]: \" tag \" [0 2 -7 7]\"))\n :series (when-not (or (nums? a 2) (nums? a 3)) (str tag \" takes [start step] or [start step n]: \" tag \" [0 2 8]\"))\n :hold (when-not (and (sequential? a) (= 2 (count a)) (number? (first a)) (pos? (first a))\n (sequential? (second a)) (seq (second a)))\n (str tag \" takes [beats [values]]: \" tag \" [4 [:c :g :d]]\"))\n (str \"unknown generator \" tag))))\n\n(defn problems\n \"What is wrong with a pbind map (a list of reasons, empty if nothing).\"\n [m]\n (if-not (map? m)\n [\"a pbind is a map {:key values …}: {:degree [0 2 4] :dur 1/2}\"]\n (concat\n (for [k (keys m) :when (not (keyword? k))] (str \"the keys of a pbind are keywords (\" (pr-str k) \" is not)\"))\n (->> (tree-seq (fn [x] (or (map? x) (sequential? x))) (fn [x] (if (map? x) (if (gen? x) [(:pat/args x)] (vals x)) x)) m)\n (filter gen?)\n (keep gen-problem)))))\n\n;; ───────── streams: one per key ─────────\n;; stream-of gives {:stream (lazy, infinite) :period n-or-nil}: a finite sequence of n values cycles (so a\n;; shorter one starts again), an endless one has no period; a constant is :const and a hold is :held.\n\n(declare stream-of)\n\n(defn rng-for [ctx] (rng [(:seed ctx) (:key ctx) (:pass ctx) (:path ctx)]))\n\n(defn- elements\n \"The values of a vector, nested vectors flattened (as Overtone's pbind does); generators and lazy\n sequences stay one element each.\"\n [xs]\n (mapcat (fn [x] (if (vector? x) (elements x) [x])) xs))\n\n(defn- cycle-or-stream\n \"A lazy seq as a stream: a finite one round and round, an endless one as it is.\"\n [s]\n (if (<= (bounded-count (inc max-period) s) max-period) (if (seq s) (cycle s) (repeat nil)) s))\n\n(defn- taker\n \"A function that gives the next value of an element each time it is called: a generator or a lazy seq\n gives one of its values, anything else itself.\"\n [x ctx]\n (cond (gen? x) (let [s (volatile! (:stream (stream-of x ctx)))] (fn [] (let [v (first @s)] (vswap! s rest) v)))\n (seq? x) (let [s (volatile! (cycle-or-stream x))] (fn [] (let [v (first @s)] (vswap! s rest) v)))\n :else (constantly x)))\n\n(defn- takers [xs ctx] (vec (map-indexed (fn [i x] (taker x (update ctx :path conj i))) xs)))\n\n(defn- cycling\n \"The elements of a vector, round and round (a generator in it gives a new value each time it comes round).\"\n [xs ctx]\n (let [ts (takers xs ctx) n (count ts)]\n {:stream (map (fn [i] ((nth ts (mod i n)))) (range)) :period n}))\n\n(defn stream-of\n \"The values of one key of a pbind, given ctx {:seed :key :pass :path}.\"\n [x ctx]\n (let [ctx (update ctx :path (fnil identity []))]\n (cond\n (gen? x)\n (let [a (:pat/args x)]\n (case (:pat/gen x)\n :seq (stream-of (vec a) ctx)\n :chord {:stream (repeat (vec a)) :const true}\n :choose (let [r (rng-for ctx) ts (takers (vec (elements a)) ctx)]\n {:stream (repeatedly (fn [] ((pick r ts))))})\n :shuffle (let [r (rng-for ctx) ts (takers (vec (elements a)) ctx)\n pass (fn pass [] (lazy-seq (concat (map (fn [t] (t)) (shuffled r ts)) (pass))))]\n {:stream (pass) :period (count ts)})\n :white (let [r (rng-for ctx) [lo hi] a] {:stream (repeatedly (fn [] (rand-in r lo hi)))})\n :walk (let [r (rng-for ctx) [x0 step lo hi] a\n lo' (min lo hi) hi' (max lo hi)\n reflect (fn [x] (cond (> x hi') (max lo' (- hi' (- x hi'))) (< x lo') (min hi' (+ lo' (- lo' x))) :else x))]\n {:stream (iterate (fn [x] (reflect (+ x (rand-in r (- step) step)))) x0)})\n :series (let [[x0 step n] a s (iterate (fn [x] (+ x step)) x0)]\n (if (and (number? n) (pos? n))\n {:stream (cycle (take (js/Math.round n) s)) :period (js/Math.round n)}\n {:stream s}))\n :hold (let [[beats xs] a] {:held {:beats beats :values (vec (elements xs))}})\n (throw (js/Error. (str \"unknown generator #pat/\" (name (:pat/gen x)))))))\n (vector? x) (let [xs (vec (elements x))] (if (seq xs) (cycling xs ctx) {:stream (repeat nil) :const true}))\n ;; a lazy seq (from code): finite ones cycle like a vector, endless ones are a stream as they are\n (seq? x) (if (<= (bounded-count (inc max-period) x) max-period)\n (if (seq x) (cycling (vec x) ctx) {:stream (repeat nil) :const true})\n {:stream x})\n :else {:stream (repeat x) :const true})))\n\n(defn static-period\n \"How many events one key gives in a pass, without making it: a number, nil (endless), :const or :held.\"\n [x]\n (cond\n (gen? x) (case (:pat/gen x)\n (:seq) (static-period (vec (:pat/args x)))\n (:shuffle) (count (elements (:pat/args x)))\n (:series) (let [n (nth (:pat/args x) 2 nil)] (if (and (number? n) (pos? n)) (js/Math.round n) nil))\n (:chord) :const\n (:hold) :held\n nil)\n (vector? x) (if (seq x) (count (elements x)) :const)\n (seq? x) (let [n (bounded-count (inc max-period) x)] (if (<= n max-period) (if (pos? n) n :const) nil))\n :else :const))\n\n;; ───────── events ─────────\n\n(defn dur-of \"The length of an event in beats (:dur, 1 if it has none).\" [e]\n (let [d (:dur e)] (if (and (number? d) (>= d 0) (js/isFinite d)) d 1)))\n\n(defn sustain\n \"How long the notes of an event sound, in beats: :sustain, or :dur × :legato (0.8).\"\n [e]\n (let [s (:sustain e) l (:legato e)]\n (if (and (number? s) (pos? s)) s (* (dur-of e) (if (number? l) l 0.8)))))\n\n(defn- timed\n \"The events, each map with its #pat/hold keys filled in for the beat it starts on.\"\n [rows holds]\n (if (empty? holds)\n rows\n (letfn [(step [rows beat]\n (lazy-seq\n (when-let [e (first rows)]\n (let [e (reduce (fn [e [k {:keys [beats values]}]]\n (assoc e k (nth values (mod (js/Math.floor (/ (+ beat 1e-9) beats)) (count values)))))\n e holds)]\n (cons e (step (rest rows) (+ beat (dur-of e))))))))]\n (step rows 0))))\n\n(defn pbind-events\n \"The events of the pbind map m: a lazy seq of maps. opts {:seed :repeat} (repeat a number or :inf). As\n in Overtone, a pattern with an endless key is endless; otherwise one pass lasts as long as its longest\n sequence, and there are `repeat` passes.\"\n [m {:keys [seed repeat]}]\n (let [ks (sort-by str (keys m))\n holds (keep (fn [k] (let [v (get m k)] (when (and (gen? v) (= :hold (:pat/gen v))) [k (:held (stream-of v {:key k}))]))) ks)\n streamed (remove (set (map first holds)) ks)\n periods (map (fn [k] (static-period (get m k))) streamed)\n seqs (remove #{:const} periods)\n endless? (some nil? seqs)\n n (if (seq seqs) (apply max seqs) 1)\n one-pass (fn [p]\n (let [ss (map (fn [k] (:stream (stream-of (get m k) {:seed seed :key k :pass p}))) streamed)]\n (if (seq ss)\n (apply map (fn [& vs] (zipmap streamed vs)) ss)\n (repeat {}))))\n rows (cond endless? (one-pass 0)\n (= repeat :inf) (letfn [(passes [p] (lazy-seq (concat (take n (one-pass p)) (passes (inc p)))))] (passes 0))\n :else (mapcat (fn [p] (take n (one-pass p))) (range (max 1 (or repeat 1)))))]\n (timed rows holds)))\n\n(defn summary\n \"A few words about a pbind map: its keys and how many events a pass has.\"\n [m]\n (let [periods (keep (fn [[_ v]] (let [p (static-period v)] (when-not (#{:const :held} p) p))) m)\n pass (cond (some nil? periods) \"endless\"\n (seq periods) (str (apply max periods) \" events a pass\")\n :else \"1 event\")]\n (str (count m) (if (= 1 (count m)) \" key · \" \" keys · \") pass)))\n\n;; ───────── pattern values: what travels along a line ─────────\n\n(defn pattern\n \"A pattern value: make gives a new stream (a lazy seq of event maps) each time; key tells whether two\n patterns are the same (the same source and seed).\"\n [make key info]\n {:kairotic/pattern true :key key :make make :summary info})\n\n(defn pattern? [x] (and (map? x) (true? (:kairotic/pattern x))))\n\n(defn events \"A new stream of the pattern p.\" [p] ((:make p)))\n\n(defn pbind-pattern\n \"The pattern of a pbind map. opts {:seed n :repeat n|:inf}.\"\n [m opts]\n (let [opts {:seed (or (:seed opts) 0) :repeat (or (:repeat opts) 1)}]\n (pattern (fn [] (pbind-events m opts)) [:pbind m (:seed opts) (:repeat opts)] (summary m))))\n\n;; ───────── patterns as code ─────────\n;; The source of a `pattern` box is a Clojure expression evaluated inside\n;; (fn [{:keys [rand rand-int rand-nth shuffle pbind pseq pwhite …]}] …)\n;; so its randomness is seeded, and the pattern functions are at hand (no other name of clojure.core is\n;; replaced: macros such as `for` expand into them). It returns a sequence of event\n;; maps (nested sequences are flattened, as phrases) or one map, which is read as a pbind.\n\n(defn code-env\n \"The names a pattern's code sees, with their randomness from r.\"\n [r seed rep]\n (let [pb (fn ([m] (pbind-events m {:seed seed :repeat rep})) ([m n] (pbind-events m {:seed seed :repeat (if (or (= n :inf) (= n js/Infinity)) :inf n)})))]\n {:rand (fn ([] (r)) ([n] (* n (r))))\n :rand-int (fn [n] (js/Math.floor (* n (r))))\n :rand-nth (fn [xs] (pick r (vec xs)))\n :shuffle (fn [xs] (shuffled r (vec xs)))\n :pbind pb\n :pseq (fn ([xs] (seq xs)) ([xs n] (if (or (= n :inf) (= n js/Infinity)) (cycle xs) (take (* n (count xs)) (cycle xs)))))\n :pwhite (fn ([lo hi] (repeatedly (fn [] (rand-in r lo hi)))) ([lo hi n] (take n (repeatedly (fn [] (rand-in r lo hi))))))\n :pchoose (fn [xs] (let [v (vec xs)] (repeatedly (fn [] (pick r v)))))\n :pshuffle (fn [xs] (let [v (vec xs)] ((fn pass [] (lazy-seq (concat (shuffled r v) (pass)))))))\n :pseries (fn ([x step] (iterate (fn [x] (+ x step)) x)) ([x step n] (take n (iterate (fn [x] (+ x step)) x))))\n :pwalk (fn [x0 step lo hi] (:stream (stream-of (gen :walk [x0 step lo hi]) {:seed [seed (r)]})))}))\n\n(def code-names (sort (map name (keys (code-env (constantly 0) 0 1)))))\n\n(defn flat-events\n \"The event maps of what a pattern's code returned: a map is one pbind, a sequence is flattened.\"\n [x seed rep]\n (letfn [(fl [x] (cond (map? x) [x] (sequential? x) (mapcat fl x) :else []))]\n (if (map? x)\n (pbind-events x {:seed seed :repeat rep})\n (fl x))))\n\n(defn code-pattern\n \"The pattern of a compiled `pattern` source f. opts {:seed :repeat :source}.\"\n [f opts]\n (let [seed (or (:seed opts) 0) rep (or (:repeat opts) 1)]\n (pattern (fn [] (flat-events (f (code-env (rng [seed :code]) seed rep)) seed rep))\n [:code (:source opts) seed rep]\n \"code\")))\n\n;; ───────── pitch: what an event plays ─────────\n\n(def scales\n {:major [0 2 4 5 7 9 11] :ionian [0 2 4 5 7 9 11] :minor [0 2 3 5 7 8 10] :aeolian [0 2 3 5 7 8 10]\n :dorian [0 2 3 5 7 9 10] :phrygian [0 1 3 5 7 8 10] :lydian [0 2 4 6 7 9 11] :mixolydian [0 2 4 5 7 9 10]\n :locrian [0 1 3 5 6 8 10] :harmonic-minor [0 2 3 5 7 8 11] :melodic-minor [0 2 3 5 7 9 11]\n :pentatonic [0 2 4 7 9] :major-pentatonic [0 2 4 7 9] :minor-pentatonic [0 3 5 7 10] :blues [0 3 5 6 7 10]\n :whole-tone [0 2 4 6 8 10] :chromatic (vec (range 12)) :octatonic [0 2 3 5 6 8 9 11]})\n\n(def rest-words #{:rest :_ :- :r \"rest\" \"_\" \"-\" \"r\"})\n\n(defn rest?\n \"Is the event a silence? {:type :rest}, :rest true, or :rest (:_ :- :r) or nil as its note, degree or freq.\"\n [e]\n (boolean (or (= :rest (:type e)) (true? (:rest e))\n (some (fn [k] (and (contains? e k) (let [v (get e k)] (or (nil? v) (contains? rest-words v)))))\n [:note :midinote :degree :freq]))))\n\n(defn pitch-class\n \"A pitch class: a number, or a name (:c :eb :f# \\\"Bb\\\") → 0…11 (nil if it is not one).\"\n [x]\n (cond (number? x) x\n (or (keyword? x) (string? x) (symbol? x))\n (let [m (re-matches #\"(?i)([a-g])(#|s|b)?\" (if (symbol? x) (str x) (name x)))]\n (when m (+ (get sc/pcs (str/lower-case (nth m 1))) (case (nth m 2) \"#\" 1 \"s\" 1 \"S\" 1 \"b\" -1 \"B\" -1 0))))\n :else nil))\n\n(defn scale-of [x]\n (cond (and (sequential? x) (seq x) (every? number? x)) (vec x)\n (or (keyword? x) (string? x) (symbol? x)) (get scales (keyword (if (keyword? x) (name x) (str x))) (:major scales))\n :else (:major scales)))\n\n(defn degree->midi\n \"A scale degree (0 = the root; fractional degrees glide between steps) as a MIDI pitch, as in\n SuperCollider's default event: :scale (a name or semitones), :root (a pitch class), :octave (5 → c4).\"\n [d {:keys [scale root octave]}]\n (let [sc (scale-of scale) n (count sc)\n f (js/Math.floor d) frac (- d f)\n o (js/Math.floor (/ f n)) i (mod f n)\n s (+ (nth sc i) (* 12 o))\n s2 (if (pos? frac) (+ (if (< (inc i) n) (nth sc (inc i)) (+ 12 (first sc))) (* 12 o)) s)]\n (+ (* 12 (if (number? octave) octave 5)) (or (pitch-class root) 0) s (* frac (- s2 s)))))\n\n(defn- as-vec [x] (if (sequential? x) (vec x) [x]))\n\n(defn note->midi\n \"A note as a MIDI pitch: a number, \\\"c4\\\" or :c4, or a name without octave (:c) in :octave.\"\n [x octave]\n (or (sc/pitch x)\n (when-let [pc (and (not (number? x)) (pitch-class x))] (+ (* 12 (if (number? octave) octave 5)) pc))))\n\n(defn midis\n \"The MIDI pitches an event plays (a vector, fractional for microtones), [] for a rest, nil when it says\n nothing about pitch. :freq is in Hz, so it gives nil here (see hz).\"\n [e]\n (let [tr (if (number? (:transpose e)) (:transpose e) 0)]\n (cond (rest? e) []\n (some? (:freq e)) nil\n (some? (or (:midinote e) (:note e)))\n (vec (keep (fn [x] (some-> (note->midi x (:octave e)) (+ tr))) (as-vec (or (:midinote e) (:note e)))))\n (some? (:degree e))\n (mapv (fn [d] (+ tr (degree->midi d e))) (filter number? (as-vec (:degree e))))\n :else nil)))\n\n(defn hz\n \"The frequencies an event plays, in Hz: [] for a rest, nil when it has no pitch.\"\n [e]\n (cond (rest? e) []\n (some? (:freq e)) (vec (filter number? (as-vec (:freq e))))\n :else (some->> (midis e) (mapv (fn [m] (cv/round-to (cv/midi->hz m) 3))))))\n\n;; ───────── render: a stretch of a pattern as a musical tree (discussion #93) ─────────\n;; What a player at a position would play, worked out at once. A time map says which moment of the pattern\n;; (y, its beats) is at each moment of the result (x, beats): the diagonal from `from` to `to` by default,\n;; or the strokes of a canvas — a steeper line is faster, a flatter one slower, a line going down plays\n;; backwards (each note from its end), a flat stretch holds the note it is in, a vertical step is a cut,\n;; and several strokes are several layers of the same pattern (a canon, a canon by augmentation).\n;; Every event is a span, [onset, onset + sustain): it sounds while the map's y is inside it, so a note of\n;; the result lasts from where the map enters its span to where it leaves it. The result is a tree, so a\n;; freqt shows it live, keep! writes it with its recipe, and a score quantizes it.\n\n(def render-max 4096)\n\n(defn- spans-of\n \"The events of pattern p whose spans may meet [lo, hi]: [{:on :end :e :hz [..]} …] (rests left out).\"\n [p lo hi]\n (loop [s (events p) on 0 acc [] n 0]\n (let [e (first s)]\n (if (or (nil? e) (> on (+ hi 1e-9)) (>= n 100000) (>= (count acc) render-max))\n acc\n (let [d (dur-of e) hz (hz e)\n acc (if (or (rest? e) (empty? hz) (< (+ on (max 0 (sustain e))) (- lo 1e-9)))\n acc\n (conj acc {:on on :end (+ on (max 0 (sustain e))) :e e :hz hz}))]\n (recur (rest s) (+ on d) acc (inc n)))))))\n\n(defn- map-notes\n \"The notes one time map makes: [[x0 x1 span back?] …] for the polyline pts ([[x y] …], in drawn order).\"\n [pts spans]\n (let [eps 1e-9\n inside? (fn [sp y] (and (<= (:on sp) (+ y eps)) (< y (- (:end sp) eps))))\n instant? (fn [sp] (<= (- (:end sp) (:on sp)) eps))\n idx (vec spans)\n close (fn [[active out] i x] (if-let [[x0 back] (get active i)] [(dissoc active i) (conj out [x0 x (idx i) back])] [active out]))\n [x0 y0] (first pts)\n start [(into {} (for [i (range (count idx)) :when (inside? (idx i) y0)] [i [x0 false]])) []]]\n (loop [st start [[xa ya] & more :as ps] pts]\n (if (empty? more)\n ;; the end of the map: what still sounds ends there\n (let [[active out] st] (into out (for [[i [x0 back]] active] [x0 xa (idx i) back])))\n (let [[xb yb] (first more)\n st (cond\n ;; a vertical step (or one back in x): a cut, as a seek — what still contains yb goes on\n (<= xb (+ xa eps))\n (let [[active out] (reduce (fn [st i] (if (inside? (idx i) yb) st (close st i xa))) st (keys (first st)))]\n [(into active (for [i (range (count idx)) :when (and (inside? (idx i) yb) (not (contains? active i)))] [i [xb false]])) out])\n ;; flat: what sounds is held\n (< (js/Math.abs (- yb ya)) eps) st\n :else\n (let [up? (> yb ya)\n x-at (fn [y] (+ xa (* (- xb xa) (/ (- y ya) (- yb ya)))))\n lo (min ya yb) hi (max ya yb)]\n (reduce\n (fn [[active out :as st] i]\n (let [sp (idx i) a (:on sp) b (:end sp)]\n (cond\n (or (> a (+ hi eps)) (< b (- lo eps))) st\n ;; no length: it sounds where it is crossed, either way\n (instant? sp)\n (if (if up? (and (> a (+ ya eps)) (<= a (+ yb eps))) (and (< a (- ya eps)) (>= a (- yb eps))))\n [active (conj out [(x-at a) (x-at a) sp (not up?)])]\n st)\n :else\n (let [in0 (contains? active i) in1 (inside? sp yb)\n [enter leave] (if up? [a b] [b a])]\n (cond\n (and in0 in1) st\n in0 (close st i (x-at leave))\n in1 [(assoc active i [(x-at enter) (not up?)]) out]\n ;; passed over entirely within the step\n (if up? (and (< ya (- a eps)) (>= yb (- b eps))) (and (>= ya (- b eps)) (< yb (+ a eps))))\n [active (conj out [(x-at enter) (x-at leave) sp (not up?)])]\n :else st)))))\n st (range (count idx)))))]\n (recur st more))))))\n\n(def render-skip #{:degree :note :midinote :freq :dur :legato :sustain :octave :root :scale :transpose :type :amp :gain :pan})\n\n(defn- look-of\n \"How a note of event e is drawn: :amp as weight, :pan as a gradient, and the keys named in opts\n (:tex k, :tone k) as a texture and a colour, one for each value met (in order).\"\n [e {:keys [tex tone]} seen]\n (let [a (or (:amp e) (:gain e))\n pick (fn [k choices] (when-let [v (and k (contains? e k) (get e k))]\n (let [vs (get @seen k [])\n vs (if (some #{v} vs) vs (conj vs v))]\n (swap! seen assoc k vs)\n (nth choices (mod (first (keep-indexed (fn [i x] (when (= x v) i)) vs)) (count choices))))))]\n (cv/sane-look (cond-> {}\n (number? a) (assoc :w (+ 0.4 (* 2.4 (max 0 (min 1 a)))))\n (number? (:pan e)) (assoc :pan (:pan e))\n tex (assoc :tex (pick tex [nil :dash :dot]))\n tone (assoc :tone (pick tone [nil :kairos :ink :soft]))))))\n\n(defn render-tree\n \"A stretch of pattern p as a musical tree [:par [:note {:at x :dur d :hz h} …]]. opts: :from :to (beats,\n the identity map when there are no :maps), :maps (time maps: [[[x y] …] …]), :tex and :tone (the keys\n drawn as texture and colour). Each note keeps the event's other keys under :ev, :back true when it was\n entered from its end, and a :look for the freqt.\"\n [p {:keys [from to maps] :as opts}]\n (let [maps (if (seq maps) maps [[[(or from 0) (or from 0)] [(or to 16) (or to 16)]]])\n ys (map second (apply concat maps))\n spans (spans-of p (apply min ys) (apply max ys))\n seen (atom {})\n notes (for [[mi pts] (map-indexed vector maps)\n :when (>= (count pts) 2)\n [x0 x1 sp back] (map-notes pts spans)\n ;; a span entered and left at the same x (a cut right at its edge) is not a note\n :when (or (> (- x1 x0) 1e-6) (<= (- (:end sp) (:on sp)) 1e-9))\n hz (:hz sp)\n :let [e (:e sp) ev (apply dissoc e render-skip) look (look-of e opts seen)]]\n [x0 [:note (cond-> {:at (cv/round-to x0 4) :dur (cv/round-to (max 0.02 (- x1 x0)) 4) :hz hz}\n back (assoc :back true)\n (> (count maps) 1) (assoc :layer (inc mi))\n look (assoc :look look)\n (seq ev) (assoc :ev ev))]])]\n (into [:par {:render true}] (map second (sort-by first notes)))))\n\n;; ───────── writing a pbind back as text ─────────\n\n(defn write\n \"A value of a pbind as EDN text, generators as #pat/….\"\n [x]\n (cond (gen? x) (str \"#pat/\" (name (:pat/gen x)) \" \" (write (:pat/args x)))\n (map? x) (str \"{\" (str/join \", \" (map (fn [[k v]] (str (write k) \" \" (write v))) x)) \"}\")\n (vector? x) (str \"[\" (str/join \" \" (map write x)) \"]\")\n (seq? x) (str \"[\" (str/join \" \" (map write (take max-period x))) \"]\")\n :else (pr-str x)))\n\n(defn spec->source\n \"A pbind map as the text of its box, one key per line.\"\n [m]\n (str \"{\" (str/join \"\\n \" (map (fn [[k v]] (str (write k) \" \" (write v))) m)) \"}\"))\n\n;; ───────── the languages of the two code boxes ─────────\n\n(code/register-language! \"pbind\"\n (fn [source]\n (js/Promise.\n (fn [res rej]\n (try\n (let [m (read-spec source) ps (problems m)]\n (if (seq ps)\n (rej (js/Error. (first ps)))\n (res {:value m :info {:summary (summary m)}})))\n (catch :default e (rej e)))))))\n\n(code/register-language! \"pattern\"\n (fn [source]\n (js/Promise.\n (fn [res rej]\n (if-not (code/allowed? source)\n (rej (js/Error. \"not run: this work is shared; (trust-scripts true) to evaluate its patterns\"))\n (try\n (let [f (js/scittle.core.eval_string (str \"(fn [{:keys [\" (str/join \" \" code-names) \"]}]\\n(do \" source \"\\n))\"))\n ;; tried once, so a mistake is told now and not when it plays\n first-events (take 2 (flat-events (f (code-env (rng 0) 0 1)) 0 1))]\n (cond (not (fn? f)) (rej (js/Error. \"a pattern is an expression\"))\n (empty? first-events) (rej (js/Error. \"it gives no events: return event maps ({:degree 0 :dur 1}), a sequence of them, or a map to read as a pbind\"))\n :else (res {:value f :info {:summary (str \"pattern · \" (str/join \" \" (map name (sort (keys (first first-events))))))}})))\n (catch :default e (rej e))))))))\n","kairotic/presets.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · presets (issue #35)\n;; The keyframes of the history (◆ snapshots, takes kept from Perform) as presets of the work: switch to\n;; one, morph between two, or make a new one from what changes and what remains among them.\n;;\n;; A configuration is what a preset holds: the text of every box, sub-patches included — its arguments,\n;; and the values that controls keep in their text (a knob). Boxes that were added or removed, lines and\n;; buffers are not part of it, so switching never rebuilds the patch. Configurations are keyed by the id\n;; the engine knows a box by (:b5.b2 is :b2 inside the sub-patch :b5).\n;;\n;; This file is pure: the page reads the keyframes from the history and writes what these functions\n;; return (app/page/15-presets.cljs). The `presets` box only asks the page to do it (an effect).\n\n(ns kairotic.presets\n (:require [clojure.string :as str]\n [kairotic.components :as comp]\n [kairotic.release :as rel]))\n\n;; ───────── configurations ─────────\n\n(defn fid\n \"The engine id of box `id` of the sub-patch at `path` (as kairotic.engine/flat-id).\"\n [path id]\n (if (empty? path) id (keyword (str (str/join \".\" (map name path)) \".\" (name id)))))\n\n(defn path-of\n \"Back from an engine id to the ids that lead to it: :b5.b2 → [:b5 :b2].\"\n [f]\n (mapv keyword (str/split (name f) #\"\\.\")))\n\n(defn configuration\n \"The texts of the boxes of a patch and of its embedded sub-patches, by engine id.\"\n ([p] (configuration p []))\n ([p path]\n (reduce (fn [acc [id b]]\n (let [acc (assoc acc (fid path id) (str (:text b)))]\n (if (and (= \"patch\" (comp/klass (:text b))) (map? (:data b)))\n (merge acc (configuration (:data b) (conj path id)))\n acc)))\n (sorted-map) (:boxes p))))\n\n(defn words [text] (vec (remove str/blank? (str/split (str/trim (str text)) #\"\\s+\"))))\n\n(defn num\n \"The number a word writes, or nil.\"\n [w]\n (when (and (string? w) (re-matches #\"-?(\\d+\\.?\\d*|\\.\\d+)(e-?\\d+)?\" w)) (js/parseFloat w)))\n\n(defn decimals\n \"How many decimals a number is written with.\"\n [w]\n (let [[_ d] (re-matches #\"-?\\d*\\.(\\d+)\" (str w))] (count d)))\n\n;; ───────── controls: boxes that keep their value in their text ─────────\n\n(defn- probe\n \"What a :persist function makes of x (a map of arguments), or nil if it does not take it.\"\n [persist x]\n (try (let [m (persist x)] (when (and (map? m) (seq m)) m)) (catch :default _ nil)))\n\n(defn control\n \"The value a control box keeps in its text — a class with :persist and :args — as {:ks [argument …]\n :v value :log bool :d definition}, or nil for any other box. The value is a number (a knob: [:initial])\n or a vector of numbers (an envelope keeps [a d s r], a pad [x y]): which arguments hold it is asked of\n :persist itself.\"\n [text]\n (let [d (comp/lookup (comp/klass text))]\n (when (and d (fn? (:persist d)) (sequential? (:args d)))\n (let [args (comp/args-for d text)]\n (when (map? args)\n (if-let [m (probe (:persist d) 1)]\n (let [k (first (keys m)) v (get args k)]\n (when (and (= 1 (count m)) (number? v))\n {:ks [k] :v v :log (true? (:log args)) :d d}))\n ;; a vector: the place of each argument is the number it got from [1 2 3 …]\n (when-let [m (probe (:persist d) (vec (range 1 17)))]\n (let [ks (mapv key (sort-by val (filter (fn [[_ x]] (number? x)) m)))\n v (mapv (fn [k] (get args k)) ks)]\n (when (and (= (count ks) (count m)) (every? number? v))\n {:ks ks :v v :log false :d d})))))))))\n\n(defn control-text\n \"The text of a control with the value v kept in it, as a drag leaves it on release.\"\n [text v]\n (when-let [{:keys [d]} (control text)]\n (when-let [m (probe (:persist d) v)]\n (comp/args-text d (comp/klass text) (merge (comp/args-for d text) m)))))\n\n;; ───────── recall: switch to a configuration ─────────\n\n(defn recall-changes\n \"The boxes that are both now and in the target and whose text differs there: {id text}.\"\n [now target]\n (into (sorted-map)\n (for [[f t] target :let [t0 (get now f)] :when (and (some? t0) (not= (words t0) (words t)))] [f t])))\n\n;; ───────── morph: between two configurations ─────────\n\n(defn lerp\n \"Between a and b at t (0…1); geometric if log? and both are positive (frequencies). Vectors of numbers\n (an envelope) go element by element.\"\n [a b t log?]\n (cond\n (and (vector? a) (vector? b)) (mapv (fn [x y] (lerp x y t log?)) a b)\n (and log? (pos? a) (pos? b)) (* a (js/Math.pow (/ b a) t))\n :else (+ a (* (- b a) t))))\n\n(defn between\n \"A position x among n keyframes (1 = the first) as [a b t]: halfway from 1 to 2 is 1.5 → [1 2 0.5].\"\n [x n]\n (cond (< n 2) [1 1 0]\n :else (let [x (max 1 (min n x))\n a (min (dec n) (js/Math.floor x))]\n [a (inc a) (- x a)])))\n\n(defn morph-values\n \"The values the controls take at t between configurations a and b: {id value}. Only controls of the same\n class now, in a and in b; not those in `exclude` (the boxes that drive the morph); and only those that\n differ between a and b or whose text keeps another value now.\"\n ([now a b t] (morph-values now a b t #{}))\n ([now a b t exclude]\n (into (sorted-map)\n (for [[f tn] now\n :when (not (contains? exclude f))\n :let [ta (get a f) tb (get b f)]\n :when (and ta tb (= (comp/klass tn) (comp/klass ta) (comp/klass tb)))\n :let [cn (control tn) ca (control ta) cb (control tb)]\n :when (and cn ca cb (= (:ks cn) (:ks ca) (:ks cb))\n (or (not= (:v ca) (:v cb)) (not= (:v cn) (:v ca))))]\n [f (lerp (:v ca) (:v cb) t (or (:log ca) (:log cb)))]))))\n\n(defn keep-changes\n \"The texts that keep the values of a morph ({id value}) in the controls now: {id text}.\"\n [now values]\n (into (sorted-map)\n (for [[f v] values :let [t (get now f) t2 (when t (control-text t v))]\n :when (and t2 (not= (words t) (words t2)))]\n [f t2])))\n\n;; ───────── generate: what changes and what remains ─────────\n\n(defn variation\n \"What changes and what remains among configurations: for every box that is in all of them, with the same\n class and as many words, one entry per word — {:same w} if it is the same in all, {:lo :hi :int :places}\n for numbers that change (their range, whether all are whole, the decimals they are written with), or\n {:words [w …]} for words that change. Boxes that do not fit are left out.\"\n [cfgs]\n (if (empty? cfgs)\n (sorted-map)\n (into (sorted-map)\n (for [f (keys (first cfgs))\n :let [ws (mapv (fn [c] (when-let [t (get c f)] (words t))) cfgs)]\n :when (and (every? seq ws) (apply = (map count ws)) (apply = (map first ws)))]\n [f (vec (for [i (range (count (first ws)))\n :let [col (mapv (fn [w] (nth w i)) ws) ns (map num col)]]\n (cond (apply = col) {:same (first col)}\n (every? some? ns) {:lo (apply min ns) :hi (apply max ns)\n :int (every? (fn [w] (zero? (decimals w))) col)\n :places (apply max (map decimals col))}\n :else {:words (vec (sort (distinct col)))})))]))))\n\n(defn rng\n \"A generator of numbers in [0, 1) from a seed (mulberry32): the same seed, the same numbers.\"\n [seed]\n (let [s (atom (bit-or (js/Math.floor (or seed 0)) 0))]\n (fn []\n (let [x (swap! s (fn [x] (bit-or (+ x 0x6D2B79F5) 0)))\n t (js/Math.imul (bit-xor x (unsigned-bit-shift-right x 15)) (bit-or x 1))\n t (bit-xor t (+ t (js/Math.imul (bit-xor t (unsigned-bit-shift-right t 7)) (bit-or t 61))))]\n (/ (unsigned-bit-shift-right (bit-xor t (unsigned-bit-shift-right t 14)) 0) 4294967296)))))\n\n(defn- fixed [v d] (str (js/parseFloat (.toFixed v d))))\n\n(defn- pick-word [{:keys [same lo hi int places words]} log? rand]\n (cond\n (some? same) same\n words (nth words (min (dec (count words)) (js/Math.floor (* (rand) (count words)))))\n :else (let [u (rand)\n v (lerp lo hi u (and log? (pos? lo)))]\n (if int (str (js/Math.round v)) (fixed v (inc places))))))\n\n(defn generate-changes\n \"A new configuration from what changes and what remains among `cfgs`, for the boxes that are now: what is\n the same in all of them stays, numbers that change take a value within their range (geometric in a box\n written with log), words that change are one of theirs. `rand` gives numbers in [0, 1). {id text}.\"\n [now cfgs rand]\n (into (sorted-map)\n (for [[f spec] (variation cfgs)\n :let [t0 (get now f)]\n :when (some? t0)\n :let [log? (some (fn [s] (= \"log\" (:same s))) spec)\n ws (mapv (fn [s] (pick-word s log? rand)) spec)]\n :when (not= ws (words t0))]\n [f (str/join \" \" ws)])))\n\n;; ───────── the box ─────────\n\n(defn- ask [x] {:state nil :effects [[:presets x]]})\n\n(comp/define! \"presets\"\n {:doc \"Presets from the keyframes of the history (◆ snapshots, takes kept): a number or a label recalls one, a position on the right morphs between two, a bang makes a new one from what changes and what remains.\"\n :usage \"presets [label or number …]\"\n :io [2 1]\n ;; presets kept in the box (issue #45): part of the patch, so they travel in its code, links and embeds.\n ;; A box that keeps presets uses them instead of the keyframes of the history.\n :model {:empty {:presets []}\n :step (fn [d [op x]] (case op :store {:presets (rel/sane-presets x)} :clear {:presets []} d))\n :load (fn [x] {:presets (rel/sane-presets (:presets x))})\n :code (fn [id d] (when (seq (:presets d)) [(str \"(presets! \" id \" \" (pr-str (:presets d)) \")\")]))}\n :receive (fn [{:keys [inlet value state]}]\n (if (= inlet 1)\n (cond (not (number? value)) {}\n ;; the same position again changes nothing\n (= value (:x state)) {}\n :else {:state {:x value} :effects [[:presets [:morph-at value]]]})\n (cond\n (number? value) (if (integer? value)\n (ask [:recall value])\n {:effects [[:print \"presets: a position between keyframes goes to the right inlet (1.5: halfway from 1 to 2)\"]]})\n (= value :bang) (ask [:generate nil])\n (= value :keep) (ask [:keep])\n (or (keyword? value) (string? value) (symbol? value)) (ask [:recall (if (symbol? value) (str value) (name value))])\n (and (vector? value) (= :recall (first value))) (ask [:recall (second value)])\n (and (vector? value) (= :generate (first value))) (ask [:generate (second value)])\n (and (vector? value) (= :morph (first value)) (= 4 (count value)) (number? (nth value 3)))\n (ask (into [:morph] (rest value)))\n :else {:effects [[:print (str \"presets: \" (pr-str value) \" is not understood: a number or a label recalls, bang generates, [:morph a b t], keep\")]]})))})\n","kairotic/quantize.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · quantize\n;; Free time written as measured notation (issue #86): the strokes of a freqt, or the notes of a tree\n;; without measures, become a tree of measures, tuplets, ties and grace notes, which kairotic.mt writes\n;; as MEI (and Verovio draws). The tree is plain EDN: it can be read, kept and edited like any other.\n;;\n;; How (after bach.quantize, FOMUS, Nauert):\n;; 1. the frame: the meter comes from the bar grid of the buffer (:gx, its cycles: [4] → 4/4,\n;; [1.5 1.5 1] → 8/8 [3+3+2]) or from the options; without a grid, 4/4.\n;; 2. each bar is cut in spans (the beats of a simple meter; the groups, or dotted beats, of 6/8, 7/8 …)\n;; and every span tries a set of divisions (1 2 3 4 5 6 7 8, and those of its own units); each\n;; division costs the distance from the starts (and, less, the ends) to its points, how deep the\n;; points it uses are (the beat, its half, its quarters, then much more for 32nds; a third, a fifth…),\n;; being a tuplet (3 less than 5, 5 less than 7) and the notes it loses (two starts that fall on one\n;; point, a note that shrinks to nothing). In a simple meter two beats may also go\n;; together (a half-note triplet). Each span keeps its few cheapest divisions, and the plan of a\n;; bar chooses among them with its neighbours in view: changing kind of division (binary, triplet,\n;; quintuplet…) from one region to the next costs :coh, so that a lone triplet among eighths pays\n;; twice and a run of triplets once (issue #108; the bar starts from the kind the one before ended\n;; with). The cheapest plan of each bar wins.\n;; A beat can also be cut in halves (a dotted beat in its eighths), each with its own division.\n;; 3. notes that overlap go to different voices (layers of one staff), all on the same points;\n;; the notes are written on those points: chords where starts meet, rests in the gaps,\n;; a tie where a note goes on over a barline or into or out of a tuplet, a grace note for a note too\n;; short for any point. How each value is written (where the beats have to be seen) is kairotic.mt's\n;; work (mt/metric-split), so that hand-written trees get it too.\n;;\n;; Options (all optional): {:meter \"5/8[2+3]\" :meters [\"3/4\" \"3/4\" \"5/8[2+3]\"] :divs [1 2 3 4 5 6 7 8] :merge [3 5 6] :grace true\n;; :chord 0.04 :legato 0.25 :tempo 72 :w {:err 8 :off 0.35 :cpx 1 :lost 1.5 :coh 0.5}}. :divs are the divisions a\n;; span may take, :merge those of two beats together ([] for none), :chord how close two starts are to be\n;; one chord (beats), :legato the largest gap before the next note that is not a rest (beats; 0: every gap\n;; is), :key the key the score is written in (\"eb\", \"c#m\", :none; without it no signature, and names\n;; from the key the notes suggest), :time how the notes' time becomes beats (:track finds the beats of notes\n;; played freely, in seconds or at any tempo: kairotic.tempo; a map [[time beat] …] is one found and kept;\n;; without it their time is already in beats), :w the weights of the cost; :voices (2) how many voices overlapping notes may take, :overlap how\n;; much a note may run into the next and stay in its voice, :nest false for no beats cut in parts, and\n;; :meters a meter for each bar (the last going on: meter changes, issue #107), :fix {beat-start choice} the divisions chosen by hand (n, [n1 n2] or [:merge n]: see `choices`).\n;; With :time (played time), :ref-bpm (100) weighs the error of a note in seconds rather than in beats: faster than\n;; ref-bpm, :err weighs less, in proportion (down to a third), so that what a player is off by in milliseconds does\n;; not turn into finer divisions at fast tempos (nil: in beats, as without :time).\n\n(ns kairotic.quantize\n (:require [kairotic.canvas :as cv]\n [kairotic.spell :as sp]\n [kairotic.mt :as mt]\n [kairotic.tempo :as tm]))\n\n(def eps 1e-6)\n(defn- near? [a b] (< (js/Math.abs (- a b)) eps))\n(defn- whole? [x] (near? x (js/Math.round x)))\n(defn- gcd [a b] (if (zero? b) (js/Math.abs a) (recur b (mod a b))))\n\n(def defaults\n {:divs [1 2 3 4 5 6 7 8]\n :ref-bpm 100\n :merge [3 5 6]\n :grace true\n :chord 0.04\n :legato 0.25\n :voices 2\n :nest true\n :overlap 0.15\n :w {:err 8 :off 0.35 :cpx 1 :lost 1.5 :coh 0.5}})\n\n;; ───────── 1. the frame ─────────\n\n(defn- default-groups [p q]\n (cond (<= q 4) (vec (repeat p 1))\n (and (zero? (mod p 3)) (> p 3)) (vec (repeat (quot p 3) 3))\n (<= p 3) [p]\n :else nil))\n\n(defn meter-of-grid\n \"The meter a bar grid (:gx) stands for: its cycles, in beats, counted in quarters when they are whole\n ([4] → 4/4, [3] → 3/4, [2 3] → 5/4 [2+3]), in eighths when they need them ([1.5 1.5] → 6/8,\n [1.5 1.5 1] → 8/8 [3+3+2]), and so on. Without a grid, 4/4.\"\n [gx]\n (let [cs (vec (or (seq (:cycles gx)) [4]))\n q (first (filter (fn [q] (every? (fn [c] (and (pos? c) (whole? (* c (/ q 4))))) cs)) [4 8 16 32]))]\n (if-not q\n {:meter [4 4]}\n (let [us (mapv (fn [c] (js/Math.round (* c (/ q 4)))) cs) p (reduce + us)]\n (cond-> {:meter [p q]} (and (> (count us) 1) (not= us (default-groups p q))) (assoc :groups us))))))\n\n(defn sane-choice\n \"A division chosen for a span: n (the span in n), [n1 n2 …] (cut in parts, each its own division) or\n [:merge n] (with the next beat, in n). nil if it is none of those.\"\n [c]\n (let [n? (fn [x] (and (number? x) (whole? x) (<= 1 x 24)))]\n (cond (n? c) (js/Math.round c)\n (and (vector? c) (= :merge (first c)) (n? (second c))) [:merge (js/Math.round (second c))]\n (and (vector? c) (<= 2 (count c) 3) (every? n? c)) (mapv js/Math.round c)\n :else nil)))\n\n(defn sane-fix\n \"The divisions chosen by hand, {span-start choice} (beats → see sane-choice), without what does not read.\"\n [f]\n (when (map? f)\n (not-empty (into {} (for [[k v] f :let [c (sane-choice v)] :when (and (number? k) (>= k 0) c)] [k c])))))\n\n(defn sane-spell\n \"Names chosen by hand for notes of a quantized score: {[beat midi] name} (the beat where the note starts\n in the score, its MIDI pitch), keeping only names that sound that pitch.\"\n [m]\n (when (map? m)\n (not-empty (into {} (for [[k v] m\n :let [[t p] (when (vector? k) k) w (sp/parse v)]\n :when (and (number? t) (number? p) w (= (sp/->midi w) (js/Math.round p)))]\n [[t (js/Math.round p)] (sp/->name w)])))))\n\n(defn respell-by-hand\n \"A tree with the names chosen by hand (:spell, see sane-spell) on the notes that start at that beat\n with that pitch.\"\n [t spell]\n (if (empty? spell)\n t\n (let [evs (filter (fn [e] (= :note (:kind e))) (mt/events t))]\n (reduce (fn [t e]\n (if-let [nm (some (fn [[[bt p] v]] (when (and (< (js/Math.abs (- bt (:t e))) 1e-4) (= p (js/Math.round (:pitch e)))) v)) spell)]\n (mt/apply-op t [:attrs (:path e) (assoc (mt/attrs (mt/node-at t (:path e))) :pitch nm)])\n t))\n t evs))))\n\n(defn options\n \"The options of a quantization, with the defaults, and its meter ({:meter [p q] :groups …}): the one\n given, or that of the bar grid gx.\"\n [opts gx]\n (let [o (merge defaults (when (map? opts) opts))\n ints (fn [xs] (vec (filter (fn [n] (and (number? n) (whole? n) (<= 1 n 24))) (when (sequential? xs) xs))))]\n (assoc o\n :meter (if (some? (:meter opts)) (mt/meter-of (if (map? (:meter opts)) (:meter opts) {:meter (:meter opts) :groups (:groups opts)}))\n (meter-of-grid gx))\n :divs (let [d (ints (:divs o))] (if (seq d) d (:divs defaults)))\n :merge (ints (:merge o))\n :chord (let [x (:chord o)] (if (and (number? x) (>= x 0)) x (:chord defaults)))\n :legato (let [x (:legato o)] (if (and (number? x) (>= x 0)) x (:legato defaults)))\n :overlap (let [x (:overlap o)] (if (and (number? x) (>= x 0)) x (:overlap defaults)))\n :voices (let [x (:voices o)] (if (and (number? x) (whole? x) (<= 1 x 4)) (js/Math.round x) (:voices defaults)))\n :fix (sane-fix (:fix o))\n :key (let [k (:key o)] (when (and (some? k) (sp/parse-key k)) k))\n :spell (sane-spell (:spell o))\n :step (when (and (map? gx) (number? (:step gx)) (pos? (:step gx))) (:step gx))\n ;; a meter for each bar, the last one going on (issue #107): [\"3/4\" \"3/4\" \"5/8[2+3]\"]\n :meters (let [ms (:meters o)]\n (when (and (sequential? ms) (seq ms))\n (not-empty (vec (keep (fn [m] (try (mt/meter-of (if (map? m) m {:meter m})) (catch :default _ nil))) ms)))))\n ;; played time (issue #106): :track finds the beats, a map [[time beat] …] is one kept\n :time (let [x (:time o)] (cond (= x :track) :track (some? x) (tm/sane-map x) :else nil))\n :w (merge (:w defaults) (when (map? (:w opts)) (:w opts))))))\n\n(declare plan)\n\n(defn track-map\n \"The time map of notes played freely (issue #106): the beats found by kairotic.tempo, and how many quarters\n each is worth (½, 1, 1½ or 2, so that a bar holds a whole number of them) chosen by analysis by synthesis:\n with the downbeat among the two beats where the notes weigh most (tempo/phase-weights), by analysis by\n synthesis: the choice whose quantization costs least, with a preference for moderate tempos (around 100 bpm,\n :prior-w). Measured on the benchmark (issue #105, --timed) against simpler rules. When the phase is\n ambiguous it can miss a pickup: :downbeat (the time of a note known to start a bar) fixes it. nil when no\n beat is found.\"\n [notes o]\n (when-let [{:keys [os beats period]} (tm/beats-of notes (:track o))]\n (let [{[p q] :meter} (:meter o) BL (* p (/ 4 q))\n P (/ (- (peek beats) (first beats)) (max 1 (dec (count beats))))\n lp (fn [bpm] (let [x (/ (js/Math.log (/ bpm (or (:prior-bpm o) 100))) js/Math.LN2)] (* x x)))\n o1 (dissoc o :time :fix)\n ;; for each value of the beat, the two phases where the notes weigh most (tempo/phase-weights)\n ;; (with :downbeat, the time of a note known to be on a downbeat, the phase that puts one there)\n db (:downbeat o)\n bv (vec beats)\n db-i (when (number? db) (apply min-key (fn [i] (js/Math.abs (- (bv i) db))) (range (count bv))))\n cands (for [u [0.5 1 1.5 2] :when (whole? (/ BL u))\n :let [m (js/Math.round (/ BL u)) pw (tm/phase-weights os beats m)]\n k (if db-i [(mod db-i m)] (take 2 (sort-by (fn [k] (- (pw k))) (range m))))]\n (tm/map-of beats u m k))\n cost (fn [mp] (+ (reduce + (map :cost (:rs (plan (tm/map-notes notes mp) o1))))\n (* (or (:prior-w o) 3) (lp (tm/tempo-of-map mp)))))]\n (when (seq cands) (apply min-key cost cands)))))\n\n(def ^:private tracked (memoize (fn [notes o] (track-map notes o))))\n\n(defn time-map-of\n \"The time map notes in free time are quantized through (options :time): the one kept, the one found\n (:track, from the onsets and the meter), or nil (their time is already in beats).\"\n [notes o]\n (let [x (:time o)]\n (cond (vector? x) x\n (= x :track) (tracked (mapv (fn [n] (select-keys n [:on :off :attrs])) notes) (select-keys o [:meter :meters :w :divs :merge :nest :chord :prior-w :prior-bpm :downbeat :track]))\n :else nil)))\n\n(defn timed\n \"Notes in free time onto beats, through their time map (see time-map-of): [notes map].\"\n [notes o]\n (if-let [m (time-map-of notes o)] [(tm/map-notes notes m) m] [notes nil]))\n\n(defn spans\n \"The spans of a bar the quantizer divides, as [start length units] (beats from the bar's start, and\n how many units of the meter): the beats of a simple meter (in 5/4 [2+3] too); the groups of a meter\n in eighths or shorter, or its dotted beats (6/8 in two), or the whole bar (3/8); else pairs of units\n and a last three (7/8 → 2+2+3).\"\n [meter]\n (let [{[p q] :meter g :groups} (mt/meter-of meter) u (/ 4 q)\n us (cond (<= q 4) (repeat p 1)\n (seq g) g\n (and (zero? (mod p 3)) (> p 3)) (repeat (quot p 3) 3)\n (<= p 3) [p]\n :else (let [n2 (quot p 2)] (if (odd? p) (concat (repeat (dec n2) 2) [3]) (repeat n2 2))))\n lens (map (fn [k] (* k u)) us)]\n (mapv vector (reductions + 0 lens) lens us)))\n\n;; ───────── 2. the divisions of a span ─────────\n\n(defn- odd-part [n] (loop [n n] (if (and (pos? n) (even? n)) (recur (/ n 2)) n)))\n\n(defn- largest-prime [n]\n (loop [n n f 2 top 1]\n (cond (< n 2) top\n (> (* f f) n) (max top n)\n (zero? (mod n f)) (recur (/ n f) f f)\n :else (recur n (inc f) top))))\n\n(defn tuplet-of\n \"The tuplet n points in a span of L beats need: nil when their unit is a written value (plain or\n dotted: three in a quarter of 6/8 are eighths), [n m] when it is not (n in the time of m: 3 in a\n quarter are [3 2] eighths, 5 are [5 4] sixteenths), or :none when no tuplet writes it.\"\n [L n]\n (let [u (/ L n) x (* u 64)]\n (if (and (whole? x) (#{1 3} (odd-part (js/Math.round x))))\n nil\n (let [up (loop [w 1] (cond (< w (- u eps)) (recur (* 2 w)) (>= (/ w 2) (- u eps)) (recur (/ w 2)) :else w))\n down (loop [w up] (if (> w (+ u eps)) (recur (/ w 2)) w))\n m (some (fn [w] (let [m (/ L w)] (when (whole? m) (js/Math.round m)))) [up down])]\n (if m [n m] :none)))))\n\n(defn complexity\n \"What a division costs before any note is put on it: a tuplet, by its largest prime (3, 5, 7, more),\n a grid of dotted values a little, and a very little more for each point (between two divisions that\n place the notes alike, the simpler one).\"\n [L n]\n (let [tup (tuplet-of L n)]\n (+ (* 0.01 n)\n (cond (nil? tup) (if (= 3 (odd-part (js/Math.round (* 64 (/ L n))))) 0.05 0)\n (= :none tup) 99\n :else (let [[a b] tup g (gcd a b)]\n (case (largest-prime (* (/ a g) (/ b g))) 3 0.25 5 0.5 7 0.7 1.0))))))\n\n(defn depth\n \"How deep point k of n in a span of L beats is, as a cost to read a note there: 0 on the beat, little on\n its half, more on its quarters, much on eighths of a beat and below (32nds); in a tuplet, by how many\n parts its fraction of the span has (a third, a fifth …).\"\n [L n k]\n (if (zero? (mod k n))\n 0\n (if (nil? (tuplet-of L n))\n (let [x (* k (/ L n))\n den (loop [d 1] (if (or (whole? (* x d)) (> d 64)) d (recur (* 2 d))))]\n (case den 1 0 2 0.05 4 0.15 8 0.8 16 1.2 1.5))\n (let [d (/ n (gcd k n))]\n (case d 2 0.05 4 0.15 (+ 0.1 (* 0.05 d)))))))\n\n(defn- points-in [pts a b] (filterv (fn [p] (and (>= (:t p) (- a eps)) (< (:t p) (- b eps)))) pts))\n\n(defn span-options\n \"Every division of the span [s, s+L) for the points that fall in it ({:t :kind :on|:off :note i}),\n cheapest first: [{:n :tup :cost}]. merged?: two beats together (only the :merge divisions).\"\n [s L units pts o merged?]\n (let [W (:w o)\n divs (distinct (concat (if merged?\n (:merge o)\n (concat (:divs o) (map (fn [k] (* units k)) [1 2 4])\n (when-let [st (:step o)] (let [n (/ L st)] (when (and (whole? n) (<= n 16)) [(js/Math.round n)])))))))]\n (->> (for [n divs\n :when (and (<= 1 n 24) (not (and merged? (= 1 n))))\n :let [tup (tuplet-of L n)]\n :when (not= :none tup)\n :let [g (/ L n)\n ks (mapv (fn [p] (js/Math.round (/ (- (:t p) s) g))) pts)\n err (reduce + (map (fn [p k] (* (if (= :on (:kind p)) 1 (:off W)) (js/Math.abs (- (:t p) (+ s (* k g))))))\n pts ks))\n ons (filter (fn [[p _]] (= :on (:kind p))) (map vector pts ks))\n ;; starts that meet on one point though they were not together: one is lost (or a chord)\n clash (reduce + (for [[_ grp] (group-by second ons) :when (> (count grp) 1)\n :let [ts (map (comp :t first) grp)]]\n (if (> (- (apply max ts) (apply min ts)) (:chord o)) (dec (count grp)) 0)))\n ;; a note that starts and ends on the same point vanishes\n gone (count (filter (fn [[_ xs]] (and (= 2 (count xs)) (apply = (map second xs))))\n (group-by (comp :note first) (map vector pts ks))))\n deep (reduce + (map (fn [p k] (* (if (= :on (:kind p)) 1 (:off W)) (depth L n k))) pts ks))\n cost (+ (* (:err W) err)\n (* (:cpx W) (+ (complexity L n) deep (if merged? 0.1 0)))\n (* (:lost W) (+ clash gone)))\n ;; the division its notes need: the fewest points that hold the same ones (two eighths on\n ;; a grid of six need two)\n need (/ n (reduce gcd n ks))]]\n {:n n :tup tup :cost cost :need need})\n (sort-by :cost)\n vec)))\n\n(defn- nested-of\n \"The span cut in parts (halves of a beat, the three eighths of a dotted beat), each with its own\n cheapest division, when one of them needs a tuplet the whole span cannot give; or nil.\"\n [s L u pts o]\n (let [k (cond (and (= u 3) (zero? (mod (* 64 L) 3))) 3 (or (= u 1) (= u 2)) 2 :else nil)]\n (when (and k (:nest o))\n (let [pl (/ L k)\n parts (mapv (fn [i] (let [ps (+ s (* i pl))]\n (assoc (first (span-options ps pl (/ u k) (points-in pts ps (+ ps pl)) o false)) :s ps :L pl)))\n (range k))]\n (when (some :tup parts)\n {:s s :L L :n k :tup nil :parts parts\n :cost (+ (reduce + (map :cost parts)) (* (:cpx (:w o)) 0.15))})))))\n\n(defn best-of-span\n \"The cheapest way to divide one span [s, s+L) of u units: a division of the whole span, or the span cut\n in parts (halves of a beat, the three eighths of a dotted beat) each with its own division, when one of\n them needs a tuplet the whole span cannot give (an eighth and a triplet of sixteenths). {:s :L :n :tup\n :cost}, with :parts [regions] when it is cut.\"\n [s L u pts o]\n (let [flat (assoc (first (span-options s L u (points-in pts s (+ s L)) o false)) :s s :L L)\n nested (nested-of s L u pts o)]\n (if (and nested (< (:cost nested) (:cost flat))) nested flat)))\n\n(defn- span-candidates\n \"The few cheapest ways to divide a span (issue #108: the plan of a bar chooses among them with its\n neighbours in view): the best divisions of the whole span, and the span cut in parts.\"\n [s L u pts o]\n (let [in (points-in pts s (+ s L))]\n (vec (concat (map (fn [x] (assoc x :s s :L L)) (take 4 (span-options s L u in o false)))\n (when-let [x (nested-of s L u pts o)] [x])))))\n\n(defn family\n \"The kind of division a region has, for coherence between neighbours (issue #108): :none when it puts\n one point on the span (the beat alone: it says nothing), :bin for written values (halves, quarters, the\n eighths of a dotted beat), and for a tuplet the largest prime of its count (3, 5, 7…), all by the\n points its notes use (:need), not the grid it is written on: two eighths on a grid of six are binary.\n A span cut in parts has the family of its tuplet part.\"\n [r]\n (let [m (or (:need r) (:n r))\n tup (if (and (:need r) (:L r)) (tuplet-of (:L r) m) (:tup r))]\n (cond (:parts r) (or (some (fn [p] (let [f (family p)] (when (number? f) f))) (:parts r)) :bin)\n (= 1 m) :none\n (vector? tup) (largest-prime (first tup))\n :else :bin)))\n\n(defn- after\n \"The family in force after a region: its own, or the one before when it says nothing.\"\n [fam r] (let [f (family r)] (if (= f :none) fam f)))\n\n(defn- switch-cost\n \"What it costs to go from one family to another between neighbouring regions (:coh of the weights): a\n lone triplet among eighths pays twice, a run of triplets once.\"\n [fam r o]\n (let [f (family r)]\n (if (or (= f :none) (= fam :none) (= f fam)) 0 (or (:coh (:w o)) 0))))\n\n(def ^:private forced -1e6)\n\n(defn- fix-at [o s] (some (fn [[k v]] (when (near? k s) v)) (:fix o)))\n(defn- merge-choice? [c] (and (vector? c) (= :merge (first c))))\n\n(defn- choose-span\n \"The division c chosen for the span [s, s+L) (n, or [n1 n2 …] for its parts) as a region that the plan\n takes whatever it costs, or nil when the span cannot take it.\"\n [s L u pts o c]\n (let [with (fn [ps pl pu n] (some-> (first (filter (fn [x] (= n (:n x)))\n (span-options ps pl pu (points-in pts ps (+ ps pl)) (update o :divs conj n) false)))\n (assoc :s ps :L pl)))]\n (cond (number? c) (some-> (with s L u c) (assoc :cost forced))\n (and (vector? c) (number? (first c)))\n (let [k (count c) pl (/ L k)\n parts (mapv (fn [i n] (with (+ s (* i pl)) pl (/ u k) n)) (range k) c)]\n (when (every? some? parts) {:s s :L L :n k :tup nil :parts parts :cost forced}))\n :else nil)))\n\n(defn bar-plan\n \"The cheapest way to divide one bar (it starts at beat b0) for the points in it: its regions\n [{:s :L :n :tup :cost}] in order, each a span (or two beats together) with its division. Each span\n weighs its few cheapest divisions with its neighbours in view: changing kind of division (binary,\n triplet, quintuplet…) from one region to the next costs (:coh, issue #108). fam is the kind in force\n before the bar (the one the bar before ended with).\"\n ([b0 meter pts o] (bar-plan b0 meter pts o :none))\n ([b0 meter pts o fam]\n (let [{[_ q] :meter g :groups} (mt/meter-of meter)\n sps (mapv (fn [[s L u]] [(+ b0 s) L u]) (spans meter))\n n (count sps)\n simple? (and (<= q 4) (empty? g))\n ;; a division chosen by hand (:fix) is the only candidate there; else the few cheapest\n single (mapv (fn [[s L u]] (or (let [c (fix-at o s)] (when (and c (not (merge-choice? c))) (some-> (choose-span s L u pts o c) vector)))\n (span-candidates s L u pts o)))\n sps)\n merged (fn [i] (when (and simple? (even? i) (< (inc i) n) (near? (second (sps i)) (second (sps (inc i)))))\n (let [[s L u] (sps i) c (fix-at o s) mc (when (merge-choice? c) (second c))\n xs (span-options s (* 2 L) (* 2 u) (points-in pts s (+ s L L)) (cond-> o mc (update :merge conj mc)) true)]\n (if mc\n (some-> (first (filter (fn [x] (= mc (:n x))) xs)) (assoc :cost forced :s s :L (* 2 L)) vector)\n (when (seq (:merge o)) (mapv (fn [x] (assoc x :s s :L (* 2 L))) (take 2 xs)))))))\n ;; states: at each span boundary, for each family in force, the cheapest [cost path]\n add (fn [m f c p] (if (or (nil? (m f)) (< c (first (m f)))) (assoc m f [c p]) m))\n step (fn [st i j rs] (reduce (fn [st [f [c p]]]\n (reduce (fn [st r] (update st j add (after f r) (+ c (:cost r) (switch-cost f r o)) (conj p r))) st rs))\n st (st i)))\n st (reduce (fn [st i]\n (cond-> (step st i (inc i) (single i))\n (merged i) (step i (+ i 2) (merged i))))\n (assoc (vec (repeat (inc n) {})) 0 {fam [0 []]})\n (range n))\n [_ path] (apply min-key first (vals (st n)))]\n ;; a span divided in parts is as many regions\n (vec (mapcat (fn [r] (or (:parts r) [r])) path)))))\n\n;; ───────── 3. the notes on the points ─────────\n\n(defn- region-at [rs t] (first (filter (fn [r] (and (>= t (- (:s r) eps)) (< t (- (+ (:s r) (:L r)) eps)))) rs)))\n\n(defn- snap [rs t]\n (if-let [r (region-at rs t)]\n (let [g (/ (:L r) (:n r))] (cv/round-to (+ (:s r) (* g (js/Math.round (/ (- t (:s r)) g)))) 9))\n t))\n\n(defn- unit-at [rs t] (if-let [r (region-at rs t)] (/ (:L r) (:n r)) 1))\n\n(defn- first-attrs [a first?] (if first? a (dissoc a :gliss :art :dyn :text)))\n\n(defn- region-nodes\n \"The nodes of the segments that fall in [a, b): notes, chords and rests, cut where the region cuts\n them (the piece before a cut is tied: :tie), with the grace notes before a segment's first piece.\n tup: written durations are the sounding ones × n/m.\"\n [a b tup segs graces]\n (vec (mapcat (fn [sg]\n (let [x (max (:s sg) a) e (min (:e sg) b)]\n (when (> e (+ x eps))\n (let [;; written values live on a lattice of 1/128 beat (dyadic, or dotted)\n wd (/ (js/Math.round (* 128 (if tup (* (- e x) (/ (first tup) (second tup))) (- e x)))) 128)\n first? (near? x (:s sg))\n tie? (and (:notes sg) (> (:e sg) (+ e eps)))\n ns (:notes sg)]\n (concat\n (when (and first? ns)\n (for [gn (get graces (cv/round-to (:s sg) 6))]\n [:note (assoc (dissoc (:attrs gn) :gliss :dur) :grace true)]))\n [(cond (nil? ns) [:rest {:dur wd}]\n (= 1 (count ns)) [:note (cond-> (assoc (first-attrs (:attrs (first ns)) first?) :dur wd) tie? (assoc :tie true))]\n :else (into [:chord (cond-> {:dur wd} tie? (assoc :tie true))]\n (for [n ns] [:note (first-attrs (:attrs n) first?)])))])))))\n segs)))\n\n(defn- clean [notes]\n (vec (sort-by (juxt :on (fn [n] (if (:grace? n) 0 1)) (fn [n] (- (or (mt/midi-of (:attrs n)) 0))))\n (filter (fn [n] (and (number? (:on n)) (number? (:off n)) (>= (:on n) 0) (> (:off n) (:on n)))) notes))))\n\n(defn- legato\n \"A note released just before the next one of its voice starts (less than :legato beats before it, and\n less than half the time between their starts) reaches it: a small gap is not a rest.\"\n [notes o]\n (let [ons (vec (distinct (map :on notes)))]\n (mapv (fn [n]\n (if-let [nx (when-not (:grace? n) (first (filter (fn [t] (> t (+ (:on n) (:chord o)))) ons)))]\n (let [gap (- nx (:off n))]\n (if (and (pos? gap) (< gap (:legato o)) (< gap (* 0.5 (- nx (:on n))))) (assoc n :off nx) n))\n n))\n notes)))\n\n(defn separate\n \"Notes in free time as voices that do not overlap (beyond :overlap beats): notes that start and end\n together stay together (a chord); each one goes to a voice that is free when it starts, the nearest in\n pitch to that voice's last note, or to a new one, up to :voices; past that, to the voice that ends\n first (whose last note it cuts). The highest voice first.\"\n [notes o]\n (let [notes (clean notes)\n pitch-of (fn [n] (or (mt/midi-of (:attrs n)) 60))\n mean (fn [ns] (/ (reduce + (map pitch-of ns)) (count ns)))\n together? (fn [a b] (and (< (js/Math.abs (- (:on a) (:on b))) (+ (:chord o) eps))\n (< (js/Math.abs (- (:off a) (:off b))) (max (:chord o) (* 0.25 (- (:off b) (:on b)))))))\n events (reduce (fn [evs n] (let [lst (peek evs)] (if (and lst (together? (first lst) n)) (conj (pop evs) (conj lst n)) (conj evs [n]))))\n [] notes)\n vs (reduce (fn [vs ev]\n (let [on (:on (first ev)) off (reduce max (map :off ev)) p (mean ev)\n free (filter (fn [i] (<= (:end (vs i)) (+ on (:overlap o)))) (range (count vs)))\n pick (cond (seq free) (apply min-key (fn [i] (+ (js/Math.abs (- p (:pitch (vs i)))) (* 0.01 i))) free)\n (< (count vs) (:voices o)) nil\n :else (apply min-key (fn [i] (:end (vs i))) (range (count vs))))]\n (cond\n ;; notes together while several voices are free: each to the nearest of them\n (and (> (count ev) 1) (> (count free) 1))\n (reduce (fn [vs [i ns]] (update vs i (fn [v] (-> v (assoc :end (reduce max (map :off ns)) :pitch (mean ns)) (update :notes into ns)))))\n vs (group-by (fn [n] (apply min-key (fn [i] (js/Math.abs (- (pitch-of n) (:pitch (vs i))))) free)) ev))\n (nil? pick) (conj vs {:end off :pitch p :notes (vec ev)})\n :else (update vs pick (fn [v] (-> v (assoc :end off :pitch p) (update :notes into ev)))))))\n [] events)]\n (mapv :notes (sort-by (fn [v] (- (mean (:notes v)))) vs))))\n\n(defn- bar-len [meter] (let [{[p q] :meter} meter] (* p (/ 4 q))))\n\n(defn bars\n \"The bars notes ending at maxoff (starting last at maxon) are written in: [{:b0 :L :meter}], each in its\n meter (:meters, the last going on; else :meter). A last bar where nothing starts and the ends would go back\n to its start is not a bar.\"\n [o maxoff maxon]\n (let [ms (or (:meters o) [(:meter o)])\n meter-at (fn [i] (get ms i (peek ms)))\n bs (loop [i 0 b0 0 out []]\n (let [m (meter-at i) L (bar-len m) out (conj out {:b0 b0 :L L :meter m})]\n (if (< (+ b0 L) (- maxoff eps)) (recur (inc i) (+ b0 L) out) out)))\n lst (peek bs)\n [_ L1] (first (spans (:meter lst)))]\n (if (and (> (count bs) 1) (< maxon (- (:b0 lst) eps)) (< (- maxoff (:b0 lst)) (* 0.5 L1))) (pop bs) bs)))\n\n(defn bar-at \"The bar of a plan that holds beat t (the last one past the end).\" [bs t]\n (or (first (filter (fn [b] (< t (- (+ (:b0 b) (:L b)) eps))) bs)) (peek bs)))\n\n(defn plan\n \"How the bars are divided for all these notes together (every voice on the same points): its bars\n [{:b0 :L :meter}], and the regions [{:s :L :n :tup}] of every bar. (:meter and :BL are those of the first.)\"\n [notes o]\n (let [maxoff (reduce max 0 (map :off notes))\n maxon (reduce max 0 (map :on notes))\n bs (bars o maxoff maxon)\n pts (vec (sort-by :t (mapcat (fn [i n] [{:t (:on n) :kind :on :note i} {:t (:off n) :kind :off :note i}]) (range) notes)))]\n {:meter (:meter (first bs)) :BL (:L (first bs)) :bars bs :nbars (count bs)\n :total (let [b (peek bs)] (+ (:b0 b) (:L b)))\n ;; bar by bar, each starting from the kind of division the one before ended with (issue #108)\n :rs (first (reduce (fn [[rs fam] {:keys [b0 L meter]}]\n (let [bar (bar-plan b0 meter (points-in pts b0 (+ b0 L)) o fam)]\n [(into rs bar) (reduce after fam bar)]))\n [[] :none] bs))}))\n\n(defn write-voice\n \"One voice's notes (already free of overlaps but for small ones, which are cut) written on a plan as a\n :voice of measures: chords where starts meet, rests in the gaps, ties over barlines and out of tuplets,\n grace notes for notes that shrink to nothing.\"\n [notes {:keys [bars total rs]} o]\n (let [qs (mapv (fn [n] (assoc n :qon (snap rs (:on n)) :qoff (min total (snap rs (:off n))))) notes)\n collapsed? (fn [n] (<= (:qoff n) (+ (:qon n) eps)))\n starts (set (map (fn [n] (cv/round-to (:qon n) 6)) (remove collapsed? qs)))\n grace? (fn [n] (and (:grace o) (collapsed? n) (contains? starts (cv/round-to (:qon n) 6))))\n graces (group-by (fn [n] (cv/round-to (:qon n) 6)) (filter grace? qs))\n real (->> qs (remove grace?)\n (map (fn [n] (if (collapsed? n) (assoc n :qoff (min total (+ (:qon n) (unit-at rs (:qon n))))) n)))\n (remove collapsed?))\n groups (sort-by key (group-by (fn [n] (cv/round-to (:qon n) 6)) real))\n sounding (map-indexed (fn [j [_ ns]]\n (let [nxt (some-> (nth groups (inc j) nil) second first :qon)]\n {:s (:qon (first ns)) :e (min (or nxt js/Infinity) (reduce max (map :qoff ns)))\n :notes (vec (sort-by (fn [n] (mt/midi-of (:attrs n))) ns))}))\n groups)\n segs (loop [ss sounding t 0 out []]\n (if (empty? ss)\n (if (< t (- total eps)) (conj out {:s t :e total}) out)\n (let [sg (first ss)]\n (recur (rest ss) (:e sg) (cond-> out (> (:s sg) (+ t eps)) (conj {:s t :e (:s sg)}) true (conj sg))))))\n ;; a bar says its meter when it is the first, or when the meter changes\n bar-attrs (fn [i {{[p q] :meter g :groups} :meter}]\n (let [prev (when (pos? i) (:meter (bars (dec i))))]\n (cond-> {}\n (or (zero? i) (not= (select-keys prev [:meter :groups]) (select-keys (:meter (bars i)) [:meter :groups])))\n (merge (cond-> {:meter [p q]} (seq g) (assoc :groups (vec g))))\n (and (zero? i) (some? (:key o))) (assoc :key (:key o)))))]\n (into [:voice {}]\n (for [[i {:keys [b0 L] :as bar}] (map-indexed vector bars)\n :let [BL L\n ;; a tuplet only for a voice that starts or ends something inside it (a note of\n ;; this voice held through another voice's triplet is not written in a triplet)\n inside? (fn [r] (some (fn [x] (< (+ (:s r) eps) x (- (+ (:s r) (:L r)) eps))) (mapcat (juxt :s :e) segs)))\n regs (mapv (fn [r] (if (and (:tup r) (not (inside? r))) (assoc r :tup nil) r))\n (filterv (fn [r] (and (>= (:s r) (- b0 eps)) (< (:s r) (- (+ b0 BL) eps)))) rs))\n ;; plain regions next to each other are written together; a tuplet on its own\n runs (reduce (fn [acc r]\n (let [lst (peek acc)]\n (if (and lst (nil? (:tup lst)) (nil? (:tup r)))\n (conj (pop acc) (update lst :L + (:L r)))\n (conj acc (select-keys r [:s :L :tup])))))\n [] regs)]]\n (into [:measure (bar-attrs i bar)]\n (mapcat (fn [{:keys [s L tup]}]\n (let [ns (region-nodes s (+ s L) tup segs graces)]\n (if tup [(into [:tuplet {:ratio tup}] ns)] ns)))\n runs))))))\n\n(defn graces-first\n \"Notes played as grace notes (shorter than :grace-dur beats, starting less than 0.15 beat before a note at\n least twice as long, which is not part of a run of short notes) moved onto the note they lead into, with\n almost no length: they are written as its grace notes and do not ask for a fine division of the beat.\"\n [notes o]\n (if-not (:grace o)\n notes\n (let [g (or (:grace-dur o) 0.1)\n ns (vec (sort-by :on notes))\n n (count ns)]\n (vec (map-indexed\n (fn [i x]\n (let [d (- (:off x) (:on x))\n nxt (first (filter (fn [y] (> (:on y) (+ (:on x) 0.01))) (subvec ns (inc i))))]\n (if (and nxt (< d g) (< (- (:on nxt) (:on x)) 0.15) (>= (- (:off nxt) (:on nxt)) (* 2 d)) (>= (- (:off nxt) (:on nxt)) 0.2))\n (assoc x :on (:on nxt) :off (+ (:on nxt) 1e-4) :grace? true)\n x)))\n ns)))))\n\n(defn- voices-of-notes [notes o] (mapv (fn [ns] (legato ns o)) (let [ss (separate (graces-first notes o) o)] (if (seq ss) ss [[]]))))\n\n(defn notes->voices\n \"Notes in free time ({:on :off :attrs}, beats; :attrs those of the :note each becomes) as voices of\n measures, quantized with the options o (see `options`): separated where they overlap (at most\n :voices), all on one plan, the voices after the first as layers of its staff. nm names them.\"\n ([notes o] (notes->voices notes o nil))\n ([notes o nm]\n (let [vs (voices-of-notes notes o)\n pl (plan (vec (remove :grace? (apply concat vs))) o)\n staff (or nm \"voice 1\")]\n (vec (map-indexed (fn [i ns]\n (let [v (write-voice ns pl o)]\n (cond\n (= 1 (count vs)) (if nm (mt/update-attrs v assoc :name nm) v)\n :else (mt/update-attrs v assoc\n :name (if (and nm (zero? i)) nm (str (or nm \"voice\") \" \" (inc i)))\n :staff staff))))\n vs)))))\n\n(defn notes->voice\n \"Notes in free time as one voice of measures (overlapping notes are cut where the next one starts).\"\n [notes o]\n (first (notes->voices notes (assoc o :voices 1))))\n\n;; ───────── choosing another division (stage 6) ─────────\n\n(defn choices\n \"How the beat (or group) that holds beat t can be divided, for these notes in free time: {:s its start\n :pair the start of the two beats it can go with (or nil) :current the division the plan gives it\n :all [the current one, then the others, cheapest first]}. A division is n, [n1 n2] (in parts) or\n [:merge n] (with the next beat).\"\n [notes o t]\n (let [notes (first (timed notes o))\n all-notes (vec (remove :grace? (apply concat (voices-of-notes notes o))))\n {:keys [rs bars]} (plan all-notes o)\n current-in (fn [rs s L]\n (let [here (filterv (fn [r] (and (> (+ (:s r) (:L r)) (+ s eps)) (< (:s r) (- (+ s L) eps)))) rs)]\n (cond (and (= 1 (count here)) (near? (:L (first here)) L)) (:n (first here))\n (and (= 1 (count here)) (> (:L (first here)) (+ L eps))) [:merge (:n (first here))]\n :else (mapv :n here))))\n pts (vec (mapcat (fn [i n] [{:t (:on n) :kind :on :note i} {:t (:off n) :kind :off :note i}]) (range) all-notes))\n {:keys [b0 meter]} (bar-at bars t)\n {[_ q] :meter g :groups} meter\n sps (mapv (fn [[s L u]] [(+ b0 s) L u]) (spans meter))\n i (or (first (keep-indexed (fn [i [s L]] (when (and (>= t (- s eps)) (< t (- (+ s L) eps))) i)) sps)) 0)\n [s L u] (sps i)\n simple? (and (<= q 4) (empty? g))\n pair (when simple? (cond (and (even? i) (< (inc i) (count sps)) (near? L (second (sps (inc i))))) i\n (and (odd? i) (near? L (second (sps (dec i))))) (dec i)))\n in (points-in pts s (+ s L))\n ;; divisions that put the notes on other points (6 places a triplet where 3 does: it is not another choice)\n flat (->> (span-options s L u in o false)\n (reduce (fn [[seen out] x]\n (let [g (/ L (:n x)) k (mapv (fn [p] (cv/round-to (* g (js/Math.round (/ (- (:t p) s) g))) 6)) in)]\n (if (contains? seen k) [seen out] [(conj seen k) (conj out (:n x))])))\n [#{} []])\n second (take 5))\n nested (let [x (best-of-span s L u pts (assoc o :nest true))] (when (:parts x) [(mapv :n (:parts x))]))\n merged (when pair\n (let [[ps pL pu] (sps pair)]\n (map (fn [x] [:merge (:n x)])\n (take 2 (span-options ps (* 2 pL) (* 2 pu) (points-in pts ps (+ ps pL pL)) (assoc o :merge [3 5 6]) true)))))\n current (current-in rs s L)\n ;; the order does not depend on what was chosen: the quantizer's own choice first\n free-o (update o :fix (fn [f] (into {} (remove (fn [[x _]] (or (near? x s) (and pair (near? x (first (sps pair)))))) f))))\n own (current-in (:rs (plan all-notes free-o)) s L)\n all (vec (distinct (concat [own] flat nested merged)))]\n {:s s :pair (when pair (first (sps pair))) :current current\n :all (if (some #{current} all) all (conj all current))}))\n\n(defn next-choice\n \"The next way to divide the beat that holds t (see `choices`), as the options with that choice in\n their :fix: {:choice c :s span-start :opts opts'}. opts are the options as they are kept (with :fix).\"\n [notes opts gx t]\n (let [{:keys [s pair current all]} (choices notes (options opts gx) t)\n c (nth all (mod (inc (max 0 (.indexOf all current))) (count all)))\n k (if (merge-choice? c) pair s)\n fix (into {} (remove (fn [[x _]] (or (near? x s) (and pair (near? x pair)))) (:fix opts)))]\n {:choice c :s k :opts (assoc (if (map? opts) opts {}) :fix (assoc fix k c))}))\n\n;; ───────── what is quantized ─────────\n\n(defn strokes->notes\n \"The strokes of a freqt as notes in free time: each one a note at the pitch of its first point (with\n decimals when it is between semitones), its bends a :gliss, as mt/<-strokes reads them.\"\n [d]\n (vec (for [[_ s] (cv/sorted-strokes d)\n :let [pts (:pts s) [t0 f0] (first pts) [t1 _] (peek pts)\n m (cv/hz->midi f0) mr (js/Math.round m)\n dur (max 0.01 (- t1 t0))\n gl (mapv (fn [[t f]] [(cv/round-to (/ (- t t0) dur) 3) (+ 0 (cv/round-to (cv/hz->cents f (cv/midi->hz mr)) 1))]) pts)\n flat? (every? (fn [[_ c]] (< (js/Math.abs (- c (second (first gl)))) 1)) gl)]]\n ;; numbers: the names are chosen afterwards, all together (mt/spell, issue #88)\n {:on t0 :off (+ t0 dur)\n :attrs (cond-> {:pitch (if (< (js/Math.abs (- m mr)) 0.02) mr (cv/round-to m 2))}\n (not flat?) (assoc :pitch mr :gliss gl)\n ;; the weight of a stroke is how strong its note was (as an event's :amp: 0.4 … 2.8 → 0 … 1):\n ;; transcribe writes the strength of each attack so (issue #106)\n (number? (get-in s [:look :w])) (assoc :vel (cv/round-to (max 0 (min 1 (/ (- (get-in s [:look :w]) 0.4) 2.4))) 3)))})))\n\n(defn quantize\n \"A freqt's buffer as a measured tree (a :voice of :measure nodes), with options (see the top of this\n file); its meter comes from the buffer's bar grid unless :meter is given.\"\n ([d] (quantize d {}))\n ([d opts]\n (let [o (options opts (:gx d))\n [ns m] (timed (strokes->notes d) o)\n vs (notes->voices ns o)\n t (if (= 1 (count vs)) (first vs) (into [:par {}] vs))\n tempo (or (:tempo opts) (when m (js/Math.round (tm/tempo-of-map m))))]\n (respell-by-hand (mt/spell (cond-> t tempo (mt/update-attrs assoc :tempo tempo))) (:spell o)))))\n\n(defn tree-notes\n \"The notes of a tree without measures as notes in free time ({:on :off :attrs :voice}): a written name\n stays (with its :cents), numbers stay numbers (they are spelled afterwards).\"\n [tree]\n (let [xt (mt/expand tree)]\n (vec (for [e (mt/events xt) :when (and (= :note (:kind e)) (not (:grace e)))]\n {:on (:t e) :off (+ (:t e) (:dur e)) :voice (:voice e)\n :attrs (merge (select-keys e [:art :dyn :text :vel :env :gliss])\n (let [a (mt/attrs (mt/node-at xt (:path e))) w (mt/spelling-of a)]\n (if w\n (cond-> {:pitch (sp/->name w)} (:cents a) (assoc :cents (:cents a)))\n {:pitch (if (whole? (:pitch e)) (js/Math.round (:pitch e)) (cv/round-to (:pitch e) 2))})))}))))\n\n(defn tree-options\n \"The options a tree without measures is quantized with: its root's :quant (how its score is quantized,\n as a freqt keeps them in its buffer) under the ones given, and its root's :grid for the meter.\"\n [tree opts]\n (let [a (mt/attrs (mt/expand tree))]\n (options (merge (:quant a) opts) (:grid a))))\n\n(defn quantize-tree\n \"A tree without measures (notes placed in free time, with :at or durations of any size) as a measured\n tree: each of its voices quantized on its own, in the meter of the options (or of its root's :grid;\n 4/4 by default). Its root's :quant are options too.\"\n ([tree] (quantize-tree tree {}))\n ([tree opts]\n (let [o (tree-options tree opts)\n ;; played time onto beats, all voices through one map (issue #106)\n [ns m] (timed (tree-notes tree) o)\n ;; played time: the error of a note is weighed in seconds, not in beats — 30 ms off is as much at 220 bpm as\n ;; at 80, though it is a larger part of a beat (the Weimar Jazz Database, issue #106). At ref-bpm the\n ;; weight is the one given; faster, it is less (less chasing of fine divisions), down to a third.\n o (if-let [r (and m (number? (:ref-bpm o)) (pos? (:ref-bpm o)) (:ref-bpm o))]\n (let [f (js/Math.min 1 (js/Math.max 0.33 (/ r (tm/tempo-of-map m))))] (update-in o [:w :err] * f))\n o)\n by-voice (sort-by key (group-by (fn [n] (or (:voice n) \"\")) ns))\n ;; a voice keeps its name; one without (named by mt/events v<depth>-<index>) stays without\n voices (fn [[nm ns]] (notes->voices (mapv (fn [n] (dissoc n :voice)) ns) o\n (when (and (seq nm) (not (re-matches #\"v\\d+-\\d*\" nm))) nm)))\n vs (vec (mapcat voices by-voice))\n t (if (> (count vs) 1) (into [:par {}] vs) (or (first vs) (notes->voice [] o)))]\n (respell-by-hand (mt/spell (mt/update-attrs t assoc :tempo (or (:tempo opts)\n (when m (js/Math.round (* (tm/tempo-of-map m) (/ (mt/tempo-of tree) 60))))\n (mt/tempo-of tree))))\n (:spell o)))))\n\n(defn measure-free-voices\n \"A measured tree whose voices without measures (a free voice beside the measured ones) are quantized\n in the meter of its first measure, so that the whole tree is written in measures.\"\n [tree]\n (let [x (mt/expand tree)\n first-m (first (filter (fn [n] (and (mt/node? n) (= :measure (mt/tag n)))) (tree-seq mt/node? mt/kids (mt/with-meters x))))\n meter (select-keys (mt/attrs first-m) [:meter :groups])\n free? (fn [v] (and (mt/node? v) (= :voice (mt/tag v)) (not (mt/measured? v))))]\n (if (and (= :par (mt/tag x)) (some free? (mt/kids x)) first-m)\n (mt/with-kids x (vec (mapcat (fn [k]\n (if (free? k)\n (let [q (quantize-tree k {:meter meter})]\n (if (= :par (mt/tag q)) (mt/kids q) [q]))\n [k]))\n (mt/kids x))))\n x)))\n\n(defn ->score\n \"MEI for a score: a measured tree as it is, a tree without measures quantized, a freqt's buffer\n quantized. Returns {:mei :pieces} (see mt/->mei).\"\n ([x pre] (->score x pre {}))\n ([x pre opts]\n (cond\n (and (mt/tree? x) (mt/measured? x)) (mt/->mei (measure-free-voices x) pre)\n (mt/tree? x) (mt/->mei (quantize-tree x opts) pre)\n :else (mt/->mei (quantize x opts) pre))))\n","kairotic/record.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · record\n;; Any stream of numbers written into a canvas (or a freqt) as strokes over time: an envelope from\n;; snapshot~, a descriptor from features~, a gesture on a knob, a position. Then it can be edited like\n;; any drawing and read again with reader~, as an automation.\n;;\n;; record [lo hi] [log] [tolerance]\n;; left: numbers; rec starts a take from 0 (its first write clears the buffer), stop ends it;\n;; rec t (a msg :rec 4, or [:rec 4]) records from t on: what was there before t stays, from t\n;; on it is replaced (punch-in); ovr t (msg :ovr 4) overwrites only what the take covers, from t\n;; to where it stops, and keeps what comes after (punch-in/out); ovr alone, from 0\n;; right: a bang ends the stroke that is being drawn; the next number begins another\n;; out: edits for the canvas (or freqt) on its inlet\n;;\n;; Senders such as snapshot~ only send what changed, so a value holds until the next one: the stroke is a\n;; staircase (each new value starts where the last one held), simplified within `tolerance` (in the units\n;; of the values; 1% of their range without it). Time is seconds from rec (a freqt reads them as beats:\n;; one a second, at 60). With lo hi the Y axis of a canvas is set to them (log with `log`); without them it\n;; follows the values; X follows the take. A freqt keeps its own axes and takes only values from 1 to\n;; 30000 (Hz). It writes at most every 2 seconds, each write one event of the history.\n\n(ns kairotic.record\n (:require [kairotic.components :as comp]))\n\n(def flush-every 2)\n(def max-points 2000)\n\n(defn r4 [x] (/ (js/Math.round (* x 10000)) 10000))\n\n(defn simplify\n \"Ramer–Douglas–Peucker for a time series: keeps the points whose value is more than eps away from the\n line between the ones kept around them (the error measured in value, not in a mixed distance).\"\n [pts eps]\n (if (< (count pts) 3)\n (vec pts)\n (let [pts (vec pts)\n keep? (fn keep? [a b acc]\n (if (<= (- b a) 1)\n acc\n (let [[ta va] (nth pts a) [tb vb] (nth pts b)\n dt (- tb ta)\n err (fn [i] (let [[t v] (nth pts i)\n line (if (zero? dt) va (+ va (* (- vb va) (/ (- t ta) dt))))]\n (js/Math.abs (- v line))))\n [i e] (reduce (fn [[bi be] i] (let [x (err i)] (if (> x be) [i x] [bi be]))) [a -1] (range (inc a) b))]\n (if (> e eps) (keep? i b (keep? a i (conj acc i))) acc))))\n idx (sort (keep? 0 (dec (count pts)) #{0 (dec (count pts))}))]\n (mapv (fn [i] (nth pts i)) idx))))\n\n(defn args-of\n \"lo hi tolerance (numbers in that order) and the word log, from the raw words of the box.\"\n [args]\n (let [ns (filterv number? args)]\n {:lo (get ns 0) :hi (get ns 1) :tol (get ns 2) :log (boolean (some #{:log} args))}))\n\n(defn tolerance [state]\n (or (:tol state)\n (let [lo (or (:lo state) (:min state)) hi (or (:hi state) (:max state))]\n (if (and lo hi (> hi lo)) (* 0.01 (- hi lo)) 0))))\n\n(defn axes\n \"The axes a canvas should have now, as edits (a freqt leaves them out).\"\n [state]\n (let [t1 (max 1 (:t-end state 0))\n ;; a take from t keeps the Y axis the canvas had (what is before t was drawn on it), unless lo hi\n lo (or (:lo state) (when-not (:from state) (:min state))) hi (or (:hi state) (when-not (:from state) (:max state)))\n [lo hi] (cond (and lo hi (< lo hi)) (if (:lo state) [lo hi] (let [m (* 0.05 (- hi lo))] [(- lo m) (+ hi m)]))\n (and lo hi) [(- lo 0.5) (+ hi 0.5)]\n :else nil)]\n ;; over a take (ovr) what comes after it stays: X is left as it was\n (cond-> (if (:ovr state) [] [[:axis :x 0 (r4 t1)]])\n lo (conj (cond-> [:axis :y (r4 lo) (r4 hi)] (and (:log state) (pos? lo)) (conj :log))))))\n\n(defn stroke-edit [state [id pts]]\n (let [ps (simplify pts (tolerance state))\n ps (if (> (count ps) max-points) (vec (take-nth (js/Math.ceil (/ (count ps) max-points)) ps)) ps)]\n (when (>= (count ps) 2) [:stroke id (mapv (fn [[t v]] [(r4 t) (r4 v)]) ps)])))\n\n(defn write-out\n \"[state edit later]: the strokes that changed since the last write, with the axes, as one [:batch …],\n at most every flush-every seconds (force: now).\"\n [state at force]\n (let [dirty (:dirty state)]\n (cond\n (empty? dirty) [state nil nil]\n (or force (nil? (:sent state)) (>= (- at (:sent state)) flush-every))\n (let [strokes (keep (fn [id] (stroke-edit state [id (get-in state [:strokes id])])) (sort-by name dirty))]\n ;; a stroke of one point waits for the next one (nothing is written, nothing is marked as sent)\n (if (seq strokes)\n [(cond-> (assoc state :dirty #{} :sent at :pending false :fresh false)\n (:ovr state) (assoc :cut-from (:t-end state)))\n [:batch (vec (concat (cond\n ;; ovr: what the take covered since the last write goes first (strokes kept\n ;; from before end there, those after begin where the take stops)\n (:ovr state) [[:cut (:cut-from state) (:t-end state)]]\n (:fresh state) [(if (:from state) [:cut (:from state)] [:clear])])\n (axes state) strokes))]\n nil]\n [state nil nil]))\n (:pending state) [state nil nil]\n :else [(assoc state :pending true) nil [(+ (:sent state) flush-every) 0 [:flush]]])))\n\n(defn add-value\n \"A value v at instant at: it continues the stroke being drawn (a step from where the last value held),\n or begins one.\"\n [state v at]\n (let [t (- at (:t0 state))\n id (:cur state)\n ;; ids of a take from t carry the take, so they do not replace strokes kept from an earlier one\n state (if id state (-> state (update :n inc)\n (as-> s (assoc s :cur (keyword (str \"r\" (when (:from s) (str (:take s) \"-\")) (:n s)))))))\n id (:cur state)\n pts (get-in state [:strokes id] [])\n [_ lv] (peek pts)\n pts (cond-> pts (and lv (not= lv v)) (conj [t lv]) true (conj [t v]))]\n (-> state\n (assoc-in [:strokes id] pts)\n (update :dirty conj id)\n (assoc :t-end t)\n (update :min (fn [m] (if (some? m) (min m v) v)))\n (update :max (fn [m] (if (some? m) (max m v) v))))))\n\n(defn end-stroke\n \"The stroke being drawn ends: held until now, so a value that never changed still has a length.\"\n [state at]\n (if-let [id (:cur state)]\n (let [t (- at (:t0 state)) [lt lv] (peek (get-in state [:strokes id]))]\n (cond-> (dissoc state :cur)\n (and lv (> t lt)) (-> (update-in [:strokes id] conj [t lv]) (update :dirty conj id) (assoc :t-end t))))\n state))\n\n(defn result [[st edit later]]\n (cond-> {:state st :show (select-keys st [:on :n])}\n edit (assoc :out [[0 edit]])\n later (assoc :later [later])))\n\n(comp/define! \"record\"\n {:doc \"Writes any stream of numbers into a canvas (or a freqt) as strokes over time: an envelope (snapshot~ 50 rms), a descriptor (features~), a knob, a position. :rec starts a take from 0 (its first write clears the buffer); :rec t (msg :rec 4) records from t seconds on, keeping what is before t and replacing what is after (punch-in); :ovr t (msg :ovr 4) overwrites only what the take covers, from t to where it stops, keeping what comes after (punch-in/out); :stop ends it; a bang on the right ends a stroke, and the next number begins another. A value holds until the next one (snapshot~ sends only what changed), simplified within tolerance (1% of the range without it). Time in seconds from rec. With lo hi the Y axis of a canvas is set to them (log with log); without them it follows the values. It writes at most every 2 seconds, each write one event of the history; then reader~ reads it back as an automation.\"\n :usage \"record [lo hi] [log] [tolerance]\"\n :license \"MPL-2.0\"\n :io [2 1]\n :size [124 30]\n :receive (fn [{:keys [inlet value state args at]}]\n (let [state (or state {})]\n (cond\n (or (#{:rec :ovr} value) (and (vector? value) (#{:rec :ovr} (first value))))\n (let [{:keys [lo hi tol log]} (args-of args)\n ovr (or (= value :ovr) (and (vector? value) (= :ovr (first value))))\n from (or (when (vector? value) (let [x (second value)] (when (and (number? x) (>= x 0)) x)))\n (when ovr 0))]\n {:state (cond-> {:on true :t0 (- at (or from 0)) :lo lo :hi hi :tol tol :log log :n 0 :strokes {}\n :dirty #{} :fresh true}\n from (assoc :from from :take (js/Math.round (* 1000 at)))\n ovr (assoc :ovr true :cut-from from))\n :show {:on true :n 0}})\n (not (:on state)) {}\n (= value :stop)\n (let [[st edit _] (write-out (end-stroke state at) at true)]\n (cond-> {:state (assoc st :on false) :show {:on false :n (:n st)}}\n edit (assoc :out [[0 edit]])))\n (= value [:flush]) (result (write-out (assoc state :pending false) at false))\n (= inlet 1) (result (write-out (end-stroke state at) at false))\n (and (number? value) (js/isFinite value)) (result (write-out (add-value state value at) at false))\n :else {})))\n :derive (fn [{:keys [shown]}]\n {:label (str (if (:on shown) \"● recording · \" \"record · \") (or (:n shown) 0)\n (if (= 1 (:n shown)) \" stroke\" \" strokes\"))})\n :view [[:rect {:x 2 :y 2 :w 120 :h 26 :r 3 :stroke :grid :fill :bg}]\n [:text {:x 8 :y 19 :size 10 :fill :soft} :$label]]})\n","kairotic/release.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · release (issue #45)\n;; A release is a compact history: one point per keyframe, each written as the changes from the one before,\n;; ending at the work as it is. Forgetting points of a history squashes them the same way. Both need the\n;; changes that turn one patch into another, as events of the history: patch-diff. And presets that\n;; travel with the patch (in its EDN, in links and embeds) keep only what changes between their keyframes:\n;; stored-presets.\n;;\n;; Pure: the page reads and writes the history (app/page/16-release.cljs).\n\n(ns kairotic.release\n (:require [clojure.string :as str]))\n\n;; ───────── the changes from one patch to another ─────────\n\n(def box-keys\n \"What a box keeps besides its text and place, and the event that sets each (nil removes it).\"\n [:present :view :size :recipe])\n\n(defn- set-ev [k id v]\n (case k\n :present (if v (into [:present id] v) [:present id nil])\n :view [:view id v]\n :size (if v (into [:size id] v) [:size id nil])\n :recipe [:recipe id v]))\n\n(defn patch-diff\n \"The events that turn patch p into patch q (top level; a sub-patch that changed is written whole, as the\n data of its box). Applying them in order, with the step of the history, gives q.\"\n [p q]\n (let [pb (:boxes p) qb (:boxes q)\n gone (sort (remove (fn [id] (contains? qb id)) (keys pb)))\n lines-p (set (:lines p)) lines-q (set (:lines q))\n ;; lines that a deleted box takes with it are not disconnected again\n alive? (fn [[a _ b _]] (and (contains? qb a) (contains? qb b)))\n ;; the order of lines is the order messages fan out in: kept as it is in q\n kept (filter (fn [l] (and (contains? lines-q l) (alive? l))) (:lines p))\n in-order? (= (vec (concat kept (remove lines-p (:lines q)))) (vec (:lines q)))\n old-lines (if in-order? (remove lines-q (:lines p)) (:lines p))\n new-lines (if in-order? (remove lines-p (:lines q)) (:lines q))]\n (vec\n (concat\n (for [id gone] [:delete id])\n (mapcat\n (fn [[id b]]\n (let [a (get pb id)\n new? (or (nil? a) (not (contains? pb id)))]\n (concat\n (cond new? [[:box id (:text b) (:x b) (:y b)]]\n :else (concat (when (not= (:text a) (:text b)) [[:text id (:text b)]])\n (when (or (not= (:x a) (:x b)) (not= (:y a) (:y b))) [[:move id (:x b) (:y b)]])))\n (for [k box-keys :when (not= (get a k) (get b k)) :when (or (not new?) (some? (get b k)))]\n (set-ev k id (get b k)))\n (when (and (not= (:data a) (:data b)) (or (not new?) (some? (:data b))))\n [[:data id (:data b)]]))))\n (sort-by key qb))\n (for [l old-lines :when (alive? l)] (into [:disconnect] l))\n (for [l new-lines] (into [:connect] l))))))\n\n(defn as-event\n \"Several events as one event of the history: nothing, the event itself, or a [:batch …].\"\n [evs]\n (case (count evs) 0 nil 1 (first evs) [:batch (vec evs)]))\n\n;; ───────── presets that travel with the patch ─────────\n\n(defn stored-presets\n \"Keyframes as presets a box can keep in its data: [{:label :kind :texts {id text}}], where :texts holds only\n the boxes whose text is not the same in all of them (with a single keyframe, every box). `kfs` is\n [{:label :kind :config {id text}}].\"\n [kfs]\n (let [cfgs (map :config kfs)\n ids (distinct (mapcat keys cfgs))\n changing (if (< (count kfs) 2)\n (set ids)\n (set (filter (fn [id] (not (apply = (map (fn [c] (get c id)) cfgs)))) ids)))]\n (vec (for [{:keys [label kind config]} kfs]\n (cond-> {:kind (or kind :snapshot)\n :texts (into (sorted-map) (filter (fn [[id _]] (changing id)) config))}\n (seq (str label)) (assoc :label (str label)))))))\n\n(defn sane-presets\n \"Stored presets as they may arrive from anyone (a link, a room): only labels, kinds and texts.\"\n [x]\n (if (sequential? x)\n (vec (for [p x :when (and (map? p) (map? (:texts p)))]\n (cond-> {:kind (if (keyword? (:kind p)) (:kind p) :snapshot)\n :texts (into (sorted-map) (for [[k v] (:texts p) :when (and (keyword? k) (string? v))] [k v]))}\n (string? (:label p)) (assoc :label (:label p)))))\n []))\n","kairotic/ring.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · ring and writer: a span of time for messages and the heads that write it (discussion \"Heads on a span\n;; of time\"; Studies 44 and 47). The model is kairotic.span; reader reads a ring (components.cljs).\n;;\n;; ring [seconds]\n;; left: any value, written where its time is (its implicit write head, a tape head: what is older than one\n;; turn is gone); a writer's edits ([:write p v mode], [:cut a b], [:erase]); :clear (empty, its time\n;; starts again at the next message); [:data] → what it keeps, on the left\n;; right outlet: the buffer, for a reader or a writer (on their right inlet); :start goes out on it when the\n;; ring's time starts, so a reader given a d begins to follow\n;;\n;; writer [ovr|mix] [jump s] [norm]\n;; left: what is written where the writer is; :rec t / :ovr t (msg :rec 2) send it to t, moving on at speed 1\n;; and replacing what it passes (:rec on a ring also erases everything, as rec t cuts what is after t);\n;; :stop holds it where it is\n;; middle: the buffer (a ring's right outlet), to know its length\n;; right: a position (seconds of the span, or 0…1 with norm), from any source — a ramp, a counter, a\n;; phasor~ through snapshot~. Moving, with ovr (the default) it erases what it passes; a move larger than\n;; its jump is a seek, which erases nothing between\n;; out: edits for the ring (its left inlet). Without a position, it writes where the ring's head is\n\n(ns kairotic.ring\n (:require [kairotic.components :as comp]\n [kairotic.span :as span]))\n\n(def tick 0.05)\n\n(defn- after-word\n \"The number after word k in the raw args (reader d 1 → 1).\"\n [args k]\n (let [x (second (drop-while #(not= k %) args))] (when (number? x) x)))\n\n;; ───────── ring ─────────\n\n(defn- summary [r at]\n {:dur (:dur r) :n (count (span/alive r at)) :on (boolean (:t0 r))\n :p (when-let [h (span/head r at)] (span/wrap r h))})\n\n(defn ring-receive [{:keys [state args value at]}]\n (let [dur (or (comp/num-of (first args)) 8)\n r (assoc (or state (span/ring dur)) :dur dur)\n done (fn [r2]\n (cond-> {:state r2 :show (summary r2 at)}\n ;; its time starts now: the readers on its buffer are told\n (and (nil? (:t0 r)) (:t0 r2)) (assoc :out [[1 :start]])))]\n (cond\n (nil? value) {}\n (= value :clear) {:state (span/ring dur) :show (summary (span/ring dur) at)}\n (and (vector? value) (= :write (first value)))\n (let [[_ p v mode] value] (done (span/write r at p v (or mode :mix))))\n (and (vector? value) (= :cut (first value)))\n (let [[_ a b] value] {:state (span/cut r at a b) :show (summary r at)})\n (= value [:erase]) {:state (span/erase r) :show (summary (span/erase r) at)}\n (= value [:data])\n {:out [[0 {:dur dur :events (mapv (fn [e] [(span/wrap r (:t e)) (:v e)]) (span/alive r at))}]]}\n :else (done (span/write r at value)))))\n\n(comp/define! \"ring\"\n {:doc \"A span of time for messages: it keeps what reached it in the last seconds (8 by default), each at its time. Its time starts at its first message; its write head goes round as a tape head, so what is older than one turn is gone. Its right outlet is the buffer for a reader (d behind, then a speed: a canon, a delay; or at a position from any source) and for a writer (several heads, anywhere, at any speed). :clear empties it, and its time starts again.\"\n :usage \"ring [seconds]\"\n :license \"MPL-2.0\"\n :io [1 2]\n :size [124 30]\n :receive ring-receive\n ;; its length from its text (what it shows comes only with its first message)\n :derive (fn [{:keys [shown args]}]\n {:label (str \"ring \" (comp/nice (or (comp/num-of (first args)) 8)) \" s · \" (or (:n shown) 0) \" kept\")})\n :view [[:rect {:x 2 :y 2 :w 120 :h 26 :r 13 :stroke :grid :fill :bg}]\n [:text {:x 10 :y 19 :size 10 :fill :soft} :$label]]})\n\n;; ───────── writer ─────────\n\n(defn writer-args [args]\n {:mode (if (some #{:mix} args) :mix :ovr)\n :jump (or (after-word args :jump) 0.5)\n :norm (boolean (some #{:norm} args))})\n\n(defn- clock-at [{:keys [clock]} at] (when clock (+ (:p clock) (- at (:at clock)))))\n\n(defn writer-receive [{:keys [state args inlet value at buffer]}]\n (let [{:keys [mode jump norm]} (writer-args args)\n st (or state {})\n l (when (span/ring? buffer) (:dur buffer))\n gen (inc (:gen st 0))\n cue (fn [kind t]\n (let [t (or t 0)]\n {:state (assoc st :clock {:at at :p t} :p t :gen gen)\n :out (if (= kind :rec) [[0 [:erase]]] [])\n :later [[(+ at tick) 0 [:tick gen]]]}))]\n (cond\n ;; the buffer's wire (:start when the ring's time starts): nothing to do\n (= inlet 1) {}\n ;; a position, from any source\n (= inlet 2)\n (if-let [u (comp/num-of value)]\n (let [q (if norm (* u (or l 1)) u)\n prev (when-not (:clock st) (:p st))\n p (if (and prev l) (+ prev (span/shortest l (mod prev l) q)) q)\n seek (or (nil? prev) (> (js/Math.abs (- p prev)) jump))]\n (cond-> {:state (-> st (assoc :p p :gen gen) (dissoc :clock))}\n (and (= mode :ovr) (not seek)) (assoc :out [[0 [:cut prev p]]])))\n {})\n ;; :rec t and :ovr t: to t, then at speed 1, replacing\n (or (#{:rec :ovr} value) (and (vector? value) (#{:rec :ovr} (first value))))\n (let [[kind t] (if (vector? value) value [value 0])]\n (cue kind (comp/num-of t)))\n (= value :stop) {:state (-> st (assoc :p (or (clock-at st at) (:p st)) :gen gen) (dissoc :clock))}\n ;; moving on its own clock it erases what it passes, a little at a time\n (comp/tick? value nil)\n (if (and (:clock st) (= (second value) (:gen st)))\n (let [p (clock-at st at)]\n {:state (assoc st :p p) :out [[0 [:cut (:p st) p]]] :later [[(+ at tick) 0 [:tick (:gen st)]]]})\n {})\n :else\n (let [p (or (clock-at st at) (:p st) :now)\n m (if (:clock st) :ovr mode)]\n ;; on its clock, first what it passed since the last tick is erased, then the value is written\n {:state (cond-> st (:clock st) (assoc :p p))\n :out (cond-> []\n (and (:clock st) (number? (:p st)) (not= p (:p st))) (conj [0 [:cut (:p st) p]])\n true (conj [0 [:write p value m]]))}))))\n\n(comp/define! \"writer\"\n {:doc \"A write head on a buffer (a ring): what reaches its left inlet is written where it is. Its position comes in on the right, from any source (a ramp, a counter, a phasor~ through snapshot~), in seconds of the span (0…1 with norm); without one it writes where the ring's head is. Moving, it replaces what it passes, as a tape head — silence too (ovr, the default) — or leaves it (mix); a move larger than its jump is a seek. :rec t / :ovr t send it to t, moving on at speed 1. Its outlet goes to the ring's left inlet; the ring's right outlet to its middle inlet.\"\n :usage \"writer [ovr|mix] [jump s] [norm]\"\n :license \"MPL-2.0\"\n :io [3 1]\n :reads-buffer true\n :receive writer-receive})\n","kairotic/ringaudio.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · ring~ and writer~: a span of sound and the heads that write it (discussion \"Heads on a span of time\";\n;; Studies 45 and 48). One AudioWorklet node per ring~ (kairotic/ringcore.mjs) holds the buffer and every head on\n;; it: the writer~ and reader~ boxes connected to its right outlet take a slot of that node, so they share the\n;; buffer and a feedback inside the ring is exact (a loop through other boxes costs a block, 128 samples).\n;;\n;; ring~ [seconds]\n;; left: the sound written where its time is (its own write head, a tape head: the last seconds are kept;\n;; with nothing on its left it does not write, and the ring is what its writer~s write); :clear\n;; right outlet: the buffer, for reader~ and writer~ (on their right / middle inlet)\n;;\n;; writer~ [ovr|mix [keep]] [jump s] [norm]\n;; left: the sound it writes; :rec t / :ovr t (from t at speed 1, replacing; rec erases the ring first);\n;; :stop holds it where it is\n;; middle: the ring~'s buffer\n;; right: a position signal (seconds, or 0…1 with norm; a phasor~); without one it writes where the ring's\n;; head is — ovr replaces what the ring writes there, mix adds to it\n;;\n;; reader~ on a ring~ (kairotic.signal): with a position signal on its left it reads there; without one it\n;; follows the ring's head d behind, then its speed (reader~ d 1 speed 0.5; msg :d 2, :speed −1).\n\n(ns kairotic.ringaudio\n (:require [kairotic.components :as comp]\n [kairotic.code :as code]))\n\n(def slots 8)\n\n(defonce modules (atom {}))\n\n(defn ready\n \"Promise that resolves when kairotic/ringcore.mjs is loaded as a worklet module in this AudioContext.\"\n [ac]\n (or (get @modules ac)\n (let [p (.addModule (.-audioWorklet ac) (.-href (js/URL. \"kairotic/ringcore.mjs\" (.-baseURI js/document))))]\n (swap! modules assoc ac p)\n p)))\n\n(defn handle? [x] (and (map? x) (= ::ring (:kind x))))\n\n(defn post!\n \"A message to the ring's node, once it is there (in the order they were sent).\"\n [h m]\n (when h (.then (:ready h) (fn [w] (when w (.postMessage (.-port w) (clj->js m)))))))\n\n(defn attach!\n \"A head takes a free slot of ring h: a promise of [worklet slot], or of nil when it is full or gone.\"\n [h opts]\n (.then (:ready h)\n (fn [w]\n (when (and w @(:alive h))\n (when-let [s (first (remove @(:used h) (range slots)))]\n (swap! (:used h) conj s)\n (post! h {:attach (assoc opts :slot s)})\n [w s])))))\n\n(defn detach! [h s]\n (when (and h s)\n (swap! (:used h) disj s)\n (post! h {:detach s})))\n\n(defn- after-word [args k] (let [x (second (drop-while #(not= k %) args))] (when (number? x) x)))\n\n(defn head-args\n \"What a reader~ or writer~ says about its head on a ring~: d, speed, jump, norm, ovr/mix, keep.\"\n [args]\n (cond-> {:norm (boolean (some #{:norm} args))}\n (after-word args :d) (assoc :d (after-word args :d))\n (after-word args :speed) (assoc :speed (after-word args :speed))\n (after-word args :jump) (assoc :jump (after-word args :jump))\n (some #{:mix} args) (assoc :write \"mix\" :keep (or (after-word args :mix) 1))))\n\n(defn head-message\n \"A message to a head (:d 2, :speed 0.5, :jump 1, :gain 0.5) as the change it makes, or nil.\"\n [v]\n (when (and (vector? v) (#{:d :speed :jump :gain :keep} (first v)) (number? (second v)))\n {(first v) (second v)}))\n\n;; ───────── a box that is a head of a ring~ (its node: :ring the ring it is on, :slot its slot) ─────────\n\n(defn hook!\n \"Puts the head of box node on ring h (nil: on none): it leaves the slot it had, takes one on h, and wires\n its input (and, for a reader, the slot's output) there.\"\n [node h role]\n (let [{:keys [ring slot]} node]\n (when-let [[w s] @slot]\n (try (.disconnect (:m node) w) (catch :default _ nil))\n (when-let [o (:out node)] (try (.disconnect w o) (catch :default _ nil)))\n (detach! @ring s))\n (reset! slot nil) (reset! ring h)\n (when h\n (-> (attach! h (merge {:role role} @(:opts node)))\n (.then (fn [ws]\n (when-let [[w s] ws]\n (if (and @(:alive node) (= h @ring))\n (do (reset! slot ws)\n (.connect (:m node) w 0 (inc s))\n (when-let [o (:out node)] (.connect w o s 0)))\n (detach! h s)))))))))\n\n(defn set-head!\n \"Changes the head of box node (kept for when it is hooked again).\"\n [node o]\n (swap! (:opts node) merge o)\n (when-let [[_ s] @(:slot node)] (post! @(:ring node) {:set (assoc o :slot s)})))\n\n(defn unhook! \"The box is gone: its head leaves the ring.\" [node] (reset! (:alive node) false) (hook! node nil nil))\n\n;; ───────── ring~ ─────────\n\n(comp/define! \"ring~\"\n {:doc \"A span of sound: it keeps the last seconds (8 by default) of what reaches its left inlet, written where its time is, going round as a tape head. Its right outlet is the buffer for reader~ (d behind its head, then a speed: a canon, a delay, an octave down at 0.5, backwards at −1; or at a position signal) and for writer~ (more heads, anywhere, from any signal). Up to 8 heads share one node, so a feedback inside the ring is exact. :clear silences it.\"\n :usage \"ring~ [seconds]\"\n :license \"MPL-2.0\"\n :io [1 2]\n :size [124 30]\n :receive (fn [{:keys [value]}] (if (= value :clear) {:effects [[:clear true]]} {}))\n :derive (fn [{:keys [args]}] {:label (str \"ring~ \" (comp/nice (or (comp/num-of (first args)) 8)) \" s\")})\n :view [[:rect {:x 2 :y 2 :w 120 :h 26 :r 13 :stroke :grid :fill :bg}]\n [:text {:x 10 :y 19 :size 10 :fill :soft} :$label]]\n :audio {:create (fn [ac b _]\n (let [len (or (comp/num-of (first (:args b))) 8)\n in (.createGain ac)\n w (atom nil) alive (atom true)\n p (-> (ready ac)\n (.then (fn [_]\n (when @alive\n (let [n (js/AudioWorkletNode.\n ac \"kairotic-ring\"\n (clj->js {:numberOfInputs (inc slots) :numberOfOutputs slots\n :outputChannelCount (vec (repeat slots 1))\n :channelCount 2 :channelCountMode \"explicit\" :channelInterpretation \"discrete\"\n :processorOptions {:len len :max 60 :slots slots}}))]\n (.connect in n 0 0)\n (reset! w n)\n n))))\n (.catch (fn [e] (js/console.error \"ring~\" e) nil)))]\n {:in in :inlets [[in 0]] :outlets []\n :ring {:kind ::ring :w w :ready p :used (atom #{}) :alive alive :len len}}))\n ;; with nothing on its left its own head does not write: the ring is only what its writer~s write\n :wired (fn [node ins] (post! (:ring node) {:own (contains? ins 0)}))\n :effects {:clear (fn [node _ _] (post! (:ring node) {:clear true}))}\n :dispose (fn [node]\n (reset! (:alive (:ring node)) false)\n (when-let [n @(:w (:ring node))] (try (.disconnect n) (catch :default _ nil)))\n (try (.disconnect (:in node)) (catch :default _ nil)))}})\n\n;; ───────── writer~ ─────────\n\n(comp/define! \"writer~\"\n {:doc \"A write head on a ring~: the sound on its left is written where it is, as a tape head — ovr (the default) replaces what is there, silence too; mix adds to it (mix 0.8: what was there fades a little at each pass). Its position: a signal on the right (seconds, or 0…1 with norm: a phasor~), any speed, either way — a jump larger than its jump is a seek; or, without one, the ring's head. :rec t / :ovr t send it to t, moving on at speed 1 (rec erases the ring first); :stop holds it. The ring~'s right outlet goes to its middle inlet.\"\n :usage \"writer~ [ovr|mix [keep]] [jump s] [norm]\"\n :license \"MPL-2.0\"\n :io [3 0]\n :reads-buffer true\n :receive (fn [{:keys [inlet value]}]\n (cond\n (not= inlet 0) {}\n (or (#{:rec :ovr} value) (and (vector? value) (#{:rec :ovr} (first value))))\n (let [[k t] (if (vector? value) value [value 0])] {:effects [[:cue {:kind (name k) :t (or (comp/num-of t) 0)}]]})\n (= value :stop) {:effects [[:cue {:kind \"stop\"}]]}\n (head-message value) {:effects [[:head (head-message value)]]}\n :else {}))\n :audio {:create (fn [ac b _]\n (let [vin (.createGain ac) pin (.createGain ac) m (.createChannelMerger ac 2)]\n (.connect vin m 0 0) (.connect pin m 0 1)\n {:m m :inlets [[vin 0] nil [pin 0]] :outlets []\n :fed (atom ::none) :ring (atom nil) :slot (atom nil) :alive (atom true) :folded (atom nil)\n :opts (atom (merge {:mode \"head\"} (head-args (:args b))))}))\n ;; a position signal on the right: it writes there; without one, where the ring's head is\n :wired (fn [node ins] (set-head! node {:mode (if (contains? ins 2) \"pos\" \"head\")}))\n :feed (fn [node d] (hook! node (when (handle? d) d) \"write\"))\n :effects {:cue (fn [node x _]\n (when-let [[_ s] @(:slot node)] (post! @(:ring node) {:cue (assoc x :slot s)})))\n :head (fn [node x _] (set-head! node x))}\n :dispose unhook!}})\n\n;; ───────── a faust~ in a loop of a ring~ runs inside it (Study 49) ─────────\n;; reader~ → faust~ → writer~, all on one ring~: the faust~'s compiled bytes go to the ring's node, where they run\n;; one sample at a time in the writer's slot, hearing those readers; the line from the faust~ to the writer~ is\n;; taken away (what it would bring, a block late, is already written). The faust~ keeps its own node for whatever\n;; else it is connected to (a dac~), and its parameters reach its copy in the ring as well. Every tick, after the\n;; nodes are fed: a loop that appears is folded, one that is gone unfolded.\n\n(defn loops\n \"The faust~ boxes in a loop of a ring~: [{:faust id :ring id :readers [id …] :writers [id …]}]. Every input of\n the faust~ comes from a reader~ on the ring, and its output reaches the left inlet of a writer~ on the same ring.\"\n [p]\n (let [k (fn [id] (comp/klass (get-in p [:boxes id :text])))\n ring-of (fn [id] (some (fn [[a _ b i]] (when (and (= b id) (= i 1) (= \"ring~\" (k a))) a)) (:lines p)))]\n (vec (for [[f _] (:boxes p) :when (= \"faust~\" (k f))\n :let [ins (filter (fn [[_ _ b _]] (= b f)) (:lines p))\n rs (vec (distinct (map first ins)))\n ring (when (seq rs) (ring-of (first rs)))\n ws (vec (distinct (keep (fn [[a _ b i]] (when (and (= a f) (= i 0) (= \"writer~\" (k b)) (= ring (ring-of b))) b)) (:lines p))))]\n :when (and ring (seq ws) (every? (fn [r] (and (= \"reader~\" (k r)) (= ring (ring-of r)))) rs))]\n {:faust f :ring ring :readers rs :writers ws}))))\n\n(defn- bytes-of [source]\n (let [r (code/compiled \"faust\" source)]\n (when (and (= :ok (:status r)) (not (:poly (:info r))) (:value r))\n (let [f (.-factory (:value r))] (when (and f (.-code f)) [f (:info r)])))))\n\n(defn fold-pass!\n \"Folds the loops of p into their rings, and unfolds what no longer is one (called every tick by the engine).\"\n [p nodes sig]\n (let [want (into {} (for [{:keys [faust ring readers writers]} (loops p) w writers] [w [faust ring readers]]))]\n ;; unfolded: a writer~ that was folded and no longer is\n (doseq [[id node] nodes :let [fa (:folded node)] :when (and fa @fa (not (contains? want id)))]\n (when-let [[_ s] @(:slot node)] (post! @(:ring node) {:unfold s}))\n (when-let [m (:mirrors (get nodes (:faust @fa)))] (swap! m dissoc id))\n (reset! fa nil))\n ;; folded: when every head has its slot and the faust~ is compiled\n (doseq [[w [faust ring readers]] want\n :let [wn (get nodes w) fnode (get nodes faust) rnode (get nodes ring)\n h (:ring rnode) ws @(:slot wn)\n rslots (mapv (fn [r] (second @(:slot (get nodes r)))) readers)\n src (get-in p [:boxes faust :data :source])\n [fac info] (bytes-of src)]\n :when (and wn fnode h ws (= h @(:ring wn)) (every? some? rslots) fac)\n :let [key [h (second ws) rslots src sig]]\n :when (not= key (:key @(:folded wn)))]\n (post! h {:fold {:slot (second ws) :readers rslots :code (.slice (.-code fac)) :json (.-json fac)}})\n ;; its parameters as they are, and from now on as they change\n (doseq [prm (:params info) :let [v (get @(:values fnode) (:label prm))] :when (number? v)]\n (post! h {:param {:slot (second ws) :address (:address prm) :value v}}))\n (swap! (:mirrors fnode) assoc w (fn [address v] (post! h {:param {:slot (second ws) :address address :value v}})))\n ;; what the faust~'s own node would bring into the writer~, a block late, is taken away\n (let [vin (ffirst (:inlets wn))]\n (doseq [[n _] (:outlets fnode)] (try (.disconnect n vin) (catch :default _ nil))))\n (reset! (:folded wn) {:key key :faust faust}))))\n\n(reset! comp/after-feed fold-pass!)\n","kairotic/score.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · score\n;; A musical voice in time as EDN data, projected to notation (MEI, drawn with Verovio), with a\n;; time ⇄ space relation built from the drawn notation, in the style of INScore.\n;; Voice data: {:tempo beats-per-minute :meter [4 4] :events {:e1 {:t beat :pitch midi :dur beats :txt \"…\"}}}\n;; (a canvas gives one with kairotic.canvas/->voice). Also: pitch names and a melody parser for the REPL.\n\n(ns kairotic.score\n (:require [clojure.string :as str]))\n\n(defn num? [x] (and (number? x) (not (js/isNaN x))))\n\n(defn sorted-events [s] (sort-by (fn [[_ e]] [(:t e) (- (:pitch e))]) (:events s)))\n\n;; ───────── pitches ─────────\n\n(def pcs {\"c\" 0 \"d\" 2 \"e\" 4 \"f\" 5 \"g\" 7 \"a\" 9 \"b\" 11})\n(def sharp-names [\"c\" \"c\" \"d\" \"d\" \"e\" \"f\" \"f\" \"g\" \"g\" \"a\" \"a\" \"b\"])\n(def sharp-acc [nil \"s\" nil \"s\" nil nil \"s\" nil \"s\" nil \"s\" nil])\n\n(defn pitch\n \"60, \\\"c4\\\", \\\"f#3\\\", \\\"bb2\\\", \\\"f##3\\\", \\\"fx3\\\", \\\"ebb2\\\", \\\"cn4\\\" → MIDI number (c4 = 60).\"\n [x]\n (cond (num? x) x\n (keyword? x) (pitch (name x))\n (symbol? x) (pitch (str x))\n (string? x) (let [m (re-matches #\"(?i)([a-g])(##|#|x|s|bb|b|n)?(-?\\d)\" (str/trim x))]\n (when m\n (+ (* 12 (inc (js/parseInt (nth m 3) 10)))\n (get pcs (str/lower-case (nth m 1)))\n (case (some-> (nth m 2) str/lower-case) (\"##\" \"x\") 2 (\"#\" \"s\") 1 \"bb\" -2 \"b\" -1 0))))\n :else nil))\n\n(defn parse-melody\n \"\\\"c4/1 d4/.5 r/1 c4+e4+g4/2\\\" → [[t pitch dur] ...] starting at beat t0.\"\n [txt t0]\n (loop [toks (remove str/blank? (str/split (str/trim (str txt)) #\"\\s+\")) t t0 out []]\n (if (empty? toks)\n out\n (let [[p d] (str/split (first toks) #\"/\")\n dur (if d (js/parseFloat d) 1)\n dur (if (js/isNaN dur) 1 dur)]\n (if (= (str/lower-case p) \"r\")\n (recur (rest toks) (+ t dur) out)\n (let [ps (map pitch (str/split p #\"\\+\"))]\n (when (some nil? ps) (throw (js/Error. (str \"I don't understand the note «\" p \"». Use for example c4, f#3 or bb2.\"))))\n (recur (rest toks) (+ t dur) (into out (map (fn [a] [t a dur]) ps)))))))))\n\n;; ───────── projection to MEI (notation) ─────────\n;; A sixteenth-note grid; one voice per staff: notes that start together form a chord,\n;; a note is cut when the next one starts.\n;; Every element has its own id (n-<event>-<piece>) so that the notation can be related to the model.\n\n(def unit 0.25)\n(defn slots [x] (js/Math.round (/ x unit)))\n(def lens [[16 \"1\" 0] [12 \"2\" 1] [8 \"2\" 0] [6 \"4\" 1] [4 \"4\" 0] [3 \"8\" 1] [2 \"8\" 0] [1 \"16\" 0]])\n(defn bar-slots [s] (let [[n d] (:meter s)] (* n (/ 4 d) 4)))\n\n(defn segments [notes total]\n (let [groups (vec (sort-by key (group-by :s notes)))\n starts (mapv key groups)]\n (loop [i 0 cur 0 out []]\n (if (>= i (count groups))\n (if (< cur total) (conj out {:s cur :e total :notes nil}) out)\n (let [[s g] (nth groups i)\n nxt (get starts (inc i))\n e (min (apply min (map :e g)) (or nxt js/Infinity))\n e (max e (inc s))\n out (if (> s cur) (conj out {:s cur :e s :notes nil}) out)]\n (recur (inc i) (max cur e) (conj out {:s s :e e :notes (sort-by :pitch g)})))))))\n\n(defn pieces [s e bar]\n (loop [p s out []]\n (if (>= p e)\n out\n (let [room (- bar (mod p bar))\n remaining (- e p)\n [len du dots] (first (filter (fn [[l]] (<= l (min room remaining))) lens))]\n (recur (+ p len) (conj out {:p p :len len :dur du :dots dots}))))))\n\n(defn nid [pre id k] (str \"n-\" pre (name id) \"-\" k))\n\n(defn note-xml [pre n k durattr]\n (let [a (:pitch n) pc (mod a 12)]\n (str \"<note xml:id=\\\"\" (nid pre (:id n) k) \"\\\" pname=\\\"\" (nth sharp-names pc) \"\\\" oct=\\\"\" (dec (js/Math.floor (/ a 12))) \"\\\"\"\n (when-let [ac (nth sharp-acc pc)] (str \" accid=\\\"\" ac \"\\\"\"))\n durattr\n ;; a text under the note (e.g. the deviation in cents of an untempered pitch)\n (if (and (:txt n) (zero? k))\n (str \"><verse n=\\\"1\\\"><syl>\" (-> (str (:txt n)) (str/replace \"&\" \"&\") (str/replace \"<\" \"<\")) \"</syl></verse></note>\")\n \"/>\"))))\n\n(defn ->mei*\n \"MEI of the voice. `staves` = [[n filter clef-shape clef-line] ...]; `pre` prefixes the ids\n (so that several scores can live on one page). Returns {:mei text :pieces [{:id :t :ev :staff}]}.\"\n [s staves pre]\n (let [bar (bar-slots s)\n notes (for [[id e] (sorted-events s)]\n (let [a (slots (:t e))]\n {:id id :s a :e (max (inc a) (slots (+ (:t e) (:dur e)))) :pitch (:pitch e) :txt (:txt e)}))\n nbars (max 2 (js/Math.ceil (/ (reduce max 0 (map :e notes)) bar)))\n total (* nbars bar)\n measures (atom (vec (repeat nbars {:ties []})))\n placed (atom [])]\n (doseq [[st keep? _ _] staves]\n (doseq [[si seg] (map-indexed vector (segments (filter keep? notes) total))]\n (let [pz (pieces (:s seg) (:e seg) bar)]\n (doseq [[k pc] (map-indexed vector pz)]\n (let [m (quot (:p pc) bar)\n durattr (str \" dur=\\\"\" (:dur pc) \"\\\"\" (when (pos? (:dots pc)) \" dots=\\\"1\\\"\"))\n t (* (:p pc) unit)\n ns-seg (:notes seg)\n xml (if (seq ns-seg)\n (do\n (doseq [n ns-seg]\n (swap! placed conj {:id (nid pre (:id n) k) :t t :ev (:id n) :staff st}))\n (when (< (inc k) (count pz))\n (swap! measures update-in [m :ties] into\n (for [n ns-seg]\n (str \"<tie startid=\\\"#\" (nid pre (:id n) k) \"\\\" endid=\\\"#\" (nid pre (:id n) (inc k)) \"\\\"/>\"))))\n (if (= 1 (count ns-seg))\n (note-xml pre (first ns-seg) k durattr)\n (str \"<chord xml:id=\\\"c-\" pre st \"-\" si \"-\" k \"\\\"\" durattr \">\"\n (apply str (map (fn [n] (note-xml pre n k \"\")) ns-seg))\n \"</chord>\")))\n (let [rid (str \"r-\" pre st \"-\" si \"-\" k)]\n (swap! placed conj {:id rid :t t :ev nil :staff st})\n (str \"<rest xml:id=\\\"\" rid \"\\\"\" durattr \"/>\")))]\n (swap! measures update-in [m st] (fnil conj []) xml))))))\n {:mei (str \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\"\n \"<mei xmlns=\\\"http://www.music-encoding.org/ns/mei\\\" meiversion=\\\"5.0\\\">\"\n \"<meiHead><fileDesc><titleStmt><title>Kairotic</title></titleStmt><pubStmt/></fileDesc></meiHead>\"\n \"<music><body><mdiv><score>\"\n \"<scoreDef meter.count=\\\"\" (first (:meter s)) \"\\\" meter.unit=\\\"\" (second (:meter s)) \"\\\" key.sig=\\\"0\\\">\"\n \"<staffGrp\" (when (> (count staves) 1) \" symbol=\\\"brace\\\" bar.thru=\\\"true\\\"\") \">\"\n (apply str (for [[st _ shape line] staves]\n (str \"<staffDef n=\\\"\" st \"\\\" lines=\\\"5\\\" clef.shape=\\\"\" shape \"\\\" clef.line=\\\"\" line \"\\\"/>\")))\n \"</staffGrp></scoreDef><section>\"\n (apply str (map-indexed (fn [i m]\n (str \"<measure n=\\\"\" (inc i) \"\\\">\"\n (apply str (for [[st] staves]\n (str \"<staff n=\\\"\" st \"\\\"><layer n=\\\"1\\\">\" (apply str (get m st)) \"</layer></staff>\")))\n (apply str (:ties m))\n \"</measure>\"))\n @measures))\n \"</section></score></mdiv></body></music></mei>\")\n :pieces (vec (sort-by :t @placed))}))\n\n(defn ->mei\n \"Grand staff (treble and bass, split at middle C).\"\n [s]\n (->mei* s [[1 (fn [n] (>= (:pitch n) 60)) \"G\" 2] [2 (fn [n] (< (:pitch n) 60)) \"F\" 4]] \"\"))\n\n(defn ->mei-voice\n \"A single voice on one staff, with treble or bass clef according to its mean register.\"\n [s pre]\n (let [as (map :pitch (vals (:events s)))\n low? (and (seq as) (< (/ (reduce + as) (count as)) 57))]\n (->mei* s [[1 (constantly true) (if low? \"F\" \"G\") (if low? 4 2)]] pre)))\n\n;; ───────── notation: time ⇄ space relation from the drawn notation ─────────\n;; After drawing, each piece (note or rest) with its beat is located on the page: those\n;; anchors {:t :x :y0 :y1 :right} (built by the page) map time to position (cursor).\n\n(defn t->pos [as t]\n (when (seq as)\n (let [a (last (filter (fn [x] (<= (:t x) t)) as))\n b (first (filter (fn [x] (> (:t x) t)) as))]\n (cond\n (nil? a) (first as)\n (nil? b) a\n :else\n (let [f (/ (- t (:t a)) (- (:t b) (:t a)))]\n (if (< (js/Math.abs (- (:y0 a) (:y0 b))) 2)\n (assoc a :x (+ (:x a) (* f (- (:x b) (:x a)))))\n (assoc a :x (+ (:x a) (* f (- (- (:right a) 8) (:x a)))))))))))\n","kairotic/shapes.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · shapes\n;; A component's own view is described with data, not HTML: a list of shapes in box\n;; coordinates (0,0 top left). This way a class written by anyone can be drawn in the patch\n;; without being able to inject markup into the page, and it follows its light or dark theme.\n;;\n;; [:rect {:x :y :w :h :r}]\n;; [:circle {:cx :cy :r}]\n;; [:line {:x1 :y1 :x2 :y2}]\n;; [:arc {:cx :cy :r :from :to}] degrees: 0 up, clockwise\n;; [:needle {:cx :cy :r :angle :r0}] a radial line from radius r0 (default 0) to r at `angle` degrees\n;; [:path {:points [[x y] …] :closed true}] a polyline (a waveform, an envelope…)\n;; [:text {:x :y :anchor :start|:middle|:end :size 11} \"text\"]\n;; [:curve {:points [[x y] …]}] a smooth path through the points (Catmull–Rom)\n;; [:group {:x :y :rotate :scale} [shape …]] shapes moved (x y), turned (degrees, clockwise) and scaled\n;; together; groups can hold groups (4 deep)\n;;\n;; All accept :stroke and :fill with a palette colour, :weight in pixels and :opacity (0…1).\n;; Any shape can also carry :hit k (a keyword or a number): pressing it, the component learns k (in the\n;; m of its :gesture, as :hit), so a view can have parts to click: the nodes of a graph, the keys of\n;; a scale. The last shape with :hit under the press wins (the one drawn on top).\n;; Palette: :ink :soft :accent :kairos :bg :grid (nil = no stroke or no fill).\n;; nils in the list are ignored, so you can write (when cond [:text …]).\n;;\n;; Templates: a component's :view is a list of shapes where any value can be a hole, a keyword\n;; that starts with $ (:$angle, :$label). `fill` replaces each hole with the value of the same\n;; key (without the $) in a map: the one its :derive returns, merged over the declared args and\n;; the box context (:shown :w :h). A hole with no value becomes nil.\n\n(ns kairotic.shapes\n (:require [clojure.string :as str]\n [clojure.walk :as walk]))\n\n(def palette #{:ink :soft :accent :kairos :bg :grid})\n(def max-shapes 600) ; shapes per box\n\n(defn esc [s]\n (-> (str s) (str/replace \"&\" \"&\") (str/replace \"<\" \"<\") (str/replace \">\" \">\") (str/replace \"\\\"\" \""\")))\n\n(defn n\n \"A safe number for an SVG attribute (with two decimals).\"\n [x]\n (if (and (number? x) (js/isFinite x)) (/ (js/Math.round (* x 100)) 100) 0))\n\n(defn classes [o stroke fill]\n (let [s (if (contains? o :stroke) (:stroke o) stroke)\n f (if (contains? o :fill) (:fill o) fill)]\n (str \" class=\\\"shape\" (when (palette s) (str \" s-\" (name s))) (when (palette f) (str \" f-\" (name f))) \"\\\"\"\n (when (number? (:weight o)) (str \" stroke-width=\\\"\" (n (max 0 (min 24 (:weight o)))) \"\\\"\"))\n (when (number? (:opacity o)) (str \" opacity=\\\"\" (n (max 0 (min 1 (:opacity o)))) \"\\\"\")))))\n\n(defn polar\n \"Point at distance r from the centre, with the angle in degrees (0 up, clockwise).\"\n [cx cy r a]\n (let [t (* a (/ js/Math.PI 180))]\n [(+ cx (* r (js/Math.sin t))) (- cy (* r (js/Math.cos t)))]))\n\n(defn arc-d [cx cy r from to]\n (let [span (- to from)]\n (when (> (js/Math.abs span) 0.01)\n (if (>= (js/Math.abs span) 359.99)\n (str \"M\" (n (- cx r)) \" \" (n cy) \"a\" (n r) \" \" (n r) \" 0 1 0 \" (n (* 2 r)) \" 0a\" (n r) \" \" (n r) \" 0 1 0 \" (n (* -2 r)) \" 0\")\n (let [[x1 y1] (polar cx cy r from) [x2 y2] (polar cx cy r to)]\n (str \"M\" (n x1) \" \" (n y1) \"A\" (n r) \" \" (n r) \" 0 \" (if (> (js/Math.abs span) 180) 1 0) \" \" (if (pos? span) 1 0)\n \" \" (n x2) \" \" (n y2)))))))\n\n(defn curve-d\n \"The SVG path of a smooth curve through the points (Catmull–Rom as cubic Béziers).\"\n [ps]\n (let [ps (vec ps) c (count ps) P (fn [i] (nth ps (max 0 (min (dec c) i))))]\n (when (>= c 2)\n (str \"M\" (n (first (P 0))) \" \" (n (second (P 0)))\n (apply str (for [i (range (dec c))]\n (let [[x0 y0] (P (dec i)) [x1 y1] (P i) [x2 y2] (P (inc i)) [x3 y3] (P (+ i 2))]\n (str \" C\" (n (+ x1 (/ (- x2 x0) 6))) \" \" (n (+ y1 (/ (- y2 y0) 6)))\n \" \" (n (- x2 (/ (- x3 x1) 6))) \" \" (n (- y2 (/ (- y3 y1) 6)))\n \" \" (n x2) \" \" (n y2)))))))))\n\n(defn points-of [o] (filter (fn [p] (and (sequential? p) (= 2 (count p)))) (take 2000 (:points o))))\n\n(declare shapes-str)\n\n(defn shape\n ([f] (shape f 0))\n ([f depth]\n (if-not (and (vector? f) (keyword? (first f)))\n \"\"\n (let [[kind o text] f o (if (map? o) o {})]\n (case kind\n :curve (if-let [d (curve-d (points-of o))] (str \"<path d=\\\"\" d \"\\\"\" (classes o :ink nil) \"></path>\") \"\")\n :group (if (or (> depth 3) (not (sequential? text)))\n \"\"\n (str \"<g transform=\\\"translate(\" (n (:x o 0)) \",\" (n (:y o 0)) \") rotate(\" (n (:rotate o 0)) \") scale(\"\n (n (let [k (:scale o 1)] (if (and (number? k) (pos? k)) (min 20 k) 1))) \")\\\"\"\n (when (number? (:opacity o)) (str \" opacity=\\\"\" (n (max 0 (min 1 (:opacity o)))) \"\\\"\")) \">\"\n (shapes-str text (inc depth)) \"</g>\"))\n :rect (str \"<rect x=\\\"\" (n (:x o)) \"\\\" y=\\\"\" (n (:y o)) \"\\\" width=\\\"\" (n (max 0 (:w o 0))) \"\\\" height=\\\"\" (n (max 0 (:h o 0)))\n \"\\\" rx=\\\"\" (n (:r o 0)) \"\\\"\" (classes o :ink nil) \"></rect>\")\n :circle (str \"<circle cx=\\\"\" (n (:cx o)) \"\\\" cy=\\\"\" (n (:cy o)) \"\\\" r=\\\"\" (n (max 0 (:r o 0))) \"\\\"\" (classes o :ink nil) \"></circle>\")\n :line (str \"<line x1=\\\"\" (n (:x1 o)) \"\\\" y1=\\\"\" (n (:y1 o)) \"\\\" x2=\\\"\" (n (:x2 o)) \"\\\" y2=\\\"\" (n (:y2 o)) \"\\\"\" (classes o :ink nil) \"></line>\")\n :arc (if-let [d (arc-d (n (:cx o)) (n (:cy o)) (n (:r o)) (n (:from o 0)) (n (:to o 360)))]\n (str \"<path d=\\\"\" d \"\\\"\" (classes o :ink nil) \"></path>\")\n \"\")\n :needle (let [cx (n (:cx o)) cy (n (:cy o)) a (n (:angle o 0))\n [x1 y1] (polar cx cy (n (:r0 o 0)) a)\n [x2 y2] (polar cx cy (n (:r o 0)) a)]\n (str \"<line x1=\\\"\" (n x1) \"\\\" y1=\\\"\" (n y1) \"\\\" x2=\\\"\" (n x2) \"\\\" y2=\\\"\" (n y2) \"\\\"\" (classes o :ink nil) \"></line>\"))\n :path (let [ps (filter (fn [p] (and (sequential? p) (= 2 (count p)))) (take 2000 (:points o)))]\n (if (< (count ps) 2)\n \"\"\n (str \"<\" (if (:closed o) \"polygon\" \"polyline\") \" points=\\\"\"\n (str/join \" \" (map (fn [[x y]] (str (n x) \",\" (n y))) ps)) \"\\\"\" (classes o :ink nil) \"></\"\n (if (:closed o) \"polygon\" \"polyline\") \">\")))\n :text (str \"<text x=\\\"\" (n (:x o)) \"\\\" y=\\\"\" (n (:y o)) \"\\\" text-anchor=\\\"\"\n (case (:anchor o) :middle \"middle\" :end \"end\" \"start\") \"\\\"\"\n \" font-size=\\\"\" (n (max 7 (min 28 (or (:size o) 11)))) \"\\\"\" (classes o nil :ink) \">\"\n (esc (let [s (str text)] (if (> (count s) 80) (subs s 0 80) s))) \"</text>\")\n \"\")))))\n\n(defn shapes-str [shapes depth]\n (if (sequential? shapes)\n (apply str (map (fn [f] (shape f depth)) (take max-shapes (remove nil? shapes))))\n \"\"))\n\n(defn svg\n \"The SVG (as text) of a list of shapes.\"\n [shapes]\n (shapes-str shapes 0))\n\n;; ───────── pressing a shape (:hit) ─────────\n;; Where a press lands is worked out from the shapes themselves (the view is drawn above the patch and\n;; does not take the pointer), in the coordinates of the box.\n\n(defn- num [x d] (if (and (number? x) (js/isFinite x)) x d))\n\n(defn- seg-dist [[px py] [ax ay] [bx by]]\n (let [dx (- bx ax) dy (- by ay) L2 (+ (* dx dx) (* dy dy))\n u (if (zero? L2) 0 (max 0 (min 1 (/ (+ (* (- px ax) dx) (* (- py ay) dy)) L2))))]\n (js/Math.hypot (- px (+ ax (* u dx))) (- py (+ ay (* u dy))))))\n\n(defn- inside-polygon? [[x y] ps]\n (let [ps (vec ps) c (count ps)]\n (loop [i 0 j (dec c) in false]\n (if (>= i c)\n in\n (let [[xi yi] (nth ps i) [xj yj] (nth ps j)\n cross (and (not= (> yi y) (> yj y))\n (< x (+ xi (/ (* (- xj xi) (- y yi)) (- yj yi)))))]\n (recur (inc i) i (if cross (not in) in)))))))\n\n(defn covers?\n \"Whether shape f (not a group) covers the point [x y] of its own coordinates (strokes within 4 px).\"\n [f [x y :as p]]\n (let [[kind o text] f o (if (map? o) o {})]\n (case kind\n :rect (and (<= (num (:x o) 0) x (+ (num (:x o) 0) (num (:w o) 0))) (<= (num (:y o) 0) y (+ (num (:y o) 0) (num (:h o) 0))))\n :circle (<= (js/Math.hypot (- x (num (:cx o) 0)) (- y (num (:cy o) 0))) (max 4 (num (:r o) 0)))\n :arc (let [d (js/Math.hypot (- x (num (:cx o) 0)) (- y (num (:cy o) 0)))] (< (js/Math.abs (- d (num (:r o) 0))) 5))\n :line (< (seg-dist p [(num (:x1 o) 0) (num (:y1 o) 0)] [(num (:x2 o) 0) (num (:y2 o) 0)]) 4)\n :needle (let [cx (num (:cx o) 0) cy (num (:cy o) 0) a (num (:angle o) 0)]\n (< (seg-dist p (polar cx cy (num (:r0 o) 0) a) (polar cx cy (num (:r o) 0) a)) 4))\n (:path :curve) (let [ps (vec (points-of o))]\n (or (and (:closed o) (> (count ps) 2) (inside-polygon? p ps))\n (some (fn [[a b]] (< (seg-dist p a b) 4)) (map vector ps (rest ps)))))\n :text (let [sz (max 7 (min 28 (num (:size o) 11))) w (* 0.62 sz (count (str text)))\n x0 (case (:anchor o) :middle (- (num (:x o) 0) (/ w 2)) :end (- (num (:x o) 0) w) (num (:x o) 0))]\n (and (<= x0 x (+ x0 w)) (<= (- (num (:y o) 0) sz) y (+ (num (:y o) 0) 3))))\n false)))\n\n(defn- into-group\n \"The point p of the outside, in the coordinates inside a group (its translate, rotate and scale undone).\"\n [o [x y]]\n (let [x (- x (num (:x o) 0)) y (- y (num (:y o) 0))\n t (* (- (num (:rotate o) 0)) (/ js/Math.PI 180))\n k (let [k (:scale o 1)] (if (and (number? k) (pos? k)) k 1))\n xr (- (* x (js/Math.cos t)) (* y (js/Math.sin t)))\n yr (+ (* x (js/Math.sin t)) (* y (js/Math.cos t)))]\n [(/ xr k) (/ yr k)]))\n\n(defn- group-covers?\n \"Whether any shape of a group (or of the groups inside it) covers the point.\"\n [kids p depth]\n (and (sequential? kids) (< depth 4)\n (some (fn [f]\n (when (and (vector? f) (keyword? (first f)))\n (let [[kind o ks] f o (if (map? o) o {})]\n (if (= kind :group) (group-covers? ks (into-group o p) (inc depth)) (covers? f p)))))\n (take max-shapes (remove nil? kids)))))\n\n(defn hit-at\n \"The :hit of the shape drawn on top at [x y] (box coordinates), or nil. A group with :hit is hit\n wherever one of its shapes is; a :hit inside it, more precise, wins.\"\n ([shapes p] (hit-at shapes p 0))\n ([shapes p depth]\n (when (sequential? shapes)\n (reduce (fn [found f]\n (if-not (and (vector? f) (keyword? (first f)))\n found\n (let [[kind o kids] f o (if (map? o) o {})\n inner (when (and (= kind :group) (< depth 4)) (hit-at kids (into-group o p) (inc depth)))\n own (when (and (some? (:hit o)) (not= kind :group) (covers? f p)) (:hit o))\n g (when (and (= kind :group) (some? (:hit o)) (group-covers? kids (into-group o p) depth)) (:hit o))]\n (or inner g own found))))\n nil (take max-shapes (remove nil? shapes))))))\n\n(defn dist-to\n \"How far the point [x y] is from shape f (not a group): 0 when it covers it.\"\n [f [x y :as p]]\n (if (covers? f p)\n 0\n (let [[kind o text] f o (if (map? o) o {})]\n (case kind\n :rect (let [x0 (num (:x o) 0) y0 (num (:y o) 0) x1 (+ x0 (num (:w o) 0)) y1 (+ y0 (num (:h o) 0))]\n (js/Math.hypot (max (- x0 x) 0 (- x x1)) (max (- y0 y) 0 (- y y1))))\n :circle (max 0 (- (js/Math.hypot (- x (num (:cx o) 0)) (- y (num (:cy o) 0))) (max 4 (num (:r o) 0))))\n :arc (js/Math.abs (- (js/Math.hypot (- x (num (:cx o) 0)) (- y (num (:cy o) 0))) (num (:r o) 0)))\n :line (seg-dist p [(num (:x1 o) 0) (num (:y1 o) 0)] [(num (:x2 o) 0) (num (:y2 o) 0)])\n :needle (let [cx (num (:cx o) 0) cy (num (:cy o) 0) a (num (:angle o) 0)]\n (seg-dist p (polar cx cy (num (:r0 o) 0) a) (polar cx cy (num (:r o) 0) a)))\n (:path :curve) (let [ps (vec (points-of o))]\n (if (< (count ps) 2) js/Infinity (apply min (map (fn [[a b]] (seg-dist p a b)) (map vector ps (rest ps))))))\n :text (let [sz (max 7 (min 28 (num (:size o) 11))) w (* 0.62 sz (count (str text)))\n x0 (case (:anchor o) :middle (- (num (:x o) 0) (/ w 2)) :end (- (num (:x o) 0) w) (num (:x o) 0))\n y0 (- (num (:y o) 0) sz) y1 (+ (num (:y o) 0) 3)]\n (js/Math.hypot (max (- x0 x) 0 (- x (+ x0 w))) (max (- y0 y) 0 (- y y1))))\n js/Infinity))))\n\n(defn- hit-dists\n \"[[hit distance] …] of every shape with :hit (a group with :hit: its nearest shape), in the outside\n coordinates (a scaled group scales its distances).\"\n [shapes p depth k]\n (when (and (sequential? shapes) (< depth 5))\n (mapcat (fn [f]\n (when (and (vector? f) (keyword? (first f)))\n (let [[kind o kids] f o (if (map? o) o {})]\n (if (= kind :group)\n (let [q (into-group o p)\n gk (* k (let [s (:scale o 1)] (if (and (number? s) (pos? s)) s 1)))\n inner (hit-dists kids q (inc depth) gk)]\n (concat inner\n (when (some? (:hit o))\n (let [ds (keep (fn [g] (when (and (vector? g) (keyword? (first g)) (not= :group (first g)))\n (* gk (dist-to g q))))\n (take max-shapes (remove nil? kids)))]\n (when (seq ds) [[(:hit o) (apply min ds)]])))))\n (when (some? (:hit o)) [[(:hit o) (* k (dist-to f p))]])))))\n (take max-shapes (remove nil? shapes)))))\n\n(defn hit-near\n \"Like hit-at, but forgiving: when no shape with :hit is under [x y], the nearest one within tol px\n (10 by default), so small parts (a node, a key, a point) are easy to press.\"\n ([shapes p] (hit-near shapes p 10))\n ([shapes p tol]\n (or (hit-at shapes p)\n (let [[h d] (first (sort-by second (hit-dists shapes p 0 1)))]\n (when (and (some? h) (<= d tol)) h)))))\n\n(defn only-hit\n \"The shapes that make the part k of a view (those with :hit k, inside their groups), to draw it again\n highlighted; a group with :hit k keeps all its shapes.\"\n [shapes k]\n (when (sequential? shapes)\n (vec (keep (fn [f]\n (when (and (vector? f) (keyword? (first f)))\n (let [[kind o kids] f o (if (map? o) o {})]\n (cond\n (= (:hit o) k) f\n (= kind :group) (let [ks (only-hit kids k)] (when (seq ks) [:group o ks]))\n :else nil))))\n (take max-shapes (remove nil? shapes))))))\n\n;; ───────── templates ─────────\n\n(defn hole\n \"The key a hole stands for (:$angle → :angle), or nil if x is not a hole.\"\n [x]\n (when (and (keyword? x) (nil? (namespace x)) (str/starts-with? (name x) \"$\") (> (count (name x)) 1))\n (keyword (subs (name x) 1))))\n\n(defn fill\n \"Replaces the holes of a shapes template with the values in `vals`.\"\n [template vals]\n (walk/postwalk (fn [x] (if-let [k (hole x)] (get vals k) x)) template))\n","kairotic/signal.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · signal\n;; Reading at audio rate. A reader reads a canvas once per message; reader~ reads it once per sample,\n;; driven by a signal position (usually a phasor~). The canvas is sampled into a table that is sent to\n;; an AudioWorklet whenever it changes, and the worklet interpolates the table while it plays.\n;;\n;; phasor~ [hz] a ramp signal from 0 to 1, hz times per second (a number changes hz)\n;; reader~ [x|y|path] [voices] [gate]\n;; position signal on the left (the buffer's units; 0…1 with norm),\n;; buffer on the right:\n;; · x (default): along X, one outlet per voice\n;; · y: along Y, the same\n;; · path [stroke]: along a stroke, two outlets x and y\n;; · gate: then one more outlet per voice (one for path): 1 where the\n;; voice has something, 0 where not (into an adsr~ of @kairotic/synth)\n;; sig~ [value] a constant signal; a number changes it\n;;\n;; With norm, the position 0…1 covers the X axis of a canvas, or a freqt from 0 to its last point (y: the Y axis,\n;; or the lowest … highest frequency). Where nothing passes a voice keeps its last value (so an\n;; oscillator it drives does not fall to 0 Hz); the gate says whether it sounds. Voices are given like\n;; a synth gives them: a stroke keeps its voice while it lasts, and a new one takes the first free voice.\n\n(ns kairotic.signal\n (:require [kairotic.components :as comp]\n [kairotic.canvas :as cv]\n [kairotic.api :as api]\n [kairotic.sounds :as snd]\n [kairotic.ringaudio :as ringa]))\n\n(def table-size 1024)\n\n(def worklet-source\n \"class KairoticReader extends AudioWorkletProcessor {\n // tab: V value channels of n points (NaN where nothing passes), sampled over span [lo, hi] (log: on a log\n // scale). The position is in the span's units, or 0…1 with norm (and always along a path). Outputs: the V\n // values, held where nothing passes, then G gates (gate g follows value channel g): 1 where it has something.\n constructor(o) {\n super();\n this.tab = null; this.n = 0; this.V = 0; this.G = 0; this.span = null; this.norm = true;\n this.last = [];\n this.port.onmessage = (e) => {\n const { tab, n, V, G, span, norm } = e.data;\n this.tab = tab; this.n = n; this.V = V; this.G = G; this.span = span || null; this.norm = norm !== false;\n for (let c = 0; c < V; c++) {\n if (this.last[c] === undefined || isNaN(this.last[c])) {\n let v = NaN; for (let i = 0; i < n; i++) { const x = tab[c * n + i]; if (!isNaN(x)) { v = x; break; } }\n this.last[c] = isNaN(v) ? 0 : v;\n }\n }\n };\n }\n process(inputs, outputs) {\n const inp = inputs[0] && inputs[0][0];\n const out = outputs[0];\n const C = out.length, L = out[0].length, n = this.n, tab = this.tab, V = this.V, G = this.G;\n for (let i = 0; i < L; i++) {\n if (!tab || n < 2) { for (let c = 0; c < C; c++) out[c][i] = 0; continue; }\n let p = inp ? inp[i] : 0;\n const sp = this.span;\n if (!this.norm && sp) {\n p = sp[2] && sp[0] > 0 && sp[1] > 0 ? (p > 0 ? Math.log(p / sp[0]) / Math.log(sp[1] / sp[0]) : 0)\n : (sp[1] !== sp[0] ? (p - sp[0]) / (sp[1] - sp[0]) : 0);\n }\n p = p < 0 ? 0 : (p > 1 ? 1 : p);\n const f = p * (n - 1), k = Math.min(Math.floor(f), n - 2), r = f - k;\n for (let c = 0; c < V && c < C; c++) {\n const a = tab[c * n + k], b = tab[c * n + k + 1];\n if (!isNaN(a)) this.last[c] = isNaN(b) ? a : a + (b - a) * r;\n out[c][i] = this.last[c];\n if (c < G && V + c < C) out[V + c][i] = isNaN(a) ? 0 : 1;\n }\n }\n return true;\n }\n}\nclass KairoticPhasor extends AudioWorkletProcessor {\n static get parameterDescriptors() { return [{ name: 'freq', defaultValue: 1 }]; }\n constructor() { super(); this.ph = 0; }\n process(inputs, outputs, params) {\n const o = outputs[0][0], f = params.freq;\n for (let i = 0; i < o.length; i++) {\n o[i] = this.ph;\n this.ph += (f.length > 1 ? f[i] : f[0]) / sampleRate;\n this.ph -= Math.floor(this.ph);\n }\n return true;\n }\n}\nregisterProcessor('kairotic-reader', KairoticReader);\nregisterProcessor('kairotic-phasor', KairoticPhasor);\n\")\n\n(defonce modules (atom {}))\n\n(defn ready\n \"Promise that resolves when the worklet module is loaded in this AudioContext.\"\n [ac]\n (or (get @modules ac)\n (let [url (js/URL.createObjectURL (js/Blob. #js [worklet-source] #js {:type \"application/javascript\"}))\n p (.addModule (.-audioWorklet ac) url)]\n (swap! modules assoc ac p)\n p)))\n\n;; ───────── tables ─────────\n\n(defn mode-of [args] (cond (some #{:path} args) :path (some #{:y} args) :y :else :x))\n\n(defn voices-of\n \"How many voices: the first number that is not the value of a word (d 1, speed 0.5, jump 1 are a head's on a\n ring~).\"\n [args]\n (let [free (keep-indexed (fn [i x] (when (and (number? x) (not (#{:d :speed :jump :mix} (get (vec args) (dec i))))) x)) args)]\n (if (= :path (mode-of args)) 2 (max 1 (min 16 (or (comp/num-of (first free)) 1))))))\n\n(defn gate? [args] (boolean (some #{:gate} args)))\n\n(defn gates-of [args] (if (gate? args) (if (= :path (mode-of args)) 1 (voices-of args)) 0))\n\n(defn stroke-of\n \"The stroke a reader~ path follows: its word that is not one of reader~'s own (nor of a head's on a ring~).\"\n [args]\n (first (remove #{:path :x :y :gate :norm :d :speed :jump :mix} (filter keyword? args))))\n\n(defn allocate\n \"Voices for a run of readings [[[id v] …] …]: a reading keeps the voice its id had at the step\n before, a new id takes the first free voice (none if all V are taken). [{voice v} …]\"\n [readings V]\n (first\n (reduce (fn [[acc held] rd]\n (let [ids (set (map first rd))\n kept (into {} (filter (fn [[vid _]] (ids vid)) held))\n held (reduce (fn [h [vid _]]\n (if (contains? h vid) h\n (if-let [free (first (remove (set (vals h)) (range V)))] (assoc h vid free) h)))\n kept rd)]\n [(conj acc (into {} (keep (fn [[vid v]] (when-let [c (held vid)] [c v])) rd))) held]))\n [[] {}] readings)))\n\n(defn readings\n \"What the canvas holds at each of n points of the span (as cv/read-along gives it, in stroke order), but\n each stroke is only asked where it can pass: between its lowest and highest coordinate on that axis.\n A canvas of short notes is crossed by one or two strokes at a time, not by all of them.\"\n [d mode span n]\n (let [k (if (= mode :y) 1 0)\n logs [(cv/x-log? d) (cv/y-log? d)]\n strokes (vec (for [[id s] (cv/sorted-strokes d) :let [cs (map (fn [p] (nth p k)) (:pts s))]]\n [id (:pts s) (apply min cs) (apply max cs)]))]\n (vec (for [i (range n)]\n (let [v (cv/at-unit span (/ i (dec n)))]\n (vec (mapcat (fn [[id pts lo hi]]\n (when (and (<= lo v) (<= v hi))\n (map-indexed (fn [j val] [(if (zero? j) id (keyword (str (name id) \"-\" (inc j)))) val])\n (cv/crossings pts k v logs))))\n strokes)))))))\n\n(defn compute-table\n \"The buffer d sampled for reader~: a Float32Array of voices × table-size (NaN where nothing passes).\"\n [d mode V sid]\n (let [n table-size tab (js/Float32Array. (* V n))]\n (.fill tab js/NaN)\n (case mode\n :path (when-let [pts (cv/stroke-for d sid)]\n (dotimes [i n]\n (when-let [[x y] (cv/point-along d pts (/ i (dec n)))]\n (aset tab i x)\n (aset tab (+ n i) y))))\n (let [span (if (= mode :y) (cv/y-range d) (cv/x-range d))]\n (doseq [[i vs] (map-indexed vector (allocate (readings d mode span n) V)) [c v] vs]\n (aset tab (+ (* c n) i) v))))\n tab))\n\n;; Several reader~ often read the same canvas the same way, and a canvas that has not changed must not\n;; be sampled again: the tables are kept by what they depend on (the buffer compared by value).\n(defonce tables (atom [])) ; [[key table] …], the newest last\n(def tables-kept 16)\n\n(defn table [d mode V sid]\n (let [k [d mode V sid]]\n (or (some (fn [[k2 t]] (when (= k k2) t)) @tables)\n (let [t (compute-table d mode V sid)]\n (swap! tables (fn [ts] (vec (take-last tables-kept (conj ts [k t])))))\n t))))\n\n(defn send-table! [node]\n (when-let [w @(:worklet node)]\n (when-let [t @(:pending node)]\n (.postMessage (.-port w) #js {:tab t :n table-size :V (:V node) :G (:G node)\n :span (some-> @(:span node) clj->js) :norm (or (:norm node) (= :path (:mode node)))})\n (reset! (:pending node) nil))))\n\n;; ───────── a reader~ that reads a sound ─────────\n;; A sample box (kairotic.sounds) is a buffer too: then the reader~ plays it, the position 0…1 going from\n;; its start to its end, through a player worklet that takes the place of the table reader.\n\n(defn route!\n \"Puts the table reader (:table), the player (:sound) or a ring~ (:ring: the position goes to the slot of the\n ring this reader~ has, and what it reads comes back) between the position and the outlets.\"\n [node which]\n (let [w @(:worklet node) pl @(:player node) in (:in node)]\n (doseq [x [w pl (:m node)] :when x]\n (try (.disconnect in x) (catch :default _ nil)))\n (doseq [x [w pl] :when x]\n (try (.disconnect x) (catch :default _ nil)))\n (when (and (= :ring @(:route node)) (not= which :ring)) (ringa/hook! node nil nil))\n (if (= which :ring)\n (.connect in (:m node) 0 1)\n (when-let [x (if (= which :sound) pl w)]\n (.connect in x) (.connect x (:split node))))\n (reset! (:route node) which)))\n\n(defn play-sound!\n \"Gives a reader~ the sound described by d: from this browser's store (or fetched from its URL), into\n its player.\"\n [node d]\n (reset! (:route node) :sound)\n (-> (snd/sound-for d)\n (.then (fn [s]\n (when (and @(:alive node) (= d @(:fed node)))\n (if-not s\n (api/report! (:id node) {:error (str \"reader~: the sound of the sample is not in this browser\"\n \" (recorded elsewhere): (load-sound! :bN) brings a file into it\")} nil)\n (-> (or @(:player node) (snd/player (:ac node) (:V node) (:G node)))\n (js/Promise.resolve)\n (.then (fn [pl]\n (when @(:alive node)\n (reset! (:player node) pl)\n (snd/give! pl s (:norm node))\n (when (= :sound @(:route node)) (route! node :sound))))))))))\n (.catch (fn [e] (api/report! (:id node) {:error (str \"reader~: \" (or (.-message e) e))} nil)))))\n\n;; ───────── classes ─────────\n\n(comp/define! \"reader~\"\n {:doc \"Reads a buffer at audio rate, as reader does once per message: a position signal on the left, the buffer on the right. The position is in the buffer's own units — the X axis of a canvas (Y with `reader~ y`), the time of a freqt, the seconds of a sample or a ring~ — or, with `norm`, from 0 to 1 (a phasor~ straight in); along a stroke (`reader~ path`) it is always 0…1. On a canvas or freqt: one signal outlet per voice, or x and y with path; where nothing passes a voice keeps its last value; with `gate`, one more outlet per voice, 1 where it has something. A sample: it plays it. A ring~: it reads there, or, with nothing on its left, follows the ring's head d behind, then a speed (reader~ d 1 speed 0.5; msg :d, :speed, :jump, :gain).\"\n :usage \"reader~ [x|y|path [stroke]] [voices] [gate] [norm] [d s] [speed x] [jump s]\"\n :io (fn [b] [2 (+ (voices-of (:args b)) (gates-of (:args b)))]) :dynamic-io true\n :reads-buffer true\n :receive (fn [{:keys [inlet value]}]\n (cond\n (and (= inlet :audio) (:error value)) {:effects [[:print (:error value)]]}\n ;; on a ring~: msg :d 2, :speed 0.5, :jump 1, :gain 0.5\n (and (= inlet 0) (ringa/head-message value)) {:effects [[:head (ringa/head-message value)]]}\n :else {}))\n :audio {:create (fn [ac b _]\n (let [args (:args b) V (voices-of args) G (gates-of args) C (+ V G)\n in (.createGain ac)\n split (.createChannelSplitter ac C)\n node {:in in :split split :V V :G G :mode (mode-of args) :stroke (stroke-of args)\n :ac ac :id (:id b) :player (atom nil) :route (atom :table)\n :worklet (atom nil) :pending (atom nil) :fed (atom ::none) :alive (atom true)\n ;; the position: in the buffer's units (the canvas's axis, seconds…) or, with norm, 0…1\n :span (atom nil) :norm (boolean (some #{:norm} args))\n ;; as a head of a ring~: the position into channel 1 of its slot, what it reads into the outlets\n :m (.createChannelMerger ac 2) :out split :ring (atom nil) :slot (atom nil)\n :opts (atom (merge {:mode \"follow\"} (ringa/head-args args)))\n :inlets [[in 0]]\n :outlets (vec (for [c (range C)] [split c]))}]\n (-> (ready ac)\n (.then (fn [_]\n (when @(:alive node)\n (let [w (js/AudioWorkletNode. ac \"kairotic-reader\"\n #js {:numberOfInputs 1 :numberOfOutputs 1\n :outputChannelCount #js [C]\n :channelCount 1 :channelCountMode \"explicit\"})]\n (reset! (:worklet node) w)\n (when (= :table @(:route node)) (route! node :table))\n (send-table! node)))))\n (.catch (fn [e] (js/console.error \"reader~\" e))))\n node))\n :feed (fn [node d]\n (cond\n (ringa/handle? d) (do (route! node :ring) (ringa/hook! node d \"read\"))\n (snd/sample? d) (do (when (= :ring @(:route node)) (route! node :table)) (play-sound! node d))\n :else\n (do (when (#{:sound :ring} @(:route node)) (route! node :table))\n (reset! (:span node) (let [d (or d cv/empty)]\n (case (:mode node) :path nil :y (cv/y-range d) (cv/x-range d))))\n (reset! (:pending node) (table (or d cv/empty) (:mode node) (:V node) (:stroke node)))\n (send-table! node))))\n ;; on a ring~: a position signal on the left, it reads there; without one, it follows the ring's head\n :wired (fn [node ins] (ringa/set-head! node {:mode (if (contains? ins 0) \"pos\" \"follow\")}))\n :effects {:head (fn [node x _] (ringa/set-head! node x))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n (ringa/hook! node nil nil)\n (doseq [x [@(:worklet node) @(:player node)] :when x] (try (.disconnect x) (catch :default _ nil))))}})\n\n(comp/define! \"phasor~\"\n {:doc \"A ramp signal from 0 to 1, repeated hz times per second (0.25 = once every 4 seconds). A number on the left changes hz.\"\n :usage \"phasor~ [hz]\"\n :io [1 1]\n :receive (fn [{:keys [value]}] (if (comp/num-of value) {:effects [[:freq (comp/num-of value)]]} {}))\n :audio {:create (fn [ac b _]\n (let [out (.createGain ac)\n hz (atom (or (comp/num-of (first (:args b))) 1))\n node {:out out :hz hz :worklet (atom nil) :alive (atom true) :outlets [[out 0]]}]\n (-> (ready ac)\n (.then (fn [_]\n (when @(:alive node)\n (let [w (js/AudioWorkletNode. ac \"kairotic-phasor\" #js {:numberOfInputs 0 :numberOfOutputs 1\n :outputChannelCount #js [1]})]\n (set! (.-value (.get (.-parameters w) \"freq\")) @hz)\n (.connect w out)\n (reset! (:worklet node) w)))))\n (.catch (fn [e] (js/console.error \"phasor~\" e))))\n node))\n :effects {:freq (fn [node x at]\n (reset! (:hz node) x)\n (when-let [w @(:worklet node)] (.setValueAtTime (.get (.-parameters w) \"freq\") x at)))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n (when-let [w @(:worklet node)] (try (.disconnect w) (catch :default _ nil))))}})\n\n(comp/define! \"sig~\"\n {:doc \"A constant signal (a frequency for osc~, a factor for gain~, a position for reader~). A number on the left changes it.\"\n :usage \"sig~ [value]\"\n :io [1 1]\n :receive (fn [{:keys [value]}] (if (comp/num-of value) {:effects [[:value (comp/num-of value)]] :show (comp/num-of value)} {}))\n :audio {:create (fn [ac b _]\n (let [c (.createConstantSource ac)]\n (set! (.. c -offset -value) (or (comp/num-of (first (:args b))) 0))\n (.start c)\n {:c c :outlets [[c 0]]}))\n :effects {:value (fn [node x at] (.setValueAtTime (.-offset (:c node)) x at))}\n :dispose (fn [node] (try (.stop (:c node)) (catch :default _ nil)))}})\n\n;; adsr~ moved to the package @kairotic/synth (Study 14)\n","kairotic/sounds.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · sounds\n;; Recorded and loaded sound. Its samples are too big for the history of a work: they are kept in this\n;; browser (IndexedDB) under the hash of the samples, and the history keeps only a description,\n;; {:audio \"5a2c…\" :sr 48000 :frames 96000 :channels 1 :peaks [[-0.4 0.38] …]}\n;; whose peaks are enough to draw it anywhere. A work opened in another browser shows the sound and\n;; says it is not there; (load-sound! :bN) brings a file in. A sound can also come from a URL,\n;; {:url \"https://…/voice.ogg\" …} or only {:url \"…\"}\n;; and then every browser that opens the work fetches it by itself (once: then it is kept like the rest,\n;; under a key made from the URL), which is how a shared session or a test has the same sounds\n;; everywhere. Two sources need no CORS of their own:\n;; github:owner/repo[@ref]/path.wav a file of a public GitHub repository, served by jsDelivr\n;; freesound:12345 a sound of Freesound (its preview), with the API key of whoever\n;; opens the work, kept only in their browser: (freesound-key! \"…\")\n;; A Freesound sound brings its credit ({:name :author :license :page}), kept beside the description.\n;; The loops over samples are JavaScript (kairotic/sounds.mjs).\n;;\n;; sample [seconds] a buffer of sound: what reaches its left inlet is recorded on `rec` until `stop`\n;; (or until it has `seconds`, 60 by default). Its right outlet is the buffer for a\n;; reader~, which plays it at the position on its left (seconds; 0…1 with norm: a phasor~); a bang sends its length in\n;; seconds on the left, and so does every new recording.\n\n(ns kairotic.sounds\n (:require [clojure.string :as str]\n [kairotic.components :as comp]\n [kairotic.api :as api]\n [kairotic.engine :as eng]))\n\n;; ───────── the store ─────────\n\n(defonce lib* (atom nil))\n(defn lib\n \"Promise of the native part (kairotic/sounds.mjs), loaded the first time a sound is needed.\"\n []\n (or @lib* (reset! lib* ((.-kairoticImport js/window) \"kairotic/sounds.mjs\"))))\n\n(defonce cache (atom {})) ; key → {:sr n :chans #js [Float32Array …]}\n(defonce status (atom {})) ; key → :here | :missing | :checking | :loading | :failed\n(defonce local (atom {})) ; key → {:sr :frames :channels :peaks} of a sound this browser has\n(defonce failures (atom {})) ; key → why its URL could not be loaded\n\n(def peak-columns 120)\n\n;; ───────── sources: where a URL of a sound points ─────────\n\n(defn github-spec\n \"github:owner/repo[@ref]/path → {:owner :repo :ref :path}, or nil. ref is a tag, a commit or a branch\n without slashes (without it, jsDelivr serves the default branch, which can change: pin it).\"\n [u]\n (when-let [[_ owner repo ref path] (and (string? u)\n (re-matches #\"github:([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)(?:@([A-Za-z0-9_.-]+))?/(.+)\" u))]\n (when-not (re-find #\"\\.\\.\" path)\n {:owner owner :repo repo :ref ref :path path})))\n\n(defn github-url\n \"The jsDelivr URL of a github: sound (it serves public repositories with CORS open).\"\n [{:keys [owner repo ref path]}]\n (str \"https://cdn.jsdelivr.net/gh/\" owner \"/\" repo (when ref (str \"@\" ref)) \"/\"\n (str/join \"/\" (map js/encodeURIComponent (str/split path #\"/\")))))\n\n(defn freesound-id \"freesound:12345 → 12345, or nil.\" [u]\n (when-let [[_ n] (and (string? u) (re-matches #\"freesound:(\\d{1,10})\" u))] (js/parseInt n 10)))\n\n(defn url?\n \"A place a sound can be fetched from: an http(s) URL, a path of this page, a data: or blob: URL, a\n github:owner/repo/path or a freesound:id. Never javascript:, no spaces, at most 2048 characters.\"\n [u]\n (boolean\n (and (string? u) (<= 1 (count u) 2048) (not (re-find #\"\\s\" u))\n (not (re-find #\"(?i)^javascript:\" u))\n (or (re-find #\"(?i)^(https?|data|blob):\" u)\n (github-spec u)\n (freesound-id u)\n ;; a path of this page: no scheme, and a dot or a slash (sounds/voice.ogg, ./a.wav)\n (and (not (re-find #\"^[A-Za-z][A-Za-z0-9+.-]*:\" u)) (re-find #\"[./]\" u))))))\n\n;; Freesound: every person uses their own API key (freesound.org/apiv2/apply), kept in their browser and\n;; never in a work, a link or a room\n(def freesound-api \"https://freesound.org/apiv2/\")\n(def key-storage \"kairotic.freesound-key\")\n\n(defn freesound-key []\n (try (let [k (.getItem js/localStorage key-storage)] (when (seq k) k)) (catch :default _ nil)))\n\n(defn set-freesound-key! [k]\n (try (if (seq k) (.setItem js/localStorage key-storage k) (.removeItem js/localStorage key-storage)) (catch :default _ nil))\n (boolean (seq k)))\n\n(defn license-label\n \"A short name for a license URL: CC0, CC BY, CC BY-NC, Sampling+…\"\n [u]\n (let [u (str/lower-case (str u))]\n (cond (re-find #\"publicdomain/zero|cc0\" u) \"CC0\"\n (re-find #\"by-nc\" u) \"CC BY-NC\"\n (re-find #\"/by/|attribution\" u) \"CC BY\"\n (re-find #\"sampling\" u) \"Sampling+\"\n (seq u) \"see license\"\n :else \"\")))\n\n(defn freesound-get\n \"Promise of the JSON (as a map) of a Freesound API path, with the key of this browser.\"\n [path params]\n (if-let [k (freesound-key)]\n (-> (js/fetch (str freesound-api path \"?\"\n (str/join \"&\" (for [[a b] (assoc params :token k)] (str (name a) \"=\" (js/encodeURIComponent (str b)))))))\n (.then (fn [r] (if (.-ok r) (.json r) (throw (js/Error. (str \"Freesound answered \" (.-status r)\n (when (= 401 (.-status r)) \": the API key is not valid\")))))))\n (.then (fn [j] (js->clj j :keywordize-keys true))))\n (js/Promise.reject (js/Error. \"Freesound needs an API key, kept only in this browser: (freesound-key! \\\"…\\\") — get one at freesound.org/apiv2/apply\"))))\n\n(defn freesound-credit [j]\n {:name (str (:name j)) :author (str (:username j)) :license (license-label (:license j))\n :page (str (or (:url j) (str \"https://freesound.org/s/\" (:id j) \"/\")))})\n\n(defn github-hrefs\n \"Where to look for a github: sound, in order. Without @ref: @main, @master, then what jsDelivr serves\n without a version — the latest semver tag of the repository, not its default branch, which may not\n have the file.\"\n [spec]\n (if (:ref spec)\n [(github-url spec)]\n (mapv (fn [ref] (github-url (assoc spec :ref ref))) [\"main\" \"master\" nil])))\n\n(defn resolve-url\n \"Promise of {:hrefs [url-to-fetch …] :credit {…}?} for a URL of a sound: the hrefs are tried in order\n while they answer 404.\"\n [u]\n (cond\n (github-spec u) (js/Promise.resolve {:hrefs (github-hrefs (github-spec u))})\n (freesound-id u)\n (.then (freesound-get (str \"sounds/\" (freesound-id u) \"/\") {:fields \"id,name,username,license,url,previews\"})\n (fn [j]\n (let [pv (:previews j)\n href (or (get pv :preview-hq-mp3) (get pv :preview-hq-ogg) (get pv :preview-lq-mp3))]\n (when-not href (throw (js/Error. \"Freesound gave no preview for that sound\")))\n {:hrefs [href] :credit (freesound-credit j)})))\n :else (js/Promise.resolve {:hrefs [u]})))\n\n(defn fetch-first\n \"Promise of the bytes of the first of hrefs that answers; if one fails the next is tried (jsDelivr\n answers a file it does not have without the CORS header, so a missing file fails like a refused one).\n The error says why, in words: not found (and for github: where it looked), refused by the site (CORS)\n or unreachable.\"\n [u hrefs]\n (let [github? (github-spec u)\n not-found (fn [] (js/Error. (if github?\n (str \"not found: it is not in \"\n (if (:ref github?) (str \"@\" (:ref github?)) \"@main, @master or the latest tag\")\n \" of \" (:owner github?) \"/\" (:repo github?) \" — check the path, or add @branch or @commit\")\n \"not found (404)\")))]\n (letfn [(go [[href & more]]\n (-> (js/fetch href)\n (.then (fn [r]\n (if (.-ok r)\n (.arrayBuffer r)\n (throw (if (= 404 (.-status r)) (not-found) (js/Error. (str \"the site answered \" (.-status r))))))))\n (.catch (fn [e]\n (cond\n (seq more) (go more)\n ;; fetch itself fails (a TypeError) when the site refuses the page or cannot be reached\n (instance? js/TypeError e)\n (throw (if github? (not-found)\n (js/Error. \"the site does not let this page load it (CORS), or cannot be reached\")))\n :else (throw e))))))]\n (go hrefs))))\n\n(defn as-url\n \"A URL from what reaches a sample: a string, or a word as a msg box sends it (msg https://…: a name,\n or msg \\\"https://…\\\": a string; a keyword too). nil if it is not one.\"\n [v]\n (let [t (cond (string? v) v\n ;; the whole text of the keyword: name and namespace split it at its first slash\n (keyword? v) (subs (str v) 1)\n (symbol? v) (str v)\n :else nil)\n t (when t (str/trim t))\n t (if (and t (re-matches #\"\\\".*\\\"|'.*'\" t)) (subs t 1 (dec (count t))) t)]\n (when (url? t) t)))\n\n(defn url-key\n \"The key a sound from a URL is kept under: 16 hex characters from the URL (two FNV-1a hashes).\"\n [u]\n (let [h (fn [seed] (reduce (fn [h c] (unsigned-bit-shift-right (js/Math.imul (bit-xor h (.charCodeAt c 0)) 16777619) 0))\n seed (seq u)))\n hex (fn [x] (.padStart (.toString x 16) 8 \"0\"))]\n (str (hex (h 2166136261)) (hex (h 3735928559)))))\n\n(defn sample?\n \"A description of a sound (the data of a sample box), not an empty one.\"\n [d] (and (map? d) (string? (:audio d)) (or (pos? (or (:frames d) 0)) (url? (:url d)))))\n\n(defn about\n \"What is known of the sound of d: its description, completed with what this browser learnt when it\n loaded it (a description that is only a URL learns its length and peaks so).\"\n [d] (merge (get @local (:audio d)) (select-keys d [:sr :frames :channels :peaks :credit])))\n\n(defn seconds [d]\n (let [{:keys [frames sr]} (when (sample? d) (about d))]\n (if (and (number? frames) (number? sr) (pos? sr)) (/ frames sr) 0)))\n\n(defn sane\n \"The description of a sound as it may be kept in the history, or {} if it is not one. A URL alone is\n enough: its key is made from it.\"\n [d]\n (let [n (fn [x] (and (number? x) (js/isFinite x) (pos? x)))\n url (when (and (map? d) (url? (:url d))) (:url d))\n credit (when (map? (:credit d))\n (let [c (into {} (for [k [:name :author :license :page] :let [v (get-in d [:credit k])]\n :when (and (string? v) (seq v))]\n [k (subs v 0 (min 300 (count v)))]))]\n (when (seq c) c)))]\n (cond\n (and (map? d) (string? (:audio d)) (re-matches #\"[0-9a-f]{8,64}\" (:audio d)) (n (:sr d)) (n (:frames d)))\n (cond-> {:audio (:audio d) :sr (:sr d) :frames (js/Math.floor (:frames d))\n :channels (max 1 (min 32 (js/Math.floor (or (:channels d) 1))))\n :peaks (vec (for [p (take 2000 (:peaks d)) :when (and (sequential? p) (= 2 (count p)) (every? number? p))]\n (mapv (fn [x] (comp/clamp x -1 1)) p)))}\n url (assoc :url url)\n credit (assoc :credit credit))\n url (cond-> {:audio (url-key url) :url url} credit (assoc :credit credit))\n :else {})))\n\n(defn sound\n \"Promise of the sound kept under hash h ({:sr :chans}), or nil if this browser does not have it.\"\n [h]\n (if-let [s (get @cache h)]\n (js/Promise.resolve s)\n (-> (lib)\n (.then (fn [L] (.then (.get L h) (fn [r] [L r]))))\n (.then (fn [[L r]]\n (if r\n (let [chans (.-chans r)\n s {:sr (.-sr r) :chans chans}]\n (swap! cache assoc h s)\n ;; what it is (length, picture), as when it was stored: a sound kept in an earlier\n ;; session is described again, so a description that is only a URL learns it too\n (when-not (:peaks (get @local h))\n (swap! local update h merge\n {:sr (.-sr r) :frames (.-length (aget chans 0)) :channels (.-length chans)\n :peaks (js->clj (.peaks L chans peak-columns))}))\n (swap! status assoc h :here)\n s)\n (do (swap! status assoc h :missing) nil)))))))\n\n(defn store!\n \"Keeps a sound under key h in this browser (memory and IndexedDB). Promise of its description.\"\n [h sr chans]\n (.then (lib)\n (fn [L]\n (.then (.put L h sr chans)\n (fn [_]\n (let [d {:audio h :sr sr :frames (.-length (aget chans 0)) :channels (.-length chans)\n :peaks (js->clj (.peaks L chans peak-columns))}]\n (swap! cache assoc h {:sr sr :chans chans})\n (swap! local assoc h (dissoc d :audio))\n (swap! status assoc h :here)\n d))))))\n\n(defn keep!\n \"Keeps a sound (sample rate, a JS array of Float32Array, one per channel) in this browser, under the\n hash of its samples. Promise of its description, the data of a sample box.\"\n [sr chans]\n (.then (lib) (fn [L] (.then (.hash L chans sr) (fn [h] (store! h sr chans))))))\n\n(defn decode\n \"Promise of a sound ({:sr :chans}, up to 8 channels) from the bytes of a file, decoded at the sample\n rate of the engine.\"\n [buf]\n (.then (.decodeAudioData (eng/ctx) buf)\n (fn [ab] {:sr (.-sampleRate ab)\n :chans (into-array (for [c (range (min 8 (.-numberOfChannels ab)))]\n (js/Float32Array. (.getChannelData ab c))))})))\n\n(defonce fetching (atom {})) ; key → Promise\n\n(defn fetch!\n \"Promise of the sound at url, fetched, decoded and kept under key h (once, whoever asks first).\"\n [h url]\n (or (get @fetching h)\n (let [credit (atom nil)\n p (-> (resolve-url url)\n (.then (fn [{:keys [hrefs] c :credit}]\n (reset! credit c)\n (fetch-first url hrefs)))\n (.then (fn [buf] (.catch (decode buf)\n (fn [e] (throw (js/Error. (str \"it is not a sound this browser can decode (\" (or (.-message e) e) \")\")))))))\n (.then (fn [{:keys [sr chans]}] (store! h sr chans)))\n (.then (fn [_]\n (when-let [c @credit] (swap! local assoc-in [h :credit] c))\n (get @cache h)))\n (.catch (fn [e]\n (swap! status assoc h :failed)\n (swap! failures assoc h (str (or (.-message e) e)))\n (swap! fetching dissoc h)\n (throw (js/Error. (str \"could not load \" url \": \" (or (.-message e) e)))))))]\n (swap! status assoc h :loading)\n (swap! fetching assoc h p)\n p)))\n\n(defn sound-for\n \"Promise of the sound of a description ({:sr :chans}): from this browser, or fetched from its URL if\n it has one; nil if neither.\"\n [d]\n (let [h (:audio d)]\n (.then (sound h) (fn [s] (if (or s (not (url? (:url d)))) s (fetch! h (:url d)))))))\n\n(defn check!\n \"Finds out (once) whether this browser has the sound of d, fetching it if it comes from a URL:\n (get @status (:audio d)) then says it.\"\n [d]\n (let [h (:audio d)]\n (when (and (string? h) (nil? (get @status h)))\n (swap! status assoc h :checking)\n ;; why it could not be loaded is said once, in the REPL\n (.catch (sound-for d) (fn [e] (eng/print! (eng/now) (str \"sample: \" (or (.-message e) e))))))))\n\n;; ───────── playing: the worklet a reader~ uses for a sound ─────────\n\n(def player-source\n \"class KairoticPlayer extends AudioWorkletProcessor {\n // Plays a sound at the position of its input — seconds, or 0…1 from the start to the end with norm —,\n // interpolating between samples: output channel c plays channel c of the sound (or its last one); after V\n // value channels come G gate channels, 1 while it has a sound. A message {chans, sr, norm} gives it the sound.\n constructor(o) {\n super();\n const p = (o && o.processorOptions) || {};\n this.V = p.V || 1; this.G = p.G || 0; this.chans = null; this.sr = sampleRate; this.norm = true;\n this.port.onmessage = (e) => {\n const d = e.data;\n this.chans = d.chans && d.chans.length ? d.chans : null;\n if (d.sr) this.sr = d.sr;\n this.norm = d.norm !== false;\n };\n }\n process(inputs, outputs) {\n const inp = inputs[0] && inputs[0][0], out = outputs[0], ch = this.chans;\n const L = out[0].length, n = ch ? ch[0].length : 0;\n for (let i = 0; i < L; i++) {\n let p = inp ? inp[i] : 0;\n if (!this.norm && n > 1) p = p * this.sr / (n - 1);\n p = p < 0 ? 0 : (p > 1 ? 1 : p);\n const f = p * (n - 1), k = Math.floor(f), r = f - k;\n for (let c = 0; c < out.length; c++) {\n if (c < this.V) {\n if (n < 2) { out[c][i] = 0; continue; }\n const s = ch[Math.min(c, ch.length - 1)];\n out[c][i] = k + 1 < n ? s[k] + (s[k + 1] - s[k]) * r : s[n - 1];\n } else out[c][i] = n ? 1 : 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('kairotic-player', KairoticPlayer);\n\")\n\n(defn player\n \"Promise of a player worklet with V value channels and G gate channels (the outlets of a reader~).\"\n [ac V G]\n (api/worklet-node ac \"kairotic-player\" player-source\n {:numberOfInputs 1 :numberOfOutputs 1 :outputChannelCount [(+ V G)]\n :channelCount 1 :channelCountMode \"explicit\" :processorOptions {:V V :G G}}))\n\n(defn give!\n \"Gives a player the sound s ({:chans}), or none (nil).\"\n ([pl s] (give! pl s true))\n ([pl s norm]\n (.postMessage (.-port pl) #js {:chans (if s (:chans s) #js []) :sr (when s (:sr s)) :norm (boolean norm)})))\n\n;; ───────── the sample box ─────────\n\n(def block 4096)\n\n(defn sample-seconds [x] (comp/clamp (or (comp/num-of x) 60) 0.1 600))\n\n(defn splice\n \"The channels of an old sound (a JS array of Float32Array, or nil) until frame n0 — silence where it is\n shorter —, then the new samples s, in every channel; with after, what the old sound had after the new\n samples end follows them (punch-in/out).\"\n ([old n0 s] (splice old n0 s false))\n ([old n0 s after]\n (let [C (if old (max 1 (.-length old)) 1)\n n1 (+ n0 (.-length s))\n len (if (and after old) (max n1 (.-length (aget old 0))) n1)]\n (into-array\n (for [c (range C)]\n (let [out (js/Float32Array. len)\n o (when old (aget old c))]\n (when o (.set out (.subarray o 0 (min n0 (.-length o)))))\n (.set out s n0)\n (when (and after o (> (.-length o) n1)) (.set out (.subarray o n1) n1))\n out))))))\n\n(defonce takes (atom [])) ; what the last takes did, step by step (for debugging and tests)\n(defn step! [x] (swap! takes (fn [t] (vec (take-last 30 (conj t x))))))\n\n(defn finish!\n \"The end of a recording: its blocks become one sound, kept in this browser and written as the data\n of the box (through the page, an event of the history); the box hears it on inlet :audio.\"\n [node id]\n (when-let [{:keys [blocks sr max from base ovr]} @(:rec node)]\n (reset! (:rec node) nil)\n (step! [:finish id (count blocks) from])\n (-> (lib)\n (.then (fn [L]\n (let [s (.concat L (clj->js blocks) max)]\n (step! [:joined id (.-length s)])\n (cond\n (zero? (.-length s)) (js/Promise.reject (js/Error. \"nothing was recorded\"))\n ;; rec t: the sound it had until t, then the take (punch-in)\n (some? from)\n (.then (if (sample? base) (sound-for base) (js/Promise.resolve nil))\n (fn [old]\n (step! [:old id (some? old) (:sr old)])\n (cond\n (and (sample? base) (nil? old))\n (throw (js/Error. \"the sound to record over is not in this browser\"))\n (and old (not= (:sr old) sr))\n (throw (js/Error. (str \"the sound to record over is at \" (:sr old) \" Hz, the engine at \" sr \" Hz\")))\n :else (keep! sr (splice (:chans old) (js/Math.floor (* from sr)) s ovr)))))\n :else (keep! sr #js [s])))))\n (.then (fn [d]\n (step! [:kept id (:frames d)])\n (api/effect! id [:sample [:set d]])\n (api/report! id {:done d} nil)))\n (.catch (fn [e]\n (step! [:failed id (str (or (.-message e) e))])\n (js/console.warn \"sample:\" e)\n (api/report! id {:error (str \"sample: \" (or (.-message e) e))} nil))))))\n\n(defn start!\n \"rec: a new take (unless one is going on); the box hears that it started. With {:from t :base d} the\n take goes after the first t seconds of the sound d (punch-in).\"\n [node at opts]\n (when-not @(:rec node)\n (let [sr (.-sampleRate (:ac node))]\n (reset! (:rec node) (merge {:blocks [] :n 0 :sr sr :max (js/Math.floor (* sr @(:seconds node)))}\n (when (map? opts) (select-keys opts [:from :base :ovr]))))\n (when-let [w @(:tap node)] (api/retap w {:active true}))\n (api/report! (:id node) {:started true} at))))\n\n(defn stop!\n \"stop: what was heard until now (the worklet hands its last samples at once) becomes the take.\"\n [node]\n (step! [:stop (:id node) (some? @(:rec node)) (some? @(:tap node))])\n (when @(:rec node)\n (if-let [w @(:tap node)]\n (api/retap w {:flush true :active false})\n (finish! node (:id node)))))\n\n(defn on-block!\n \"A block heard while recording: kept; at the end (stop, or the length of the box) the take is finished.\"\n [node data {:keys [last]}]\n (when-let [r @(:rec node)]\n (let [b (first data)\n r (swap! (:rec node) (fn [r] (-> r (update :blocks conj b) (update :n + (.-length b)))))\n full (>= (:n r) (:max r))]\n (when full (when-let [w @(:tap node)] (api/retap w {:active false})))\n (if (or last full)\n (finish! node (:id node))\n (api/report! (:id node) {:progress (+ (or (:from r) 0) (/ (:n r) (:sr r))) :level (when-let [L @(:L node)] (.peak L b))} nil)))))\n\n(defn wave-points\n \"The waveform of a description: its peaks as a zigzag from x0 to x1 around the line at y mid.\"\n [peaks x0 x1 mid half]\n (let [k (count peaks)]\n (vec (for [i (range k) :let [[lo hi] (nth peaks i)\n x (+ x0 (* (- x1 x0) (/ i (max 1 (dec k)))))]\n y [(- mid (* hi half)) (- mid (* lo half))]]\n [x y]))))\n\n(defn fmt-s [s] (str (comp/nice s) \" s\"))\n\n(comp/define! \"sample\"\n {:doc \"A buffer of sound. What reaches its left inlet is recorded on `:rec` until `:stop` (or until it has seconds, 60 by default), replacing what it had; :rec t (msg :rec 2.5) keeps its first t seconds and records from there (punch-in); :ovr t (msg :ovr 2.5) replaces only what the take covers and keeps what comes after (punch-in/out); `:clear` empties it. Its right outlet is the buffer for a reader~, which plays it at the position on its left, in seconds (or with reader~ norm from 0 to 1: a phasor~); a bang sends its length in seconds on the left, and so does every new recording. The sound stays in this browser; the work keeps its picture. A URL (a string on the left, or (load-sound! :bN \\\"https://…\\\")) loads a sound that every browser opening the work fetches by itself. (load-sound! :bN) brings in a file, (save-sound :bN) saves it as WAV.\"\n :usage \"sample [seconds]\"\n :license \"MPL-2.0\"\n :io [1 2]\n :size [240 72]\n :args [[:seconds 60]]\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 (sample? d) [(str \"(sample! \" id \" \" (pr-str d) \")\")]))}\n :receive (fn [{:keys [inlet value state data]}]\n (let [rec? (:rec state)]\n (cond\n (= inlet :audio)\n (cond\n (:started value) {:state (assoc state :rec true) :show {:rec 0}}\n (:progress value) (if rec? {:show {:rec (:progress value) :level (:level value)}} {})\n (:done value) {:state (dissoc state :rec) :show nil :out [[0 (seconds (:done value))]]}\n (:error value) {:state (dissoc state :rec) :show nil :effects [[:print (:error value)]]}\n :else {})\n ;; the node says when it starts (only while ▶ is on: without it there is no sound to record)\n (= value :rec) {:effects [[:rec true]]}\n ;; rec t (msg :rec 2.5): the sound until t stays, the take replaces what comes after (punch-in)\n (and (vector? value) (= :rec (first value)) (number? (second value)) (>= (second value) 0))\n {:effects [[:rec {:from (second value) :base (when (sample? data) data)}]]}\n ;; ovr t (msg :ovr 2.5): only what the take covers is replaced, what comes after it stays (punch-in/out)\n (or (= value :ovr) (and (vector? value) (= :ovr (first value)) (number? (second value)) (>= (second value) 0)))\n {:effects [[:rec {:from (if (vector? value) (second value) 0) :base (when (sample? data) data) :ovr true}]]}\n (= value :stop) {:effects [[:rec false]]}\n (= value :bang) (if (sample? data) {:out [[0 (seconds data)]]} {})\n (= value :clear) {:effects [[:sample [:clear]]]}\n ;; a URL (a string, or [:url \"…\"]): the page loads it and writes it as the data of the box\n ;; msg https://… (or msg \"https://…\", or msg :url \"…\") arrives as a name or a string: as-url reads it\n (as-url value) {:effects [[:sample [:url (as-url value)]]]}\n (and (sequential? value) (= :url (first value)) (as-url (second value)))\n {:effects [[:sample [:url (as-url (second value))]]]}\n (and (sequential? value) (= :url (first value)))\n {:effects [[:print (str \"sample: \" (pr-str (second value)) \" is not a URL a sound can be loaded from\")]]}\n (or (string? value) (keyword? value) (symbol? value))\n {:effects [[:print (str \"sample: \" (pr-str value) \" is neither :rec, :stop, :clear nor a URL (https://…, github:…, freesound:…)\")]]}\n :else {})))\n ;; drawing it is also when this browser looks for its sound (and fetches it, if it comes from a URL)\n :draw (fn [{:keys [data shown w h]}]\n (let [w (or w 240) h (or h 72) mid (/ (- h 12) 2) d (when (sample? data) (merge data (about data)))\n here (when d (get @status (:audio d)))]\n (when d (check! data))\n [[:rect {:x 2 :y 2 :w (- w 4) :h (- h 4) :r 4 :stroke :grid :fill :bg}]\n [:line {:x1 6 :y1 (+ 2 mid) :x2 (- w 6) :y2 (+ 2 mid) :stroke :grid}]\n (when (seq (:peaks d)) [:path {:points (wave-points (:peaks d) 6 (- w 6) (+ 2 mid) (- mid 4))\n :stroke (if (#{:missing :failed} here) :soft :accent) :weight 1}])\n (if (:rec shown)\n [:text {:x 8 :y (- h 7) :size 10 :fill :kairos} (str \"● rec \" (fmt-s (:rec shown)))]\n [:text {:x 8 :y (- h 7) :size 9 :fill :soft}\n (cond\n (and d (= here :loading)) \"loading…\"\n (and d (= here :failed))\n (if (re-find #\"API key\" (str (get @failures (:audio d)))) \"needs a Freesound API key\" \"could not load its URL\")\n (and d (number? (:sr d)))\n (str (fmt-s (seconds d)) \" · \" (comp/nice (/ (:sr d) 1000)) \" kHz\"\n (when (> (or (:channels d) 1) 1) (str \" · \" (:channels d) \" ch\"))\n (if-let [c (:credit d)]\n (str \" · \" (:author c) (when (seq (:license c)) (str \" · \" (:license c))))\n (when (:url d) \" · URL\"))\n (when (= here :missing) \" · not in this browser\"))\n d \"…\"\n :else \"empty · rec records what reaches it\")])\n (when (and (:rec shown) (number? (:level shown)))\n [:rect {:x (- w 70) :y (- h 13) :w (* 60 (comp/clamp (:level shown) 0 1)) :h 4 :r 1 :stroke nil :fill :kairos}])]))\n :audio {:create (fn [ac b _]\n (let [in (.createGain ac)\n secs (sample-seconds (:seconds (comp/args-for (comp/lookup \"sample\") (:text b))))\n node {:ac ac :id (:id b) :in in :seconds (atom secs) :tap (atom nil) :L (atom nil) :rec (atom nil)\n :alive (atom true) :inlets [[in 0]] :outlets []}]\n (.then (lib) (fn [L] (reset! (:L node) L)))\n (-> (api/tap ac {:mode :frames :size block :hop block :active false}\n (fn [data _ _ flags] (on-block! node data flags)))\n (.then (fn [w]\n (if @(:alive node)\n (do (.connect in w) (reset! (:tap node) w)\n (when @(:rec node) (api/retap w {:active true})))\n (try (.disconnect w) (catch :default _ nil)))))\n (.catch (fn [e] (js/console.error \"sample\" e))))\n node))\n :update (fn [node b _]\n (reset! (:seconds node) (sample-seconds (:seconds (comp/args-for (comp/lookup \"sample\") (:text b))))))\n :effects {:rec (fn [node on at] (if on (start! node at on) (stop! node)))}\n ;; ■ while recording keeps what was heard until then\n :dispose (fn [node]\n (reset! (:alive node) false)\n (when @(:rec node) (finish! node (:id node)))\n (try (.disconnect (:in node)) (catch :default _ nil)))}})\n","kairotic/span.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · span: a ring of messages and its heads, pure (discussion \"Heads on a span of time\", Studies 44 and 47)\n;;\n;; A ring keeps what was written in the last `dur` seconds. Its time starts at its first message (or the first\n;; one after :clear); its implicit write head is where that time is, and as a tape head it erases what it passes:\n;; what is older than one turn is gone. Positions on the ring are seconds in [0, dur) (the span's own units);\n;; events keep the time they belong to, unwrapped (seconds since the start), so a head that goes round is still\n;; moving forwards and an event is met again at every turn.\n;;\n;; {:ring true :dur 8 :t0 at-or-nil :events [{:t seconds-since-start :v value :w instant-written} …]}\n;;\n;; Writers (other boxes) send it edits: [:write p v mode] at position p (or :now, the head) — with :ovr it\n;; replaces what was written there before, not what arrives with it (a chord stays) —, [:cut a b] (what a writer\n;; passed going from a to b: forwards (a, b], backwards [b, a)), [:erase] (everything; time goes on).\n;; Readers meet the events they cross (crossings), in the order they meet them.\n\n(ns kairotic.span)\n\n(def eps 1e-9)\n\n(defn ring\n \"An empty ring that keeps dur seconds, waiting for its first message to start its time.\"\n [dur]\n {:ring true :dur (if (and (number? dur) (pos? dur)) dur 8) :t0 nil :events []})\n\n(defn ring? [x] (and (map? x) (true? (:ring x))))\n\n(defn head\n \"Where the ring's write head is at instant at (seconds since its start, unwrapped), or nil before it starts.\"\n [r at]\n (when-let [t0 (:t0 r)] (- at t0)))\n\n(defn wrap\n \"A position of the span, in [0, dur).\"\n [r p]\n (let [l (:dur r) x (mod p l)] (if (< (- l x) eps) 0 x)))\n\n(defn start\n \"The ring's time starts at at, if it had not.\"\n [r at]\n (if (:t0 r) r (assoc r :t0 at)))\n\n(defn alive\n \"What the ring keeps at instant at: what was written within one turn of the head.\"\n [r at]\n (if-let [h (head r at)]\n (let [lo (+ (- h (:dur r)) eps)]\n (filterv (fn [e] (> (:t e) lo)) (:events r)))\n []))\n\n(defn- prune [r at] (assoc r :events (alive r at)))\n\n(defn- place\n \"The time an event written at position p (wrapped) belongs to: the latest one, not after the head.\"\n [r at p]\n (let [h (head r at)] (- h (mod (- h (wrap r p)) (:dur r)))))\n\n(defn- same-place? [r a b] (let [d (mod (- a b) (:dur r))] (or (< d 1e-6) (< (- (:dur r) d) 1e-6))))\n\n(defn write\n \"Writes v at instant at: at the head (p :now or nil) or at position p. With :ovr, what was written there before\n (at another instant) goes; what arrives with it stays.\"\n ([r at v] (write r at :now v :mix))\n ([r at p v mode]\n (let [r (prune (start r at) at)\n t (if (or (nil? p) (= :now p)) (head r at) (place r at p))\n keep? (fn [e] (not (and (= :ovr mode) (not= (:w e) at) (same-place? r (:t e) t))))]\n (assoc r :events (vec (sort-by :t (conj (filterv keep? (:events r)) {:t t :v v :w at})))))))\n\n(defn- in-sweep?\n \"Is position x (wrapped) met by a head going from a to b (unwrapped)? Forwards (a, b], backwards [b, a).\"\n [l x a b]\n (if (< a b)\n (let [k (js/Math.ceil (/ (- (+ a eps) x) l)) y (+ x (* k l))] (<= y (+ b eps)))\n (let [k (js/Math.floor (/ (- (- a eps) x) l)) y (+ x (* k l))] (>= y (- b eps)))))\n\n(defn crossings\n \"The events met going from a to b (positions of the span, unwrapped: a move of more than a turn meets an event\n more than once), in the order they are met, as [position-where-met event].\"\n [r at a b]\n (let [l (:dur r) es (alive r at)]\n (cond\n (or (nil? a) (nil? b) (= a b)) []\n (< a b)\n (->> (for [e es\n :let [k0 (js/Math.ceil (/ (- (+ a eps) (:t e)) l))]\n k (range k0 (inc (js/Math.floor (/ (- (+ b eps) (:t e)) l))))]\n [(+ (:t e) (* k l)) e])\n (sort-by first) vec)\n :else\n (->> (for [e es\n :let [k0 (js/Math.floor (/ (- (- a eps) (:t e)) l))]\n k (range k0 (dec (js/Math.ceil (/ (- (- b eps) (:t e)) l))) -1)]\n [(+ (:t e) (* k l)) e])\n (sort-by (comp - first)) vec))))\n\n(defn cut\n \"What a writer passed going from a to b (positions, unwrapped) is gone.\"\n [r at a b]\n (let [r (prune r at) l (:dur r)]\n (if (or (nil? a) (nil? b) (= a b) (nil? (:t0 r)))\n r\n (let [lo (min a b) hi (max a b)]\n (if (>= (- hi lo) l)\n (assoc r :events [])\n (assoc r :events (filterv (fn [e] (not (in-sweep? l (:t e) a b))) (:events r))))))))\n\n(defn erase \"Everything is gone; time goes on.\" [r] (assoc r :events []))\n\n(defn shortest\n \"The move from position a to position q on a ring of length l: the one shorter than half a turn (a phasor~ that\n goes back to 0 has gone on, not back).\"\n [l a q]\n (let [d (mod (- q a) l)] (if (> d (/ l 2)) (- d l) d)))\n\n;; ───────── a reader that follows the ring's head ─────────\n;; d behind it, then drifting by (1 − speed) for each second: first the distance, then the speed (Study 47).\n;; Its position at instant T: head(T) − d − drift0 − (1 − speed)·(T − since).\n\n(defn follow-at\n \"Where a following reader is at instant T (unwrapped), or nil before the ring starts.\"\n [r {:keys [d speed drift0 since]} T]\n (when-let [h (head r T)]\n (- h d (or drift0 0) (* (- 1 speed) (- T (or since T))))))\n\n(defn when-met\n \"The instant a following reader at position p at instant T (moving at speed) meets position x.\"\n [p T speed x]\n (if (zero? speed) T (max T (+ T (/ (- x p) speed)))))\n","kairotic/spell.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · spell\n;; How a pitch is written (issue #88): a letter, an alteration and an octave, not only a MIDI number.\n;; G# and Ab sound alike and are written apart; the line of fifths (… Bb F C G D A E B F# C# …, one\n;; integer each: C = 0, G = 1, F = -1) says how far a name is from another, so that transposing,\n;; inverting and choosing a name for a sound are arithmetic on it (as in Ooloi ADR-0026 or music21).\n;;\n;; a spelling {:step 0…6 (c d e f g a b) :alter -2…2 :oct n} \"bb4\", \"f##3\", \"fx3\", \"ebb2\", \"c4\"\n;; an interval \"M3\" \"-P5\" \"A4\" \"d5\" \"m9\" … , or [steps semitones]\n;; a key \"eb\" \"c#m\" \"d dorian\" \"f lydian\" :none, or a key signature as a number (3: three sharps)\n;;\n;; Spelling the notes that have no name (numbers, Hz, a freqt's strokes): `spell-steps` chooses, for each\n;; note, the name nearest the key on the line of fifths, with melodic and vertical sense (a Viterbi over\n;; the onsets: chromatic notes rise as sharps and fall as flats, no augmented seconds where a minor\n;; third does, chords stacked in thirds), the key given or estimated per bar (Temperley's profiles).\n\n(ns kairotic.spell\n (:require [clojure.string :as str]))\n\n(def letters [\"c\" \"d\" \"e\" \"f\" \"g\" \"a\" \"b\"])\n(def natural-pc [0 2 4 5 7 9 11])\n(def natural-fifths [0 2 4 -1 1 3 5])\n\n;; ───────── spellings ─────────\n\n(defn parse\n \"A pitch name → {:step :alter :oct}: \\\"bb4\\\", \\\"f#3\\\", \\\"fs3\\\", \\\"f##3\\\", \\\"fx3\\\", \\\"ebb2\\\", \\\"cn4\\\"; nil if\n it is not one. c4 is middle C.\"\n [s]\n (when-let [[_ l acc o] (and (or (string? s) (keyword? s))\n (re-matches #\"(?i)\\s*([a-g])(##|#|x|s|bb|b|n)?(-?\\d+)\\s*\" (name s)))]\n {:step (.indexOf letters (str/lower-case l))\n :alter (case (some-> acc str/lower-case) (\"##\" \"x\") 2 (\"#\" \"s\") 1 \"bb\" -2 \"b\" -1 0)\n :oct (js/parseInt o 10)}))\n\n(defn ->midi [{:keys [step alter oct]}] (+ (* 12 (inc oct)) (natural-pc step) alter))\n\n(defn fifths \"Where a spelling is on the line of fifths (C 0, G 1, F -1, F# 6, Bb -2).\" [{:keys [step alter]}]\n (+ (natural-fifths step) (* 7 alter)))\n\n(defn acc-str [alter] (case alter 2 \"##\" 1 \"#\" -1 \"b\" -2 \"bb\" \"\"))\n\n(defn ->name \"{:step 6 :alter -1 :oct 4} → \\\"bb4\\\".\" [{:keys [step alter oct] :as sp}]\n (when sp (str (letters step) (acc-str alter) oct)))\n\n(defn from-fifths\n \"The spelling at position f of the line of fifths that sounds midi (an integer), or nil.\"\n [f midi]\n (let [base (- (mod (inc f) 7) 1)\n alter (/ (- f base) 7)\n step (.indexOf natural-fifths base)\n oct (- (/ (- midi (natural-pc step) alter) 12) 1)]\n (when (and (>= step 0) (== oct (js/Math.round oct))) {:step step :alter alter :oct oct})))\n\n(defn spellings\n \"Every way to write an integer MIDI pitch with at most two sharps or flats, fewest alterations first:\n 61 → c#4, db4 (and b##3).\"\n [midi]\n (let [pc (mod midi 12)]\n (->> (range 7)\n (keep (fn [step]\n (let [alter (- (mod (+ (- pc (natural-pc step)) 6) 12) 6)]\n (when (<= (js/Math.abs alter) 2)\n {:step step :alter alter :oct (- (/ (- midi (natural-pc step) alter) 12) 1)}))))\n (sort-by (fn [sp] (js/Math.abs (:alter sp))))\n vec)))\n\n;; ───────── intervals ─────────\n\n(def ^:private simple-semis [0 2 4 5 7 9 11])\n\n(defn interval\n \"An interval as [steps semitones]: \\\"M3\\\" → [2 4], \\\"-P5\\\" → [-4 -7], \\\"A4\\\" → [3 6], \\\"d5\\\" → [4 6],\n \\\"m9\\\" → [8 13]; [steps semitones] as it is; nil if it does not read.\"\n [x]\n (cond\n (and (vector? x) (= 2 (count x)) (every? integer? x)) x\n (or (string? x) (keyword? x) (symbol? x))\n (when-let [[_ sign q n] (re-matches #\"\\s*([+-]?)(P|M|m|A+|d+)(\\d+)\\s*\" (if (symbol? x) (str x) (name x)))]\n (let [n (js/parseInt n 10) s (mod (dec n) 7) octs (quot (dec n) 7)\n perfect? (#{0 3 4} s)\n adj (cond (= q \"P\") (when perfect? 0)\n (= q \"M\") (when-not perfect? 0)\n (= q \"m\") (when-not perfect? -1)\n (str/starts-with? q \"A\") (count q)\n (str/starts-with? q \"d\") (- (+ (count q) (if perfect? 0 1))))]\n (when (and (pos? n) (some? adj))\n (let [st (+ s (* 7 octs)) se (+ (simple-semis s) (* 12 octs) adj) k (if (= sign \"-\") -1 1)]\n [(* k st) (* k se)]))))\n :else nil))\n\n(defn interval-of-semitones\n \"The interval a transposition by n semitones is written as: 1 → m2, 6 → A4 (or d5: dim? true), 7 → P5.\"\n ([n] (interval-of-semitones n false))\n ([n dim?]\n (let [k (if (neg? n) -1 1) a (js/Math.abs n) o (quot a 12) r (mod a 12)\n steps ([0 1 1 2 2 3 (if dim? 4 3) 4 5 5 6 6] r)]\n [(* k (+ steps (* 7 o))) n])))\n\n(defn transpose-spelling\n \"A spelling moved by an interval [steps semitones]: c4 + M3 = e4, c4 + A4 = f#4, c4 - m2 = b3.\"\n [{:keys [step oct] :as sp} [steps semis]]\n (let [s (+ step steps) nstep (mod s 7) noct (+ oct (js/Math.floor (/ s 7)))\n target (+ (->midi sp) semis)\n natural (+ (* 12 (inc noct)) (natural-pc nstep))]\n {:step nstep :alter (- target natural) :oct noct}))\n\n(defn invert-spelling\n \"A spelling mirrored around a pivot spelling: on the line of fifths and in pitch (c4 around e4 = g#4).\"\n [sp pivot]\n (or (from-fifths (- (* 2 (fifths pivot)) (fifths sp)) (- (* 2 (->midi pivot)) (->midi sp)))\n sp))\n\n;; ───────── keys ─────────\n\n(def mode-offsets {:major 0 :ionian 0 :dorian -2 :phrygian -4 :lydian 1 :mixolydian -1 :minor -3 :aeolian -3 :locrian -5})\n\n(defn parse-key\n \"A key → {:sig n (sharps +, flats -) :tonic fifths :mode kw}, {:none true} for :none (atonal: no key),\n or nil. \\\"eb\\\", \\\"Eb\\\", \\\"c#m\\\", \\\"c# minor\\\", \\\"d dorian\\\", a number (a signature: 3 is A major's).\"\n [k]\n (cond\n (nil? k) nil\n (or (= k :none) (= (str/lower-case (name (if (keyword? k) k (str k)))) \"none\")) {:none true :sig 0}\n (and (number? k) (integer? k) (<= -7 k 7)) {:sig k :tonic k :mode :major}\n (map? k) (when (integer? (:sig k)) k)\n (or (string? k) (keyword? k))\n (when-let [[_ l acc m] (re-matches #\"(?i)\\s*([a-g])(##|#|x|s|bb|b)?\\s*(m|min|minor|maj|major|ionian|dorian|phrygian|lydian|mixolydian|aeolian|locrian)?\\s*\" (name k))]\n (let [tonic (fifths {:step (.indexOf letters (str/lower-case l))\n :alter (case (some-> acc str/lower-case) (\"##\" \"x\") 2 (\"#\" \"s\") 1 \"bb\" -2 \"b\" -1 0)})\n mode (case (some-> m str/lower-case) (\"m\" \"min\" \"minor\") :minor (nil \"maj\" \"major\") :major (keyword (str/lower-case m)))\n sig (+ tonic (mode-offsets mode))]\n (when (<= -7 sig 7) {:sig sig :tonic tonic :mode mode})))\n :else nil))\n\n(defn key-name\n \"A key as text, from where its tonic is on the line of fifths and its mode: {:tonic -3 :mode :major} →\n \\\"eb\\\", {:tonic 7 :mode :minor} → \\\"c#m\\\", {:tonic 2 :mode :dorian} → \\\"d dorian\\\".\"\n [{:keys [tonic mode]}]\n (let [alter (js/Math.floor (/ (inc tonic) 7))\n step (.indexOf natural-fifths (- tonic (* 7 alter)))]\n (str (letters step) (acc-str alter)\n (case mode (nil :major :ionian) \"\" (:minor :aeolian) \"m\" (str \" \" (name mode))))))\n\n(defn transpose-key\n \"A key (as parse-key reads it) moved by an interval [steps semitones], as text: \\\"eb\\\" by a major third\n is \\\"g\\\", \\\"c#m\\\" by a minor second down is \\\"cm\\\". :none, and what is not a key, stay as they are.\n A key beyond seven sharps or flats takes the tonic that sounds the same (E# major → F major).\"\n [k iv]\n (let [{:keys [tonic mode none] :as pk} (parse-key k)]\n (if (or (nil? pk) none (nil? tonic))\n k\n (let [df (fifths (transpose-spelling {:step 0 :alter 0 :oct 4} iv))\n t (+ tonic df) off (mode-offsets (or mode :major))\n t (cond (> (+ t off) 7) (- t 12) (< (+ t off) -7) (+ t 12) :else t)]\n (key-name {:tonic t :mode mode})))))\n\n(defn mei-key-sig \"A signature as MEI writes it: 3 → \\\"3s\\\", -2 → \\\"2f\\\", 0 → \\\"0\\\".\" [sig]\n (cond (pos? sig) (str sig \"s\") (neg? sig) (str (- sig) \"f\") :else \"0\"))\n\n(defn key-alter\n \"The alteration a signature gives a step: in 2 sharps, F and C are sharp (1); in 1 flat, B is flat (-1).\"\n [sig step]\n (let [x (natural-fifths step)]\n (cond (and (pos? sig) (< x (dec sig))) 1\n (and (neg? sig) (> x (+ 5 sig))) -1\n :else 0)))\n\n(defn key-center \"The middle of a key's notes on the line of fifths (its signature + 2).\" [sig] (+ sig 2))\n\n;; Temperley's key profiles (Music and Probability, 2007): they weigh notes outside a key lower than\n;; Krumhansl–Kessler's, which tells A minor from E major in a few notes (C is far from E major)\n(def ^:private major-profile [5.0 2.0 3.5 2.0 4.5 4.0 2.0 4.5 2.0 3.5 1.5 4.0])\n(def ^:private minor-profile [5.0 2.0 3.5 4.5 2.0 4.0 2.0 4.5 3.5 2.0 1.5 4.0])\n\n(defn- correlation [xs ys]\n (let [n (count xs) mx (/ (reduce + xs) n) my (/ (reduce + ys) n)\n sxy (reduce + (map (fn [x y] (* (- x mx) (- y my))) xs ys))\n sxx (reduce + (map (fn [x] (* (- x mx) (- x mx))) xs))\n syy (reduce + (map (fn [y] (* (- y my) (- y my))) ys))]\n (if (or (zero? sxx) (zero? syy)) 0 (/ sxy (js/Math.sqrt (* sxx syy))))))\n\n(defn tonic-fifths\n \"Where a tonic of pitch class pc is on the line of fifths, so that its key (in mode) has the fewest\n alterations: pc 1 major → Db (-5), pc 1 minor → C# (7).\"\n [pc mode]\n (let [r (mod (* 7 pc) 12) off (mode-offsets mode)]\n (first (sort-by (fn [f] [(js/Math.abs (+ f off)) (- f)]) [r (- r 12)]))))\n\n(defn estimate-key\n \"The key whose profile best matches a duration per pitch class (a vector of 12), as parse-key gives\n it, with :score its correlation (between two that fit alike, fewer alterations); nil when there is\n nothing to hear.\"\n [weights]\n (when (pos? (reduce + weights))\n (let [rot (fn [p k] (vec (for [i (range 12)] (p (mod (- i k) 12)))))\n ;; between keys that fit as well, the one with fewer alterations\n best (apply max-key (fn [x] (- (:score x) (* 0.01 (js/Math.abs (:sig x)))))\n (for [k (range 12) [mode p] [[:major major-profile] [:minor minor-profile]]\n :let [tonic (tonic-fifths k mode)]]\n {:pc k :mode mode :tonic tonic :sig (+ tonic (mode-offsets mode)) :score (correlation weights (rot p k))}))]\n (select-keys best [:sig :tonic :mode :score]))))\n\n(defn estimate-sig\n \"The signature of the key the weights suggest, when they suggest one clearly (a correlation of 0.5 or\n more): nil for notes that fit no key (a chromatic line, a whole-tone scale), which are then named\n without one, near C.\"\n [weights]\n (let [k (estimate-key weights)]\n (when (and k (>= (:score k) 0.5)) (:sig k))))\n\n;; ───────── spelling notes ─────────\n\n(defn- step-cost\n \"How a set of spellings sounds as one onset in a key: far from the key's notes (center ± 3), double\n alterations, and a chord spread wider than a tritone's span on the line of fifths.\"\n [sps center]\n (let [fs (map fifths sps)]\n (+ (reduce + (map (fn [f] (let [d (js/Math.abs (- f center))] (if (<= d 3) 0 (* 0.8 (- d 3))))) fs))\n (* 2.5 (count (filter (fn [sp] (= 2 (js/Math.abs (:alter sp)))) sps)))\n (* 0.05 (reduce + (map (fn [sp] (js/Math.abs (:alter sp))) sps)))\n (if (> (count fs) 1) (* 0.4 (max 0 (- (- (apply max fs) (apply min fs)) 6))) 0))))\n\n(defn- move-cost\n \"How one voice moves from spelling a to b in a key of signature sig: an augmented or diminished step\n (more than six fifths apart: C to D#, E to Gb) costs; a raised note that falls a semitone, or a\n lowered one that rises, costs more than the key's preference (chromatic lines rise in sharps and fall\n in flats).\"\n [a b sig]\n (let [d (js/Math.abs (- (fifths b) (fifths a)))\n semis (- (->midi b) (->midi a))]\n (+ (if (<= d 6) 0 (* 0.7 (- d 6)))\n (cond (and (= semis -1) (> (:alter a) (key-alter sig (:step a)))) 2\n (and (= semis 1) (< (:alter a) (key-alter sig (:step a)))) 2\n :else 0))))\n\n(defn- combos [xss]\n (reduce (fn [acc xs] (for [a acc x xs] (conj a x))) [[]] xss))\n\n(defn spell-steps\n \"Names for notes in time: steps [{:sig n :notes [{:id :midi (an integer) :voice :fixed spelling-or-nil}]}],\n one per onset, in order (:sig the key there). Returns {id spelling}. A note that is written keeps its\n name (:fixed); the others take the names that cost least over the whole line (Viterbi): near the key,\n moving well in their voice, stacked well in their chord.\"\n [steps]\n (let [cands (fn [{:keys [sig notes]}]\n (let [c (key-center sig)\n per (mapv (fn [n] (if (:fixed n)\n [(:fixed n)]\n (vec (take 3 (sort-by (fn [sp] (js/Math.abs (- (fifths sp) c))) (spellings (:midi n)))))))\n notes)]\n (if (> (reduce * 1 (map count per)) 81)\n [(mapv first per)] ; too many notes at once: each its nearest\n (vec (combos per)))))\n layers (mapv (fn [st] (let [cs (cands st) c (key-center (:sig st))]\n {:step st :states (mapv (fn [sps] {:sps sps :static (step-cost sps c)}) cs)}))\n steps)\n trans (fn [prev-st prev-sps st sps]\n (let [pv (into {} (map (fn [n sp] [(:voice n) sp]) (:notes prev-st) prev-sps))]\n (reduce + (map (fn [n sp] (if-let [a (get pv (:voice n))] (move-cost a sp (:sig st)) 0)) (:notes st) sps))))\n dp (reduce (fn [acc {:keys [step states]}]\n (if (empty? acc)\n [(mapv (fn [s] {:cost (:static s) :back nil :sps (:sps s)}) states)]\n (let [prev (peek acc) pst (:step (nth layers (dec (count acc))))]\n (conj acc (mapv (fn [s]\n (let [[bi bc] (reduce (fn [[bi bc] [i p]]\n (let [c (+ (:cost p) (trans pst (:sps p) step (:sps s)))]\n (if (< c bc) [i c] [bi bc])))\n [0 js/Infinity] (map-indexed vector prev))]\n {:cost (+ bc (:static s)) :back bi :sps (:sps s)}))\n states)))))\n [] layers)]\n (if (empty? dp)\n {}\n (loop [i (dec (count dp))\n j (first (apply min-key second (map-indexed (fn [j s] [j (:cost s)]) (peek dp))))\n out {}]\n (if (neg? i)\n out\n (let [s (nth (nth dp i) j) st (:step (nth layers i))]\n (recur (dec i) (:back s) (into out (map (fn [n sp] [(:id n) sp]) (:notes st) (:sps s))))))))))\n","kairotic/structure.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · structure\n;; The form of what is heard or played, from how alike its moments are (issue #120):\n;; · a self-similarity matrix (SSM): the cosine of every two frames' vectors (Foote 1999). Frames can be of\n;; audio (a chroma, descriptors, an onset envelope: what form~ gets) or of notes (one per beat: the pitch\n;; classes sounding in it, its onsets, how strong they were);\n;; · novelty: how much the music changes at each frame, by a checkerboard kernel slid along the diagonal of the\n;; SSM (Foote 2000) — its peaks are the boundaries of segments;\n;; · the beat spectrum: how alike frames are at each lag, the mean of each diagonal (Foote & Uchihashi 2001) —\n;; its peaks are the periods that repeat (the bar, the phrase);\n;; · segments: the novelty peaks, with a shortest and a longest segment.\n;; Pure functions on numbers. Matrices are flat Float64Arrays, n × n ({:n :data}); a few hundred frames are cheap,\n;; thousands are not (the matrix grows with their square): use frames per beat, per onset, or ~100 ms apart.\n\n(ns kairotic.structure)\n\n(defn- sq [x] (* x x))\n\n(defn unit\n \"A vector scaled to length 1 (a vector of zeros stays zeros).\"\n [v]\n (let [l (js/Math.sqrt (reduce + (map sq v)))]\n (if (pos? l) (mapv (fn [x] (/ x l)) v) (vec v))))\n\n(defn ssm\n \"The self-similarity matrix of vectors (frames, all of one length): {:n :data}, data[i n + j] the cosine of\n frames i and j (1 alike … 0 unrelated, for vectors of non-negative values).\"\n [vs]\n (let [us (mapv unit vs) n (count us) d (js/Float64Array. (* n n))]\n (dotimes [i n]\n (let [a (us i)]\n (loop [j i]\n (when (< j n)\n (let [b (us j) s (reduce + (map * a b))]\n (aset d (+ (* i n) j) s) (aset d (+ (* j n) i) s)\n (recur (inc j)))))))\n {:n n :data d}))\n\n(defn at \"The similarity of frames i and j.\" [{:keys [n data]} i j] (aget data (+ (* i n) j)))\n\n(defn novelty\n \"How much the music changes at each frame: a checkerboard kernel of half-width L (frames), tapered by a\n Gaussian, slid along the diagonal (Foote 2000): high where the frames before are alike among themselves and\n unlike the ones after. Scaled to 0 … 1. A vector of n values.\"\n [{:keys [n] :as S} L]\n (let [L (max 1 (js/Math.round L))\n g (fn [a b] (js/Math.exp (- (/ (+ (sq (+ a 0.5)) (sq (+ b 0.5))) (* 2 (sq (* 0.5 L)))))))\n raw (mapv (fn [i]\n (loop [a (- L) acc 0]\n (if (>= a L)\n acc\n (recur (inc a)\n (loop [b (- L) acc acc]\n (if (>= b L)\n acc\n (let [x (+ i a) y (+ i b)]\n (recur (inc b)\n (if (and (< -1 x n) (< -1 y n))\n (+ acc (* (if (= (neg? a) (neg? b)) 1 -1) (g a b) (at S x y)))\n acc)))))))))\n (range n))\n top (reduce max 1e-12 raw)]\n (mapv (fn [x] (max 0 (/ x top))) raw)))\n\n(defn novelty-at\n \"The novelty of frame i alone (see novelty), not scaled by the others: the checkerboard's sum divided by the\n sum of its weights, so -1 … 1 (0 where it does not change). For a stream, where frames keep arriving: frame i\n needs L frames after it. nil when it has fewer than L frames on either side.\"\n [{:keys [n] :as S} L i]\n (let [L (max 1 (js/Math.round L))]\n (when (and (>= i L) (<= (+ i L) n))\n (let [g (fn [a b] (js/Math.exp (- (/ (+ (sq (+ a 0.5)) (sq (+ b 0.5))) (* 2 (sq (* 0.5 L)))))))]\n (loop [a (- L) acc 0 wsum 0]\n (if (>= a L)\n (/ acc (max 1e-12 wsum))\n (let [[acc wsum] (loop [b (- L) acc acc wsum wsum]\n (if (>= b L)\n [acc wsum]\n (let [w (g a b)]\n (recur (inc b) (+ acc (* (if (= (neg? a) (neg? b)) 1 -1) w (at S (+ i a) (+ i b)))) (+ wsum w)))))]\n (recur (inc a) acc wsum))))))))\n\n(defn beat-spectrum\n \"How alike frames are at each lag 0 … max-lag: the mean of each diagonal of the SSM (Foote & Uchihashi 2001).\n Its peaks are the periods that repeat.\"\n [{:keys [n] :as S} max-lag]\n (mapv (fn [l] (if (>= l n) 0 (/ (reduce + (map (fn [i] (at S i (+ i l))) (range (- n l)))) (- n l))))\n (range (inc (min max-lag (dec n))))))\n\n(defn periods\n \"The lags at which the beat spectrum peaks (higher than both neighbours), strongest first: [[lag value] …].\"\n [bs]\n (let [v (vec bs)]\n (->> (range 1 (dec (count v)))\n (filter (fn [l] (and (> (v l) (v (dec l))) (>= (v l) (v (inc l))))))\n (map (fn [l] [l (v l)]))\n (sort-by (fn [[_ x]] (- x)))\n vec)))\n\n(defn boundaries\n \"The frames where segments begin: novelty peaks above mean + k × deviation, at least shortest frames apart\n (the higher peak wins), and, in a segment longer than longest, its highest novelty point too (its middle,\n if it is flat). Always\n starts with 0.\"\n [nov {:keys [shortest longest k] :or {shortest 8 longest 64 k 0.5}}]\n (let [v (vec nov) n (count v)\n mean (/ (reduce + v) (max 1 n))\n sd (js/Math.sqrt (/ (reduce + (map (fn [x] (sq (- x mean))) v)) (max 1 n)))\n peaks (filter (fn [i] (and (> (v i) (+ mean (* k sd)))\n (>= (v i) (get v (dec i) 0)) (>= (v i) (get v (inc i) 0))))\n (range 1 n))\n ;; the highest first, each keeping the others shortest frames away\n chosen (reduce (fn [acc i] (if (every? (fn [j] (>= (js/Math.abs (- i j)) shortest)) acc) (conj acc i) acc))\n [0] (sort-by (fn [i] (- (v i))) peaks))\n chosen (sort chosen)\n ;; a segment longer than longest is cut at its highest point\n split (fn split [a b]\n (if (or (<= (- b a) longest) (< (- b a) (* 2 shortest)))\n [a]\n (let [mid (/ (+ a b) 2)\n c (apply max-key (fn [i] (- (v i) (* 1e-9 (js/Math.abs (- i mid))))) (range (+ a shortest) (- b shortest)))]\n (concat (split a c) (split c b)))))]\n (vec (distinct (mapcat (fn [[a b]] (split a b)) (partition 2 1 (concat chosen [n])))))))\n\n;; ───────── frames of notes ─────────\n\n(defn note-frames\n \"Notes ({:on :off :attrs {:pitch :vel}}) as one vector per frame between the times given (beats found,\n or a grid): 12 pitch classes (each weighed by how long it sounds in the frame and how strong it was), then\n the strength of the onsets in the frame and how many there are (scaled). For the SSM of what was played.\"\n [notes times]\n (let [ts (vec times) nf (dec (count ts))\n midi (fn [n] (let [p (get-in n [:attrs :pitch])] (when (number? p) p)))\n vel (fn [n] (let [v (get-in n [:attrs :vel])] (if (number? v) (if (> v 1) (/ v 127) v) 0.7)))]\n (mapv (fn [f]\n (let [a (ts f) b (ts (inc f)) len (max 1e-9 (- b a))\n pcs (reduce (fn [pc n]\n (if-let [m (midi n)]\n (let [o (- (min b (:off n)) (max a (:on n)))]\n (if (pos? o) (update pc (mod (js/Math.round m) 12) + (* (/ o len) (+ 0.3 (vel n)))) pc))\n pc))\n (vec (repeat 12 0)) notes)\n starts (filter (fn [n] (and (>= (:on n) a) (< (:on n) b))) notes)]\n (conj pcs (reduce + (map vel starts)) (* 0.25 (count starts)))))\n (range (max 0 nf)))))\n","kairotic/talk.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · talk: what is said in a room, and a clock the pages of a room agree on (discussion #135,\n;; Studies 34 · io and 36 · talk). Pure: the page (app/page/20-talk.cljs) does the WebRTC and the sound.\n;;\n;; Everything said in a room is ephemeral: it lives in the pages that are there and goes when they go.\n;; Something stays only when someone keeps it, and then it is a gesture of the work:\n;; a message → a text annotation (layer :talk), on the box it names if it names one (@b3)\n;; a voice note → a sound in a sample box (kept by hash, as recorded audio is)\n;; a video frame → an image annotation\n;; Anyone keeps what is theirs at once; keeping what is someone else's asks them first.\n\n(ns kairotic.talk\n (:require [clojure.string :as str]))\n\n(defn signal-url\n \"The relay's rooms for a GUN relay address: wss://host/gun → wss://host/signal (nil if it is not one).\"\n [gun-url]\n (when-let [[_ scheme host] (re-matches #\"(wss?)://([^/\\s,]+)(/[^\\s,]*)?\" (str gun-url))]\n (str scheme \"://\" host \"/signal\")))\n\n;; ───────── messages and their anchors ─────────\n;; In the text: @b3 a box, #12 a point of the history, ^33 a beat (of the room's tempo).\n\n(defn anchors\n \"The anchors written in a text, in order, without repeating.\"\n [text]\n (->> (re-seq #\"(?:^|\\s)(@[A-Za-z][\\w~-]*|#\\d+|\\^\\d+(?:\\.\\d+)?)\" (or text \"\"))\n (map second)\n (map (fn [w] (case (first w)\n \"@\" {:box (subs w 1)}\n \"#\" {:point (js/parseInt (subs w 1))}\n \"^\" {:beat (js/parseFloat (subs w 1))})))\n distinct vec))\n\n(defn message\n \"A message: who says it (id: this session; who: this browser, which lasts), what, and when (shared ms).\"\n [{:keys [id who name]} text t]\n (let [text (str/trim (str text))]\n (when (seq text)\n {:kind :message :id (str who \"-\" (js/Math.round t) \"-\" (rand-int 1e6)) :author who :peer id :name name\n :text (subs text 0 (min 2000 (count text))) :t t :anchors (anchors text)})))\n\n;; ───────── keeping, and asking ─────────\n;; keep: what this page does when someone here wants to keep `item`:\n;; [:keep] it is theirs: kept now\n;; [:ask peer] someone else's, and they are in the room: ask them\n;; [:gone] someone else's, and they have left: it cannot be kept (their consent can't be asked)\n\n(defn keep-step\n [me item peers-in-room]\n (cond\n (= (:who me) (:author item)) [:keep]\n (contains? (set peers-in-room) (:peer item)) [:ask (:peer item)]\n :else [:gone]))\n\n(defn kept\n \"A kept item as the work keeps it: what it is, who made it, who kept it, and only what lasts.\"\n [item keeper t]\n (cond-> {:kind (:kind item) :author (:author item) :name (:name item) :kept-by (:who keeper) :at t}\n (= :message (:kind item)) (assoc :text (:text item) :anchors (:anchors item))\n (= :note (:kind item)) (assoc :sound (:sound item) :dur (:dur item))\n (= :frame (:kind item)) (assoc :image (:image item))))\n\n;; ───────── pieces: a voice note, a frame, over a data channel ─────────\n;; A note travels as base64 pieces small enough for any data channel (and for the relay when there is no\n;; channel), each with the hash of the whole, so the receiver knows when it has it all and that it is\n;; the same.\n\n(def piece-size 12000)\n\n(defn pieces\n \"A base64 string in pieces: [{:hash h :i 0 :n k :data …} …].\"\n [h b64]\n (let [n (max 1 (js/Math.ceil (/ (count b64) piece-size)))]\n (vec (for [i (range n)] {:hash h :i i :n n :data (subs b64 (* i piece-size) (min (count b64) (* (inc i) piece-size)))}))))\n\n(defn gather\n \"Pieces received so far ({hash → {i data}}) with one more: [new state, the whole base64 when complete].\"\n [st {:keys [hash i n data]}]\n (let [got (assoc (get st hash {}) i data)]\n (if (= n (count got))\n [(dissoc st hash) (apply str (map got (range n)))]\n [(assoc st hash got) nil])))\n\n;; ───────── the clock ─────────\n;; Every page asks the relay for its time (ping → pong): sent at t0, the relay's time ts, back at t1 (ms).\n;; The relay is ahead of the page by ts − (t0 + t1)/2, give or take half the round trip; of the last\n;; samples, the median of the third with the shortest trips. Adding it to this page's time gives the\n;; shared time, whatever each machine's clock says.\n\n(def clock-keep 24)\n\n(defn new-clock [] {:samples []})\n\n(defn clock-sample\n \"The clock with one more sample (t0 sent, ts the relay's time, t1 back, ms).\"\n [c t0 ts t1]\n (let [rtt (- t1 t0)]\n (if (neg? rtt)\n c\n (update c :samples (fn [ss] (vec (take-last clock-keep (conj ss {:rtt rtt :offset (- ts (/ (+ t0 t1) 2))}))))))))\n\n(defn- median [xs] (let [v (vec (sort xs)) n (count v)]\n (when (pos? n) (if (odd? n) (v (quot n 2)) (/ (+ (v (dec (quot n 2))) (v (quot n 2))) 2)))))\n\n(defn clock-offset\n \"The relay's time minus this page's, in ms (nil before any sample).\"\n [c]\n (let [ss (sort-by :rtt (:samples c))]\n (median (map :offset (take (max 1 (js/Math.ceil (/ (count ss) 3))) ss)))))\n\n(defn clock-error \"Half the shortest round trip: how far off the offset can be, in ms.\" [c]\n (when (seq (:samples c)) (/ (apply min (map :rtt (:samples c))) 2)))\n\n(defn shared-time \"This page's time (ms) as shared time, or nil before any sample.\" [c local] (when-let [o (clock-offset c)] (+ local o)))\n","kairotic/tempo.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · tempo\n;; Played time as beats (issue #106). Notes played live are in seconds (or in beats at a tempo nobody chose:\n;; transcribe writes them at 60 bpm), at an unknown tempo that moves. Before they can be quantized, their\n;; time has to be mapped onto the beats of the music:\n;; 1. the tempo: the period between beats that explains most intervals between onsets (each onset weighs\n;; as much as the note it starts lasts), with a mild preference for moderate tempos;\n;; 2. the beats: a dynamic programme over a grid of time (after Ellis 2007, \"Beat tracking by dynamic\n;; programming\"): each beat sits where onsets are, and the gap to the one before stays close to the\n;; period, so the beat can follow a tempo that speeds up or slows down;\n;; 3. the bar: which beat is the first of the bar, by where the weight of the notes falls (a pickup when\n;; the first beat is not a downbeat);\n;; 4. the time map: [[time beat] …] (beats as kairotic.mt counts them, a quarter = 1), linear between its\n;; points and beyond them. quantize uses it with the option :time (:track, or the map itself, kept).\n;; Pure functions on numbers: no audio, no state.\n\n(ns kairotic.tempo\n (:require [kairotic.mt :as mt]))\n\n(defn- sq [x] (* x x))\n(defn- log2 [x] (/ (js/Math.log x) js/Math.LN2))\n\n(def defaults\n \"The settings of the tracker: :prior the most likely beat period (units of the input: seconds at 60) and\n how wide its preference is (octaves); :tight how much the beat resists changing its period; :chord how\n close two onsets are to be one.\"\n {:prior 0.6 :width 1.2 :tight 25 :chord 0.05 :weigh :note :last 0 :accent true :bass false})\n\n(defn- accent-of\n \"How strong a note's attack was, 0 … 1: its :vel (0 … 1, or a MIDI velocity), or nil when it does not say.\"\n [n]\n (when-let [v (or (:vel n) (get-in n [:attrs :vel]))]\n (when (number? v) (max 0 (min 1 (if (> v 1) (/ v 127) v))))))\n\n(defn onsets\n \"Notes ({:on :off}, and their :attrs) as weighted onsets [{:t :w}], in order: onsets closer than :chord are\n one; each weighs the notes it starts, longer notes more (a note of 1 unit about 1, one of a tenth about 0.4);\n with :accent, a note played louder more (its :vel, issue #106: the strength of the attack is what places\n the beat and the bar best); with :bass, a low note more.\"\n [notes {:keys [chord accent bass]}]\n (let [ns (sort-by :on (filter (fn [n] (and (number? (:on n)) (number? (:off n)))) notes))\n w (fn [n] (* (max 0.3 (min 2 (log2 (+ 1 (* 2 (max 0 (- (:off n) (:on n))))))))\n (if-let [a (and accent (accent-of n))] (+ 0.25 (* 1.5 a)) 1)\n (if-let [p (and bass (mt/midi-of (:attrs n)))] (+ 1 (/ (max 0 (- 64 p)) 24)) 1)))]\n (reduce (fn [acc n]\n (let [lst (peek acc)]\n (if (and lst (< (- (:on n) (:t lst)) chord))\n (conj (pop acc) (update lst :w + (* 0.5 (w n))))\n (conj acc {:t (:on n) :w (w n)}))))\n [] ns)))\n\n(defn period-score\n \"How well a beat period P explains the intervals between the onsets: each pair of onsets up to 4 periods\n apart adds the product of their weights when their distance is a whole number of periods (a Gaussian of\n the deviation, 6 % of the period wide).\"\n [os P]\n (let [v (vec os) n (count v)]\n (loop [i 0 acc 0]\n (if (>= i n)\n acc\n (let [{ti :t wi :w} (v i)\n acc (loop [j (inc i) acc acc]\n (if (>= j n)\n acc\n (let [{tj :t wj :w} (v j) x (/ (- tj ti) P)]\n (if (> x 4.5)\n acc\n (let [k (js/Math.round x)]\n (recur (inc j) (if (>= k 1) (+ acc (* wi wj (js/Math.exp (/ (- (sq (- x k))) (* 2 (sq 0.06)))))) acc)))))))]\n (recur (inc i) acc))))))\n\n(defn period\n \"The beat period of weighted onsets: the best of the periods from 0.2 to 2.5 units (1 % apart), by\n period-score times a preference for periods near :prior (a Gaussian in octaves, :width wide). nil with\n fewer than 3 onsets.\"\n [os {:keys [prior width]}]\n (when (>= (count os) 3)\n (let [ps (take-while (fn [p] (<= p 2.5)) (iterate (fn [p] (* p 1.01)) 0.2))\n sc (fn [p] (* (period-score os p) (js/Math.exp (/ (- (sq (log2 (/ p prior)))) (* 2 (sq width))))))]\n (apply max-key sc ps))))\n\n(defn track\n \"The beats of weighted onsets with period P: their times, in order (after Ellis 2007). Time is a grid of\n P/40; each point of it scores the onsets near it (a Gaussian 4 % of P wide), and a beat there adds its\n score to the best beat before it, 0.66 to 1.5 periods back, less :tight × (log of the gap over P)². The\n first beat is within 1.5 periods of the first onset; the last near the last onset.\"\n [os P {:keys [tight]}]\n (when (and P (seq os))\n (let [dt (/ P 40) t0 (- (:t (first os)) (* 0.25 P)) t1 (+ (:t (peek (vec os))) (* 0.25 P))\n n (inc (js/Math.ceil (/ (- t1 t0) dt)))\n sig (* 0.04 P) reach (js/Math.ceil (/ (* 4 sig) dt))\n env (let [a (make-array n)]\n (dotimes [k n] (aset a k 0))\n (doseq [{:keys [t w]} os\n :let [c (js/Math.round (/ (- t t0) dt))]\n k (range (max 0 (- c reach)) (min n (+ c reach 1)))]\n (aset a k (+ (aget a k) (* w (js/Math.exp (/ (- (sq (- (+ t0 (* k dt)) t))) (* 2 (sq sig))))))))\n a)\n lo (js/Math.round (/ (* 0.66 P) dt)) hi (js/Math.round (/ (* 1.5 P) dt))\n start (js/Math.round (/ (* 1.5 P) dt))\n C (make-array n) prev (make-array n)]\n (dotimes [k n]\n (let [[bj bc] (loop [j (- k lo) bj -1 bc (- js/Infinity)]\n (if (or (< j 0) (< j (- k hi)))\n [bj bc]\n (let [c (- (aget C j) (* tight (sq (js/Math.log (/ (* (- k j) dt) P)))))]\n (if (> c bc) (recur (dec j) j c) (recur (dec j) bj bc)))))\n fresh (when (< k start) 0)\n [bj bc] (if (and fresh (or (< bj 0) (> fresh bc))) [-1 fresh] [bj bc])]\n (aset C k (+ (aget env k) (if (< bj 0) (or fresh (- js/Infinity)) bc)))\n (aset prev k bj)))\n ;; the last beat: the best point near the last onset\n (let [kend (dec n) from (max 0 (- kend (js/Math.round (/ (* 0.75 P) dt))))\n k* (apply max-key (fn [k] (aget C k)) (range from (inc kend)))]\n (loop [k k* out ()]\n (if (< k 0) (vec out) (recur (aget prev k) (cons (+ t0 (* k dt)) out))))))))\n\n(defn phase-weights\n \"For each of the m phases (which of the first m beats is a downbeat), the share of the notes' weight that\n falls on its downbeats (0 … 1): see bar-phase.\"\n [os beats m]\n (if (or (< m 2) (< (count beats) m))\n (vec (repeat (max 1 m) (/ 1 (max 1 m))))\n (let [v (vec os) bv (vec beats)\n P (/ (- (peek bv) (first bv)) (max 1 (dec (count bv))))\n s (mapv (fn [b] (reduce + (keep (fn [o] (when (< (js/Math.abs (- (:t o) b)) (* 0.15 P)) (:w o))) v))) bv)\n total (max 1e-9 (reduce + s))]\n (mapv (fn [k] (/ (reduce + (map-indexed (fn [i x] (if (= k (mod i m)) x 0)) s)) total)) (range m)))))\n\n(defn bar-phase\n \"Which of the first m beats is a downbeat (0 … m-1): the one whose beats every m weigh most. A beat weighs\n the onsets near it: by the time to the next onset (:weigh :ioi, long notes fall on strong beats) or by the\n note's own weight (:weigh :note); with :last, the beat the last note starts on weighs that share of the\n total more (a piece ends on a downbeat more often than not).\"\n ([os beats m] (bar-phase os beats m {}))\n ([os beats m {:keys [weigh last] :or {weigh :ioi last 0}}]\n (if (or (< m 2) (< (count beats) m))\n 0\n (let [v (vec os) bv (vec beats)\n P (/ (- (peek bv) (first bv)) (max 1 (dec (count bv))))\n wt (if (= weigh :note)\n (mapv :w v)\n (mapv (fn [i] (min (* 2 P) (if (< (inc i) (count v)) (- (:t (v (inc i))) (:t (v i))) (* 2 P)))) (range (count v))))\n s (mapv (fn [b] (reduce + (keep-indexed (fn [i o] (when (< (js/Math.abs (- (:t o) b)) (* 0.15 P)) (wt i))) v))) bv)\n lastb (apply min-key (fn [i] (js/Math.abs (- (bv i) (:t (peek v))))) (range (count bv)))\n total (reduce + s)]\n (apply max-key (fn [k] (+ (reduce + (map-indexed (fn [i x] (if (= k (mod i m)) x 0)) s))\n (if (= k (mod lastb m)) (* last total) 0)\n (if (zero? k) 0.01 0)))\n (range m))))))\n\n(defn tactus\n \"The beat a meter is felt in, in quarters, and how many of them make a bar: 4/4 → [1 4], 3/4 → [1 3],\n 6/8 → [1.5 2], 9/8 → [1.5 3], 2/2 → [2 2], 5/8 [2+3] and other meters in eighths → [0.5 5].\"\n [meter]\n (let [{[p q] :meter} (mt/meter-of meter) u (/ 4 q) bl (* p u)]\n (cond (and (= q 8) (zero? (mod p 3)) (> p 3)) [1.5 (/ p 3)]\n (>= q 8) [u p]\n :else [u p])))\n\n(defn beats-of\n \"The beats found in notes played freely ({:on :off}): {:os the weighted onsets :period :beats [times]}, or\n nil when there are too few onsets.\"\n [notes opts]\n (let [o (merge defaults opts)\n os (onsets notes o)\n P (period os o)\n beats (track os P o)]\n (when (>= (count beats) 2) {:os os :period P :beats beats})))\n\n(defn map-of\n \"A time map from beats found: each worth u quarters, m of them to a bar, the k-th the first downbeat (the\n ones before it a pickup, at the end of a first bar).\"\n [beats u m k]\n (mapv (fn [i t] [(/ (js/Math.round (* t 1e4)) 1e4) (+ (* (- i k) u) (if (pos? k) (* u m) 0))]) (range) beats))\n\n(defn time-map\n \"The time map of notes played freely ({:on :off}, in units: seconds at 60): [[time beat] …], one point\n per beat found, beats counted as kairotic.mt does (a quarter = 1) in the meter given, with a pickup bar\n when the first beat found is not a downbeat. nil when there is too little to find a beat in.\n opts: those of `defaults`, and :meter.\"\n ([notes] (time-map notes {}))\n ([notes opts]\n (let [o (merge defaults opts)\n os (onsets notes o)\n P (period os o)\n beats (track os P o)]\n (when (>= (count beats) 2)\n (let [[u m] (tactus (or (:meter o) [4 4]))\n k (bar-phase os beats m (select-keys o [:weigh :last]))\n bl (* u m)]\n (mapv (fn [i t] [(/ (js/Math.round (* t 1e4)) 1e4) (+ (* (- i k) u) (if (pos? k) bl 0))]) (range) beats))))))\n\n(defn sane-map\n \"A time map as kept in options: at least two points [time beat], both increasing; else nil.\"\n [m]\n (when (and (sequential? m) (>= (count m) 2)\n (every? (fn [p] (and (sequential? p) (= 2 (count p)) (every? number? p))) m))\n (let [m (vec (sort-by first (map vec m)))]\n (when (every? (fn [[[a x] [b y]]] (and (< a b) (< x y))) (partition 2 1 m)) m))))\n\n(defn ->beat\n \"A time as a beat, through a time map: linear between its points, and beyond them at the period of the\n nearest two.\"\n [m t]\n (let [v (vec m) n (count v)\n i (loop [i 0] (if (and (< i (- n 2)) (>= t (first (v (inc i))))) (recur (inc i)) i))\n [[a x] [b y]] [(v i) (v (inc i))]]\n (+ x (* (- t a) (/ (- y x) (- b a))))))\n\n(defn ->time\n \"A beat as a time, through a time map (the inverse of ->beat): linear between its points and beyond them.\"\n [m b]\n (->beat (mapv (fn [[t x]] [x t]) m) b))\n\n(defn tempo-of-map\n \"The tempo a time map stands for, in beats per minute of its units (60 units a minute): the median of the\n tempos between its points.\"\n [m]\n (let [ts (sort (map (fn [[[a x] [b y]]] (* 60 (/ (- y x) (- b a)))) (partition 2 1 m)))]\n (when (seq ts) (nth ts (quot (count ts) 2)))))\n\n(defn map-notes\n \"Notes ({:on :off …}) with their times mapped through a time map, onto beats.\"\n [notes m]\n (mapv (fn [n] (assoc n :on (->beat m (:on n)) :off (->beat m (:off n)))) notes))\n","kairotic/treecanvas.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · treecanvas\n;; A tree box seen and drawn as a canvas (discussion #92): the tree is the data, the canvas one more view\n;; of it, as the score and the code are. Its notes are strokes of frequency over time (each with an id\n;; that leads back to where the note is written), and what is drawn on the canvas becomes edits of the\n;; tree (kairotic.mt/apply-op), so the history stays a history of the tree.\n;;\n;; · A tree without measures is free time: drawing adds a note placed with :at, dragging moves it,\n;; erasing removes it. A free tree is kept as [:voice {…} [:par [:note {:at t :dur d :pitch p} …]]];\n;; one written otherwise (a melody string, a sequence) takes that form the first time a note's time\n;; changes (a change of pitch alone is written where the note is).\n;; · A tree with measures stays measured: a change of pitch alone is written in the note; a change of\n;; time re-quantizes the bars it touches (kairotic.quantize, in that bar's meter); with ⌥ a note leaves\n;; the measures for a free voice of the tree ({:name \"free\"}), as a stroke drawn freehand does.\n;; · Its grid and tuning are attributes of the tree's root: {:grid {:step 0.25 :cycles [4]} :tuning {…}};\n;; a measured tree without :grid shows its bars, each in its own meter, and a tree without :tuning is drawn in semitones\n;; (12-tet; :tuning false is continuous frequency).\n\n(ns kairotic.treecanvas\n (:require [kairotic.canvas :as cv]\n [kairotic.mt :as mt]\n [kairotic.quantize :as qz]))\n\n(def eps 1e-6)\n\n;; ───────── the view ─────────\n\n(defn- note-events [x] (filterv (fn [e] (= :note (:kind e))) (mt/events x)))\n\n(defn- pts-of\n \"The points of a note as a stroke: [t hz], its :gliss bending it.\"\n [e]\n (let [t0 (:t e) d (max 0.01 (:dur e)) hz (cv/midi->hz (:pitch e))\n g (let [g (:gliss e)] (if (and (sequential? g) (>= (count g) 2)) g [[0 0] [1 0]]))]\n (mapv (fn [[x c]] [(cv/round-to (+ t0 (* d x)) 4) (cv/round-to (cv/cents->hz c hz) 3)]) g)))\n\n(defn- grid-of\n \"The canvas grid of a tree: its root's :grid, else the bars of its measures (of its first voice), each in\n its own meter (:bars, when they change), else none.\"\n [x]\n (or (cv/sane-gx (:grid (mt/attrs x)))\n (let [ms (mt/measures-of (first (mt/voices-of (mt/with-meters x))))\n bar (fn [m] (let [{[p q] :meter g :groups} (mt/meter-of m) u (/ 4 q)]\n {:L (* p u) :u u :groups (when (seq g) (mapv (fn [k] (* k u)) g))}))\n bs (mapv bar ms)]\n (when-let [b0 (first bs)]\n (cond-> {:step (min 0.25 (reduce min (map :u bs))) :cycles (or (:groups b0) [(:L b0)])}\n (some (fn [b] (not= (dissoc b :u) (dissoc b0 :u))) bs)\n (assoc :bars (mapv (fn [s b] {:s s :L (:L b) :groups (:groups b)}) (reductions + 0 (map :L bs)) bs)))))))\n\n(defn view-data\n \"A tree as the data of a freqt-like canvas: {:strokes {:n1 {:pts …}} :gx :gy :ids {:n1 {…}}}, where :ids\n says for each stroke the note it is: its place in the expanded tree (:path), where it is written\n (:src :sub, or :rtm/:use when it is not written as a note), its voice, start, duration and pitch.\"\n [tree]\n (let [x (mt/expand-source (or tree [:voice]) nil)\n evs (note-events x)\n ids (into {} (map-indexed (fn [i e]\n (let [n (mt/node-at x (:path e)) m (meta n)]\n [(keyword (str \"n\" (inc i)))\n {:path (:path e) :src (:src m) :sub (:sub m) :rtm (:rtm m) :use (:use m)\n :voice (:voice e) :t (:t e) :dur (:dur e) :pitch (:pitch e)\n :attrs (mt/attrs n)}]))\n evs))]\n {:strokes (into {} (map-indexed (fn [i e] [(keyword (str \"n\" (inc i))) {:pts (pts-of e)}]) evs))\n :gx (grid-of x)\n ;; a tree is written in semitones unless it says otherwise: 12-tet, its :tuning, or false (continuous)\n :gy (let [a (mt/attrs x)]\n (if (contains? a :tuning) (cv/sane-gy (:tuning a)) (assoc (get cv/tunings \"12-tet\") :ref cv/default-ref)))\n :ids ids}))\n\n;; ───────── strokes → notes ─────────\n\n(defn- note-of-pts\n \"The note a stroke is: placed at its first point, as long as it lasts, at the pitch of its first point\n (a name kept as it was when it still fits, see mt/set-midi), its bends a :gliss. was: the attributes the\n note had (its marks are kept).\"\n [pts was]\n (let [[t0 f0] (first pts) [t1 _] (peek pts)\n m (cv/hz->midi f0) mr (js/Math.round m)\n dur (max 0.01 (- t1 t0))\n g (mapv (fn [[t f]] [(cv/round-to (/ (- t t0) dur) 3) (+ 0 (cv/round-to (cv/hz->cents f (cv/midi->hz mr)) 1))]) pts)\n flat? (every? (fn [[_ c]] (< (js/Math.abs (- c (second (first g)))) 1)) g)\n exact (if (< (js/Math.abs (- m mr)) 0.02) mr (cv/round-to m 2))\n base (dissoc (or was {}) :gliss :at :dur :tie :grace)\n a (if (some? (:pitch base)) (mt/set-midi base (if flat? exact mr)) (assoc base :pitch (if flat? exact mr)))]\n (cond-> (assoc (dissoc a :hz) :at (cv/round-to t0 4) :dur (cv/round-to dur 4))\n (not flat?) (assoc :gliss g))))\n\n(defn free-form\n \"A tree as free time: [:voice {its root's attributes} [:par [:note {:at …}] …]], every note placed where\n it sounds (ties joined), with the name it was written with.\"\n [tree]\n (let [x (mt/expand tree)\n root (dissoc (mt/attrs x) :at :dur)\n notes (for [e (note-events x)]\n (let [a (mt/attrs (mt/node-at x (:path e)))]\n [:note (cond-> (merge (select-keys a [:art :dyn :text :vel :env :gliss :cents :id :grace])\n {:at (cv/round-to (:t e) 4) :dur (cv/round-to (:dur e) 4)\n :pitch (if (mt/spelling-of a) (:pitch a) (:pitch e))})\n (number? (:hz a)) (-> (dissoc :pitch) (assoc :hz (:hz a))))]))]\n [:voice (dissoc root :meter :groups) (into [:par] notes)]))\n\n(defn- canonical-free?\n \"Is a tree written as free-form writes it (so that a note's path is [0 i])?\"\n [tree]\n (and (mt/node? tree) (= :voice (mt/tag tree)) (= 1 (count (mt/kids tree)))\n (let [p (first (mt/kids tree))]\n (and (mt/node? p) (= :par (mt/tag p))\n (every? (fn [k] (and (mt/node? k) (= :note (mt/tag k)) (number? (:at (mt/attrs k))))) (mt/kids p))))))\n\n;; ───────── where a note is written ─────────\n\n(defn writable\n \"Edits that make a written note editable (a melody string becomes its nodes) and the path of the note:\n [ops path], or nil when it comes from a fragment (:defs) or a proportional rhythm (:rtm).\"\n [t {:keys [src sub use rtm]}]\n (cond\n (or use rtm (nil? src)) nil\n (nil? sub) [[] src]\n :else (let [s (mt/node-at t src) nodes (mt/melody s) parent (pop src) idx (peek src)]\n [(into [[:remove src]] (map-indexed (fn [k n] [:insert (conj parent (+ idx k)) n]) nodes))\n (into (conj parent (+ idx (first sub))) (rest sub))])))\n\n(defn- not-written [info]\n (throw (js/Error. (if (:rtm info)\n \"That note comes from a proportional rhythm (:rtm): edit its :shares or :pitches\"\n \"That note comes from a fragment (:defs): edit the fragment, or write it out\"))))\n\n;; ───────── measured trees: re-quantizing the bars a change touches ─────────\n\n(defn- voice-nodes\n \"The :voice nodes of x with the name mt/events gives their notes (:name, :id, or v<depth>-<index>), or\n the whole tree as one voice (named nil) when it has none.\"\n [x]\n (let [found (atom [])]\n (letfn [(go [n path]\n (when (mt/node? n)\n (if (= :voice (mt/tag n))\n (swap! found conj [(or (:name (mt/attrs n)) (:id (mt/attrs n)) (str \"v\" (count path) \"-\" (last path))) n])\n (doseq [[i k] (map-indexed vector (mt/kids n))] (go k (conj path i))))))]\n (go x []))\n (if (seq @found) @found [[nil x]])))\n\n(defn- bars-of\n \"The measures of each voice of the expanded tree x: {voice [{:src :start :len :attrs :meter} …]}.\"\n [x]\n (let [x (mt/with-meters x)]\n (into {} (for [[k v] (voice-nodes x)\n :let [ms (mt/measures-of v)\n lens (map (fn [m] (let [[p q] (:meter (mt/attrs m))] (* p (/ 4 q)))) ms)]]\n [k (mapv (fn [m s l] {:src (:src (meta m)) :use (:use (meta m)) :start s :len l :attrs (mt/attrs m)\n :meter (select-keys (mt/attrs m) [:meter :groups])})\n ms (reductions + 0 lens) lens)]))))\n\n(defn- voice-key\n \"The key bars-of uses for an event's voice.\"\n [bars e]\n (if (contains? bars (:voice e)) (:voice e) (first (keys bars))))\n\n(defn- requantize-bar\n \"The new children of one measure (start s, length L, its meter) for these notes in free time\n ({:on :off :attrs}, beats): each one clipped to the bar, and tied (:tie) when it goes on past it.\"\n [notes {:keys [start len meter]}]\n (let [end (+ start len)\n inside (for [n notes :let [on (max (:on n) start) off (min (:off n) end)] :when (> off (+ on eps))]\n {:on (- on start) :off (- off start)\n :attrs (cond-> (:attrs n) (> (:off n) (+ end eps)) (assoc :tie true))})\n v (qz/notes->voice (vec inside) (qz/options {:meter meter :voices 1 :legato 0} nil))\n m (first (filter (fn [k] (and (mt/node? k) (= :measure (mt/tag k)))) (mt/kids v)))]\n (vec (mt/kids m))))\n\n(defn- measured-ops\n \"Ops that re-quantize, in the voice vk, the bars a change touches: the notes of that voice (as they\n sound) with `change` applied (a function of that list of notes), written again in every bar that\n touches [t0, t1].\"\n [x bars vk change t0 t1]\n (let [bs (get bars vk)\n evs (filter (fn [e] (= (voice-key bars e) vk)) (note-events x))\n notes (change (mapv (fn [e] (let [a (mt/attrs (mt/node-at x (:path e)))]\n {:path (:path e) :on (:t e) :off (+ (:t e) (:dur e))\n :attrs (merge (select-keys a [:art :dyn :text :vel :env :gliss :cents :id])\n {:pitch (if-let [s (mt/spelling-of a)] (:pitch a) (:pitch e))})}))\n evs))\n touched (filter (fn [b] (and (< (:start b) (- t1 eps)) (> (+ (:start b) (:len b)) (+ t0 eps)))) bs)\n touched (if (seq touched) touched (take-last 1 bs))]\n (when (some (fn [b] (or (:use b) (nil? (:src b)))) touched)\n (throw (js/Error. \"Those bars come from a fragment (:defs): write them out to edit them\")))\n (vec (for [b touched]\n [:set (:src b) (into [:measure (:attrs b)] (requantize-bar notes b))]))))\n\n(defn- free-voice-ops\n \"Ops that put a note in the free voice of a measured tree ({:name \\\"free\\\"}), making it when there is none.\"\n [tree note]\n (let [free-i (when (= :par (mt/tag tree))\n (first (keep-indexed (fn [i k] (when (and (mt/node? k) (= :voice (mt/tag k)) (= \"free\" (:name (mt/attrs k)))) i))\n (mt/kids tree))))]\n (if free-i\n (let [v (nth (mt/kids tree) free-i) p (first (mt/kids v))]\n (if (and (mt/node? p) (= :par (mt/tag p)))\n [[:insert [free-i 0 (count (mt/kids p))] note]]\n [[:insert [free-i (count (mt/kids v))] note]]))\n [[:set [] [:par (if (= :par (mt/tag tree)) (into [:par (mt/attrs tree)] (mt/kids tree)) tree)\n [:voice {:name \"free\"} [:par note]]]]])))\n\n;; ───────── canvas events → tree edits ─────────\n\n(defn- root-attrs-op [tree f] [:attrs [] (f (mt/attrs tree))])\n\n(defn edit-ops\n \"The edits of the tree (mt/apply-op operations) that make a canvas event on its view: [:stroke id pts]\n (a new id draws a note), [:move id dt cents], [:stretch id k], [:erase id], [:clear], [:grid-x gx],\n [:tuning gy] or [:batch [events]]. opts: {:free true} takes a note of a measured tree out of the\n measures (⌥). Throws, saying why, for a note that is not written as one (:defs, :rtm).\"\n ([tree ev] (edit-ops tree ev {}))\n ([tree [op & args :as ev] opts]\n (let [tree (or tree [:voice [:par]])]\n (case op\n :batch (loop [t tree evs (filter vector? (first args)) out []]\n (if (empty? evs)\n out\n (let [ops (edit-ops t (first evs) opts)]\n (recur (reduce mt/apply-op t ops) (rest evs) (into out ops)))))\n :grid-x [(root-attrs-op tree (fn [a] (if-let [g (cv/sane-gx (first args))] (assoc a :grid g) (dissoc a :grid))))]\n (:tuning :grid-y) [(root-attrs-op tree (fn [a] (if-let [g (cv/sane-gy (first args))] (assoc a :tuning g) (assoc a :tuning false))))]\n :clear [[:set [] [:voice (dissoc (mt/attrs tree) :meter :groups) [:par]]]]\n (:stroke :move :stretch :erase)\n (let [v (view-data tree)\n v2 (cv/step (dissoc v :ids) ev)\n sid (if (and (= op :stroke) (keyword? (first args))) (first args) (first args))\n old (get-in v [:strokes sid :pts])\n new (get-in v2 [:strokes sid :pts])\n new (if (and (= op :stroke) (not (keyword? (first args)))) (cv/sane-pts (first args)) new)\n info (get-in v [:ids sid])\n measured? (mt/measured? tree)]\n (cond\n (and (not= op :stroke) (nil? info)) []\n (and (= op :stroke) (nil? new)) []\n ;; a new note\n (nil? old)\n (let [note [:note (note-of-pts new nil)]]\n (cond\n (and measured? (:free opts)) (free-voice-ops tree note)\n measured?\n (let [x (mt/expand-source tree nil) bars (bars-of x)\n a (mt/attrs note) on (:at a) off (+ (:at a) (:dur a))\n ;; the voice whose notes are nearest in pitch around there\n evs (note-events x)\n near (filter (fn [e] (< (js/Math.abs (- (:t e) on)) 8)) evs)\n vk (if (seq near)\n (voice-key bars (apply min-key (fn [e] (js/Math.abs (- (:pitch e) (mt/midi-of a)))) near))\n (first (keys bars)))]\n (measured-ops x bars vk (fn [ns] (conj ns {:on on :off off :attrs (dissoc a :at :dur)})) on off))\n (canonical-free? tree) [[:insert [0 (count (mt/kids (first (mt/kids tree))))] note]]\n :else (let [f (free-form tree)] (into [[:set [] f]] (edit-ops f ev opts)))))\n ;; erased\n (nil? new)\n (cond\n ;; in measures, an erased note leaves a rest as long (or leaves its chord)\n measured?\n (let [[pre target] (or (writable tree info) (not-written info))\n t1 (reduce mt/apply-op tree pre)\n n (mt/node-at t1 target)\n in-chord? (= :chord (mt/tag (mt/node-at t1 (pop target))))\n d (or (:dur (mt/attrs n)) (:dur (mt/attrs (mt/node-at (mt/explicit t1) target))) 1)]\n (conj pre (if in-chord? [:remove target] [:set target [:rest {:dur d}]])))\n (canonical-free? tree) [[:remove (:src info)]]\n :else (let [[pre target] (or (writable tree info) (not-written info))]\n (conj pre [:remove target])))\n ;; changed\n :else\n (let [[a0 _] (first old) [a1 _] (peek old) [b0 _] (first new) [b1 _] (peek new)\n same-time? (and (< (js/Math.abs (- a0 b0)) 1e-3) (< (js/Math.abs (- a1 b1)) 1e-3))\n was (:attrs info)\n changed (note-of-pts new was)]\n (cond\n ;; a change of pitch alone: in the note, wherever it is written\n (and same-time? (not (:free opts)))\n (let [[pre target] (or (writable tree info) (not-written info))\n n (mt/node-at (reduce mt/apply-op tree pre) target)]\n (conj pre [:attrs target (cond-> (merge (dissoc (mt/attrs n) :cents :hz :pitch) (dissoc changed :at :dur))\n (not (:gliss changed)) (dissoc :gliss))]))\n (and measured? (:free opts))\n (let [x (mt/expand-source tree nil) bars (bars-of x)\n out (measured-ops x bars (voice-key bars {:voice (:voice info)})\n (fn [ns] (vec (remove (fn [n] (= (:path n) (:path info))) ns)))\n (:t info) (+ (:t info) (:dur info)))\n t2 (reduce mt/apply-op tree out)]\n (into out (free-voice-ops t2 [:note changed])))\n measured?\n (let [x (mt/expand-source tree nil) bars (bars-of x)\n a changed]\n (measured-ops x bars (voice-key bars {:voice (:voice info)})\n (fn [ns] (conj (vec (remove (fn [n] (= (:path n) (:path info))) ns))\n {:on (:at a) :off (+ (:at a) (:dur a)) :attrs (dissoc a :at :dur)}))\n (min (:t info) (:at a)) (max (+ (:t info) (:dur info)) (+ (:at a) (:dur a)))))\n (canonical-free? tree) [[:set (:src info) [:note (merge (dissoc was :gliss) changed)]]]\n :else (let [f (free-form tree)] (into [[:set [] f]] (edit-ops f ev opts)))))))\n []))))\n","page/00-work.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 1 of 12: work\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(ns user (:require [clojure.string :as str] [clojure.set] [kairotic.score :as sc] [kairotic.canvas :as cv]\n [kairotic.components :as comp] [kairotic.api :as api] [kairotic.code :as cbox] [kairotic.faust] [kairotic.library :as lib] [kairotic.help :as hlp] [kairotic.mt :as mt] [kairotic.quantize :as qz] [kairotic.tempo :as tm] [kairotic.spell :as sp] [kairotic.treecanvas :as tc] [kairotic.mtboxes :as mtb] [kairotic.hiccup :as hic] [kairotic.assistant :as ai] [kairotic.engine :as eng] [kairotic.presets :as pst] [kairotic.release :as rel] [kairotic.sounds :as snd] [kairotic.talk :as tk]\n [kairotic.shapes :as shp] [kairotic.signal] [kairotic.links :as links] [clojure.edn]))\n\n(def version \"0.2.0-alpha\")\n\n;; kairotic.code is aliased `cbox` (not `code`) because `code` is a REPL command defined below.\n\n;; ───────────────────────── model of the work ─────────────────────────\n\n(def empty-patch {:boxes (sorted-map) :lines []})\n\n;; Box classes are components registered in kairotic.components: their ports, their view,\n;; their data with its own history, their behaviour with messages and their audio all come from there.\n\n(declare open-work-file! view-instances inline-lines on-lines render-lines! line-name switch-line! check-ref-text! ref-badge ref-warning resolve-ref refs-in followed-fronts open-ref es? docs open-work! show-help! refresh-help! tsel-piece-id refill-data! forget-box! update-trust-bar! render-askbar! present-what! url-with copy-text!) ; the Help tab (Study 18), defined further down\n(def klass comp/klass)\n(defn box-def [b] (comp/lookup (klass (:text b))))\n;; how a box is shown: the view it chose among those of its class (a tree as a score or a roll, a freqt\n;; as a canvas or a score: discussion #30), or the :display of its class\n(defn display-of \"How a box is drawn (a tree's roll is drawn as a canvas).\" [b] (comp/drawn-as b))\n(defn view-of \"The view a box is shown in, by its name (:score, :roll, :canvas…).\" [b] (comp/shown-as b))\n(def own-view? comp/own-view?)\n\n(defn io\n \"Inlets and outlets of a box (or of a bare text).\"\n [b] (comp/io (if (string? b) {:text b} b)))\n\n;; boxes with a graphic buffer inside: score is another view of the same buffer\n(def music-classes #{\"canvas\" \"freqt\"})\n;; boxes that act when pressed (they are moved by their left grip)\n(def action-classes #{\"number\" \"msg\" \"bang\"})\n(def kairos-classes #{\"state\" \"transition\" \"instruction\" \"region\"})\n\n(defn prune-lines\n \"Removes the lines that no longer fit the ports of their boxes. Boxes with computed ports\n (such as faust~, which depends on its compilation) are not pruned: so the history does not depend\n on when each tab finished compiling.\"\n [p]\n (let [bx (:boxes p)\n ok? (fn [[a o b i]]\n (and (contains? bx a) (contains? bx b)\n (or (comp/dynamic? (get bx a)) (< o (second (io (get bx a)))))\n (or (comp/dynamic? (get bx b)) (< i (first (io (get bx b)))))))]\n (update p :lines (fn [ls] (vec (filter ok? ls))))))\n\n;; ───── recipes (discussion #17) ─────\n;; A buffer filled from a tree with (keep! :bN) keeps, beside its :data, the recipe that made it:\n;; {:tree the tree as it arrived (measures, tuplets, dynamics…), :calls the boxes and lines upstream as\n;; code, :from the box it came from, :stale true once the buffer has been changed since}. The recipe is\n;; not part of the buffer: the buffer stays plain data, and the recipe says where it came from.\n\n(defn sane-recipe [r]\n (when (and (map? r) (or (vector? (:tree r)) (string? (:tree r))))\n (cond-> {:tree (:tree r)}\n (string? (:calls r)) (assoc :calls (:calls r))\n (keyword? (:from r)) (assoc :from (:from r))\n (true? (:stale r)) (assoc :stale true))))\n\n\n;; ───── layers: annotations and projections over or under the boxes (Study 26) ─────\n;; A patch can have layers, drawn over or under its boxes, in the patch view, in the presentation or in\n;; both. A layer holds marks — a line drawn by hand, an arrow, a text — whose points are anchored to a box\n;; ([:b4 dx dy], from its top-left corner: they follow it when it moves) or to the paper ([:patch x y]),\n;; and projections: the view of a box drawn again, at another size, somewhere on the paper.\n;; :layers {:notes {:z :over :show #{:patch :present}}}\n;; :marks {:a1 {:layer :notes :kind :line :pts [[:b4 -10 20] [:b7 0 -8] …]}\n;; :a2 {:layer :notes :kind :text :at [:patch 400 60] :txt \"enters the clarinet\"}}\n;; :projections {:b9 {:layer :viz :rect [x y w h]}}\n;; A mark anchored to a box that is deleted stays where it was, anchored to the paper.\n\n(def layer-default {:z :over :show #{:patch :present}})\n\n(defn sane-layer [l]\n (let [l (if (map? l) l {})\n show (set (filter #{:patch :present} (if (coll? (:show l)) (:show l) [])))]\n {:z (if (= :under (:z l)) :under :over)\n :show (if (and (coll? (:show l)) (contains? l :show)) show (:show layer-default))}))\n\n(defn sane-anchor [a]\n (when (and (sequential? a) (= 3 (count a)) (keyword? (first a)) (number? (second a)) (number? (nth a 2))\n (js/isFinite (second a)) (js/isFinite (nth a 2)))\n [(first a) (/ (js/Math.round (* 10 (second a))) 10) (/ (js/Math.round (* 10 (nth a 2))) 10)]))\n\n(defn sane-mark [m]\n (when (and (map? m) (keyword? (:layer m)))\n (case (:kind m)\n (:line :arrow) (let [ps (vec (keep sane-anchor (take 400 (:pts m))))]\n (when (>= (count ps) 2) {:layer (:layer m) :kind (:kind m) :pts (if (= :arrow (:kind m)) [(first ps) (peek ps)] ps)}))\n :text (when-let [a (sane-anchor (:at m))]\n (let [t (str (:txt m))] (when (seq t) {:layer (:layer m) :kind :text :at a :txt (subs t 0 (min 200 (count t)))})))\n ;; a small picture (a frame kept from a room's camera, #135): a data URL of an image, at most 48 KB\n :image (when-let [a (sane-anchor (:at m))]\n (let [src (str (:src m)) w (:w m) h (:h m)]\n (when (and (re-matches #\"data:image/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+\" src) (<= (count src) 48000)\n (number? w) (number? h) (< 0 w 1000) (< 0 h 1000))\n {:layer (:layer m) :kind :image :at a :src src :w (js/Math.round w) :h (js/Math.round h)})))\n nil)))\n\n(defn sane-projection [pr]\n (let [[x y w h] (:rect pr)]\n (when (and (map? pr) (keyword? (:layer pr)) (every? number? [x y w h]))\n {:layer (:layer pr) :rect [(js/Math.round x) (js/Math.round y) (max 40 (min 2400 (js/Math.round w))) (max 30 (min 2400 (js/Math.round h)))]})))\n\n(defn with-layers\n \"The layers, marks and projections of x, normalized, into patch p (only those it has).\"\n [p x]\n (let [ls (into {} (for [[k l] (:layers x) :when (keyword? k)] [k (sane-layer l)]))\n ms (into (sorted-map) (for [[k m] (:marks x) :let [m (sane-mark m)] :when (and (keyword? k) m)] [k m]))\n ps (into (sorted-map) (for [[k pr] (:projections x) :let [pr (sane-projection pr)] :when (and (keyword? k) pr)] [k pr]))]\n (cond-> p (seq ls) (assoc :layers ls) (seq ms) (assoc :marks ms) (seq ps) (assoc :projections ps))))\n\n(defn ensure-layer [p id] (if (get-in p [:layers id]) p (assoc-in p [:layers id] layer-default)))\n\n(defn unanchor\n \"The marks anchored to box id, with those points on the paper where they were (the box is going).\"\n [p id]\n (let [b (get-in p [:boxes id])\n fix (fn [[a x y :as pt]] (if (and b (= a id)) [:patch (+ (:x b) x) (+ (:y b) y)] pt))]\n (if-not (:marks p)\n p\n (update p :marks (fn [ms] (into (sorted-map) (for [[k m] ms]\n [k (cond-> m (:pts m) (update :pts (fn [ps] (mapv fix ps)))\n (:at m) (update :at fix))])))))))\n\n(defn drop-empty [p k] (if (empty? (get p k)) (dissoc p k) p))\n\n(defn shift-mark\n \"Mark m moved by dx dy: each point keeps its anchor (a box or the paper) and moves from it.\"\n [m dx dy]\n (let [f (fn [[a x y]] (sane-anchor [a (+ x dx) (+ y dy)]))]\n (cond-> m (:pts m) (update :pts (fn [ps] (mapv f ps))) (:at m) (update :at f))))\n\n(defn set-point\n \"Mark m with its point i (of a line or an arrow) anchored as a, now [anchor dx dy].\"\n [m i a]\n (if (and (:pts m) (< -1 i (count (:pts m))) (sane-anchor a)) (assoc-in m [:pts i] (sane-anchor a)) m))\n\n(defn sane-patch\n \"Events may come from other people: whatever arrives is normalized.\"\n [x]\n (if (map? x)\n (with-layers\n {:boxes (into (sorted-map)\n (for [[k b0] (:boxes x) :when (and (keyword? k) (map? b0))\n :let [b (comp/upgrade-box b0)]]\n [k (cond-> {:text (str (:text b)) :x (or (:x b) 0) :y (or (:y b) 0)}\n (and (vector? (:present b)) (= 2 (count (:present b))) (every? number? (:present b)))\n (assoc :present (:present b))\n (keyword? (:view b)) (assoc :view (:view b))\n ;; a `patch @name` pinned to a point of its line (#117)\n (and (vector? (:pin b)) (= 2 (count (:pin b))) (string? (first (:pin b))) (number? (second (:pin b))))\n (assoc :pin (:pin b))\n (and (vector? (:size b)) (= 2 (count (:size b))) (every? number? (:size b)))\n (assoc :size (:size b))\n (and (map? (:data b)) (comp/model-of b)) (assoc :data ((:load (comp/model-of b)) (:data b)))\n (sane-recipe (:recipe b)) (assoc :recipe (sane-recipe (:recipe b))))]))\n :lines (vec (filter (fn [l] (and (vector? l) (= 4 (count l)))) (:lines x)))}\n x)\n empty-patch))\n\n(defn step [p [op & args]]\n (case op\n ;; a box written with the name of a class that became a view of another one (score → freqt) is read\n ;; as that class, in that view: older works and histories keep working\n :box (let [[id text x y] args] (if (keyword? id) (assoc-in p [:boxes id] (comp/upgrade-box {:text (str text) :x x :y y})) p))\n :text (let [[id text] args]\n (if (get-in p [:boxes id])\n (prune-lines (update-in p [:boxes id] (fn [b] (comp/upgrade-box (assoc b :text (str text))))))\n p))\n :move (let [[id x y] args] (if (get-in p [:boxes id]) (update-in p [:boxes id] assoc :x x :y y) p))\n ;; where a box appears in presentation (and in the panel of the sub-patch it is in), or nil\n :present (let [[id x y] args]\n (cond (not (get-in p [:boxes id])) p\n (and (number? x) (number? y)) (assoc-in p [:boxes id :present] [x y])\n :else (update-in p [:boxes id] dissoc :present)))\n ;; how a box is shown, among the views of its class (discussion #30), or nil for its default\n :view (let [[id k] args]\n (cond (not (get-in p [:boxes id])) p\n (keyword? k) (assoc-in p [:boxes id :view] k)\n :else (update-in p [:boxes id] dissoc :view)))\n ;; [:pin :b3 [node n]]: a `patch @name` reads its line at that point (#117); nil follows its front again\n :pin (let [[id pos] args]\n (cond (not (get-in p [:boxes id])) p\n (and (vector? pos) (= 2 (count pos)) (string? (first pos)) (number? (second pos)))\n (assoc-in p [:boxes id :pin] (vec pos))\n :else (update-in p [:boxes id] dissoc :pin)))\n ;; the size of a box drawn with a size of its own (a canvas, a freqt, a score: issue #40), or nil for its default\n :size (let [[id w h] args]\n (cond (not (get-in p [:boxes id])) p\n (and (number? w) (number? h)) (assoc-in p [:boxes id :size] [w h])\n :else (update-in p [:boxes id] dissoc :size)))\n :connect (let [l (vec args)] (if (some #{l} (:lines p)) p (update p :lines conj l)))\n :disconnect (let [l (vec args)] (update p :lines (fn [ls] (vec (remove #{l} ls)))))\n :delete (let [[id] args]\n (-> p (unanchor id)\n (update :boxes dissoc id)\n (update :lines (fn [ls] (vec (remove (fn [[a _ b _]] (or (= a id) (= b id))) ls))))\n (update :projections dissoc id) (drop-empty :projections)))\n ;; [:layer :notes {:z :under :show #{:present}}] · [:layer :notes nil] removes it with its marks and projections\n :layer (let [[id l] args]\n (cond (not (keyword? id)) p\n (nil? l) (-> p (update :layers dissoc id)\n (update :marks (fn [ms] (into (sorted-map) (remove (fn [[_ m]] (= id (:layer m))) ms))))\n (update :projections (fn [ps] (into (sorted-map) (remove (fn [[_ pr]] (= id (:layer pr))) ps))))\n (drop-empty :layers) (drop-empty :marks) (drop-empty :projections))\n :else (assoc-in p [:layers id] (sane-layer l))))\n ;; [:annot :a1 {:layer :notes :kind :line :pts […]}] (its layer is made if missing) · [:annot :a1 nil] erases it\n ;; (not [:mark …]: that one is a point of the history, a snapshot or a take)\n :annot (let [[id m] args]\n (cond (not (keyword? id)) p\n (nil? m) (-> p (update :marks dissoc id) (drop-empty :marks))\n :else (if-let [m (sane-mark m)]\n (-> p (ensure-layer (:layer m)) (update :marks (fnil assoc (sorted-map)) id m))\n p)))\n ;; [:project :b9 {:layer :viz :rect [x y w h]}] · [:project :b9 nil]\n :project (let [[id pr] args]\n (cond (not (get-in p [:boxes id])) (if (nil? pr) (-> p (update :projections dissoc id) (drop-empty :projections)) p)\n (nil? pr) (-> p (update :projections dissoc id) (drop-empty :projections))\n :else (if-let [pr (sane-projection pr)]\n (-> p (ensure-layer (:layer pr)) (update :projections (fnil assoc (sorted-map)) id pr))\n p)))\n ;; event addressed to the data of a box, interpreted by its component:\n ;; [:in :b2 [:stroke :t1 [[0 440] [1 440]]]] · [:in :b7 [:source \"process = …;\"]]\n :in (let [[id ev] args dd (comp/model-of (get-in p [:boxes id]))]\n (if (and dd (vector? ev))\n (let [d0 (get-in p [:boxes id :data])\n d1 ((:step dd) (or d0 (:empty dd)) ev)]\n (cond-> (assoc-in p [:boxes id :data] d1)\n ;; the buffer changed after it was kept: its recipe no longer made it\n (and (get-in p [:boxes id :recipe]) (not= d0 d1)) (assoc-in [:boxes id :recipe :stale] true)))\n p))\n ;; [:kept :b5 data recipe]: a buffer written from a tree, with the recipe that made it, as one event\n :kept (let [[id data r] args b (get-in p [:boxes id]) dd (comp/model-of b) r (sane-recipe r)]\n (if (and dd (map? data) r)\n (-> p (assoc-in [:boxes id :data] ((:load dd) data))\n (assoc-in [:boxes id :recipe] (dissoc r :stale)))\n p))\n ;; [:recipe :b5 r] sets the recipe of a box (as the code of a work writes it); nil removes it\n :recipe (let [[id r] args]\n (cond (not (get-in p [:boxes id])) p\n (sane-recipe r) (assoc-in p [:boxes id :recipe] (sane-recipe r))\n :else (update-in p [:boxes id] dissoc :recipe)))\n ;; [:data :b5 d]: the whole data of a box (a release, points forgotten: issue #45), nil to empty it\n :data (let [[id d] args b (get-in p [:boxes id]) dd (comp/model-of b)]\n (cond (not b) p\n (and dd (map? d)) (assoc-in p [:boxes id :data] ((:load dd) d))\n ;; a class not defined yet (a package still loading): its data as it was written\n (map? d) (assoc-in p [:boxes id :data] d)\n (nil? d) (update-in p [:boxes id] dissoc :data)\n :else p))\n ;; [:batch [ev …]]: several changes as one event of the history (a preset recalled: issue #35)\n :batch (let [[evs] args] (if (sequential? evs) (reduce step p (filter vector? evs)) p))\n :load (sane-patch (first args))\n :clear empty-patch\n p))\n\n;; ───────────────────────── EDN ⇄ JSON encoding ─────────────────────────\n;; db stores JSON; keywords, names (symbols) and maps are tagged so they come back as EDN without evaluating anything.\n\n(defn enc [x]\n (cond (keyword? x) {\"k\" (if (namespace x) (str (namespace x) \"/\" (name x)) (name x))}\n ;; a name (a msg sends inc, e4, 6/5 as names): its whole text, tagged like a keyword\n (symbol? x) {\"y\" (str x)}\n (map? x) {\"m\" (mapv (fn [[k v]] [(enc k) (enc v)]) x)}\n ;; a set (the views a layer is shown in) travels as a list: whoever reads it makes it a set again\n (or (sequential? x) (set? x)) (mapv enc x)\n :else x))\n\n(defn dec* [x]\n (cond (map? x) (cond (contains? x \"k\") (keyword (str (get x \"k\")))\n (contains? x \"y\") (symbol (str (get x \"y\")))\n (contains? x \"m\") (into {} (for [kv (get x \"m\") :when (and (sequential? kv) (= 2 (count kv)))]\n [(dec* (first kv)) (dec* (second kv))]))\n :else nil)\n (sequential? x) (mapv dec* x)\n :else x))\n\n;; ───────────────────────── history: a tree of segments ─────────────────────────\n;; node = segment of consecutive events by one person: {:id :parent :at :author :t :events}\n;; position = [node-id n] = after the first n events of that node.\n;;\n;; A work is a project of lines (discussion #117, phase 1): independent histories, each a whole tree of its\n;; own, shown as tabs above the patch. Their segments live in the same collection as always, each with the\n;; line it belongs to (:line, nil for the main line), so a work without lines is what it always was. :nodes\n;; holds the segments of the line on screen, and everything that reads the history reads only that line;\n;; :other holds the segments of the other lines, by line id, until their tab is chosen.\n\n(def max-events 64)\n\n(defonce hist (atom {:nodes {} :other {} :loaded false :mode :connecting :writable false}))\n\n;; the lines of the open work: their names (in <work>/lines, one document per line), which one is on screen,\n;; and where each one was left (its tab remembers its point of the history)\n;; {:active \"main\" :index {\"main\" {:name \"main\" :created 0} \"Xk3…\" {:name \"sketch\" :created … :archived false}}\n;; :pos {\"Xk3…\" [node n]}}\n(def main-line \"main\")\n(defonce line-state (atom {:active main-line :index {} :pos {}}))\n(defn active-line [] (:active @line-state))\n(defn on-main-line? [] (= main-line (active-line)))\n(defonce world (atom {:pos nil :auto true :prev-pos nil :jumped-at 0}))\n(defonce me (atom {:id nil}))\n(defonce peers (atom []))\n(defonce profiles (atom {}))\n(defonce scratch (atom nil))\n(defonce cache (atom {}))\n(defonce dbref (atom nil))\n(defonce roomref (atom nil))\n(defonce userref (atom nil))\n(defonce settings (atom {:simul-ms 1500}))\n\n;; a session = a tab; it survives reloads of that tab\n(def session-id\n (or (try (.getItem js/sessionStorage \"kairotic-session\") (catch :default _ nil))\n (let [s (str \"s\" (.toString (js/Math.floor (* (js/Math.random) 2176782336)) 36))]\n (try (.setItem js/sessionStorage \"kairotic-session\" s) (catch :default _ nil))\n s)))\n\n(defn my-author [] (or (:id @me) \"local\"))\n(defn node [nid] (get-in @hist [:nodes nid]))\n(defn node-session [n] (or (:session n) (:author n)))\n\n(defn norm\n \"A position at the start of a child node is the same as its branching point.\"\n [pos]\n (loop [[nid idx :as pos] pos guard 0]\n (let [n (node nid)]\n (cond (or (nil? pos) (nil? n) (> guard 512)) pos\n (and (zero? idx) (:parent n) (node (:parent n))) (recur [(:parent n) (:at n)] (inc guard))\n :else [nid (max 0 (min idx (count (:events n))))]))))\n\n(defn patch-at\n ([pos] (patch-at pos 0))\n ([pos depth]\n (if (or (nil? pos) (> depth 512))\n empty-patch\n (or (get @cache pos)\n (let [[nid idx] pos n (node nid)]\n (if (nil? n)\n empty-patch\n (let [base (if (and (:parent n) (node (:parent n))) (patch-at [(:parent n) (:at n)] (inc depth)) empty-patch)\n p (reduce step base (take idx (:events n)))]\n (swap! cache assoc pos p)\n p)))))))\n\n;; ───── where the commands act: the work, or a sub-patch inside it ─────\n;; view-path is the sub-patch on screen ([] = the work, [:b5] = inside :b5 …); (inside :b5 …) adds to it\n;; while its body runs. Commands read (current) and their events are wrapped as [:in :b5 event].\n\n;; ───── Perform (issue #5): a time of its own to rehearse, try and improvise with the work ─────\n;; In Perform the changes do not go to the history: they make a take that starts from a point of it\n;; (:origin), and the patch on screen (and in the engine) is that take. Leaving it (compose) keeps the\n;; take as a new point or discards it. In a shared room, the takes of those who perform from the same\n;; point are one jam: everyone's changes, in time order. 13-perform.cljs has the rest.\n;; {:from pos :origin pos :base patch :patch patch :own [{:t :s :ev}] :others {session [{:t :s :ev}]}\n;; :redo [entry] :cut t :jam id-or-nil}\n\n(declare jam-push!)\n\n(defonce perf (atom nil))\n\n(defn perf-events\n \"The changes of the take after its last snapshot (:cut), from everyone in the jam, in time order.\"\n [{:keys [own others cut]}]\n (sort-by (juxt :t :s) (filter (fn [e] (> (:t e) (or cut 0))) (concat own (apply concat (vals others))))))\n\n(defn perf-recompute [st] (assoc st :patch (reduce step (:base st) (map :ev (perf-events st)))))\n\n(defn perform-event!\n \"A change made in Perform: it goes to the take (and to the jam), not to the history.\"\n [ev]\n (swap! perf (fn [st] (-> st (update :own conj {:t (js/Date.now) :s session-id :ev ev}) (assoc :redo []) (update :patch step ev))))\n (jam-push!))\n\n(defn work-patch [] (or (:patch @perf) (patch-at (:pos @world))))\n\n;; ───── the line that plays (discussion #117, decision 6) ─────\n;; The engine plays the line where ▶ was pressed; the tab on screen is only what you see and edit, so\n;; changing tabs does not stop it. While another line plays, the one on screen still runs its messages\n;; (they travel without ▶), as a part of the engine's patch apart from the line that plays: its boxes are\n;; known by the prefix @<its line> (:@l3x.b1), so ids of two lines never meet. Its audio boxes stay out:\n;; only the line that plays sounds.\n\n(defn playing-line [] (when (eng/running?) (:playing @line-state)))\n\n(defn playing-elsewhere?\n \"Is the engine playing a line other than the one on screen?\"\n [] (let [p (playing-line)] (and p (not= p (active-line)))))\n\n(defn view-prefix\n \"Where the engine knows the line on screen while another plays: inside the line that plays, where it uses\n it (its first instance: what the tab shows), or, if it does not, under @<its line> (#117).\"\n []\n (if (playing-elsewhere?)\n (or (first (view-instances)) [(keyword (str \"@\" (active-line)))])\n []))\n\n(defn nodes-patch\n \"The patch at pos of a line whose segments are nodes (a line not on screen).\"\n [nodes pos]\n (let [evs (loop [[nid idx] pos acc () guard 0]\n (let [n (get nodes nid)]\n (if (or (nil? n) (> guard 512))\n acc\n (let [acc (cons (take idx (:events n)) acc)]\n (if (and (:parent n) (get nodes (:parent n)))\n (recur [(:parent n) (:at n)] acc (inc guard))\n acc)))))]\n (reduce step empty-patch (apply concat evs))))\n\n(defonce off-screen-cache (atom [nil nil nil]))\n\n(defn off-screen-patch\n \"The patch of line lid, not on screen: where its tab was left (or its newest point).\"\n [lid]\n (let [nodes (get-in @hist [:other lid] {})\n saved (get-in @line-state [:pos lid])\n pos (if (and saved (get nodes (first saved)))\n saved\n (when (seq nodes)\n (let [n (apply max-key (fn [n] (or (:t n) 0)) (vals nodes))] [(:id n) (count (:events n))])))\n [k1 k2 v] @off-screen-cache]\n (if (and (identical? k1 nodes) (= k2 pos))\n v\n (let [p (if pos (nodes-patch nodes pos) empty-patch)] (reset! off-screen-cache [nodes pos p]) p))))\n\n(defn silent\n \"Patch p without its audio boxes (nor the lines to and from them).\"\n [p]\n (let [audio (set (keep (fn [[id b]] (when (:audio (comp/lookup (klass (:text b)))) id)) (:boxes p)))]\n (if (empty? audio)\n p\n (-> p (update :boxes (fn [bx] (into (sorted-map) (remove (fn [[id _]] (audio id)) bx))))\n (update :lines (fn [ls] (vec (remove (fn [[a _ b _]] (or (audio a) (audio b))) ls))))))))\n\n(defonce engine-patch-cache (atom [nil nil nil nil]))\n\n(defn engine-patch\n \"The patch the engine runs: the work on screen, or, while another line plays, that line — with the one on\n screen beside it (silent, under its prefix) when it does not use it already. The same object while neither\n changes (the engine flattens it again only when it is another).\"\n []\n (if (and (playing-elsewhere?) (empty? (view-instances)))\n (let [off (off-screen-patch (playing-line)) here (work-patch) k (first (view-prefix))\n [a b c v] @engine-patch-cache]\n (if (and (identical? a off) (identical? b here) (= c k))\n v\n (let [v (assoc-in off [:boxes k] {:text \"patch\" :x 0 :y 0 :data (silent here)})]\n (reset! engine-patch-cache [off here k v])\n v)))\n (if (playing-elsewhere?) (off-screen-patch (playing-line)) (work-patch))))\n\n(declare played!)\n\n(defn inject-local!\n \"A message played here (a gesture, the REPL) into box f of the engine. In a jam it is also played to the\n others (issue #11): messages are not events of the take, so they travel apart (13-perform.cljs).\"\n [f inlet v]\n ;; from the tab of a line used more than once by the line that plays: to every instance of it (#117)\n (let [ins (view-instances)\n pre (when (next ins) (str (str/join \".\" (map name (first ins))) \".\"))\n n (name f)]\n (if (and pre (str/starts-with? n pre))\n (doseq [path ins]\n (eng/inject! engine-patch (keyword (str (str/join \".\" (map name path)) \".\" (subs n (count pre)))) inlet v))\n (eng/inject! engine-patch f inlet v)))\n (played! f inlet v))\n(defn root-patch [] (or @scratch (work-patch)))\n\n(defonce view-path (atom []))\n(def ^:dynamic *inside* [])\n\n(defn cmd-path [] (if @scratch *inside* (into @view-path *inside*)))\n\n(defn line-ref? \"A `patch @name` box: a line used as a sub-patch (#117).\" [b] (boolean (and b (eng/line-ref b))))\n\n;; an embedded patch keeps its inside in the box; a `patch @name` reads a line, and is not entered\n(defn embedded? [b] (and b (= \"patch\" (klass (:text b))) (not (line-ref? b))))\n\n;; a component box defines a class: it has no inlets nor outlets, so it is not drawn in the patch but kept\n;; in the Components tab (issue #8). It is still a box of the work: its history, its code and links.\n(defn definition? [b] (and b (= \"component\" (klass (:text b)))))\n\n(defn without-definitions [boxes] (into (or (empty boxes) (sorted-map)) (remove (fn [[_ b]] (definition? b)) boxes)))\n\n(defn valid-prefix\n \"The longest part of `path` that still leads through embedded patches of p.\"\n [p path]\n (loop [q p acc [] ids (seq path)]\n (if-let [id (first ids)]\n (let [b (get-in q [:boxes id])]\n (if (embedded? b) (recur (or (:data b) empty-patch) (conj acc id) (next ids)) acc))\n acc)))\n\n(defn patch-in [p path]\n (reduce (fn [q id] (or (get-in q [:boxes id :data]) empty-patch)) p (valid-prefix p path)))\n\n(defn current []\n (let [r (root-patch)]\n (when-not @scratch\n (let [ok (valid-prefix r @view-path)]\n (when (< (count ok) (count @view-path)) (reset! view-path ok))))\n (patch-in r (cmd-path))))\n\n(defn wrap-in [path ev] (reduce (fn [e id] [:in id e]) ev (reverse path)))\n\n(defn engine-path\n \"Where the engine knows the sub-patch on screen: its path, after the prefix of its line while another plays.\"\n [] (into (view-prefix) (cmd-path)))\n\n(defn fid\n \"The id the engine knows a box of the current view by.\"\n [id] (eng/flat-id (engine-path) id))\n\n;; ───── which box is drawn over which (issue #166) ─────\n;; Boxes are drawn in the order of the number of their ids (not as text, which put :b10–:b19 under :b2): a\n;; patch is drawn in the order its boxes were made, the newest on top. A box dragged here comes to the front,\n;; so that what is being moved is never hidden. That order is only for this tab, as the selection is: it is\n;; not part of the work, not in the history and not in its code.\n\n(defonce dragged-front (atom [])) ; engine ids of the boxes dragged here, the last one on top\n\n(defn id-z [id] (let [m (re-matches #\"b(\\d+)\" (name id))] (if m (js/parseInt (second m) 10) 0)))\n\n(defn to-front!\n \"Brings boxes of the current view to the front, in this tab only, keeping their order among themselves.\"\n [ids]\n (let [fs (map fid (sort-by id-z ids)) fs (sort-by (fn [f] (.indexOf (to-array @dragged-front) f)) fs)]\n (swap! dragged-front (fn [v] (vec (take-last 400 (concat (remove (set fs) v) fs)))))))\n\n(defn by-z\n \"The [id box] pairs of a map of boxes of the current view, from the bottom to the top: the ones dragged in\n this tab on top, in the order they were dragged; the others in the order of the number of their ids.\"\n [boxes]\n (let [rank (into {} (map-indexed (fn [i f] [f i]) @dragged-front))]\n (sort-by (fn [[id _]] [(get rank (fid id) -1) (id-z id) (name id)]) boxes)))\n\n(defn target\n \"Where a message to inlet i of box id goes in the engine: a sub-patch receives it in its i-th inlet box.\"\n [id inlet]\n (let [b (get-in (current) [:boxes id])]\n (if (and b (comp/subpatch? b))\n (let [inner (eng/inner-patch b) x (get (:inlets (comp/patch-ports inner)) inlet)]\n (if x [(eng/flat-id (conj (engine-path) id) x) 0] (throw (js/Error. (str id \" has no inlet \" inlet)))))\n [(fid id) inlet])))\n\n(defn local-id\n \"From an engine id back to an id of the current view (nil if it lives elsewhere).\"\n [fid*]\n (let [path (engine-path) n (name fid*)]\n (if (empty? path)\n (when-not (str/includes? n \".\") fid*)\n (let [pre (str (str/join \".\" (map name path)) \".\") rest-n (subs n (min (count n) (count pre)))]\n (when (and (str/starts-with? n pre) (not (str/includes? rest-n \".\"))) (keyword rest-n))))))\n\n(defn start-of\n \"Depth (number of events from the root) at which a node starts.\"\n ([nid] (start-of nid 0))\n ([nid depth]\n (let [n (node nid)]\n (if (and n (:parent n) (node (:parent n)) (< depth 512))\n (+ (start-of (:parent n) (inc depth)) (:at n))\n 0))))\n\n(defn depth-of [[nid idx]] (+ (start-of nid) idx))\n\n(defn tip-of [nid] [nid (count (:events (node nid)))])\n\n(defn newest-tip []\n (let [ns (vals (:nodes @hist))]\n (when (seq ns) (tip-of (:id (apply max-key (fn [n] (or (:t n) 0)) ns))))))\n\n;; ───────────────────────── storage ─────────────────────────\n\n(defonce queues (atom {}))\n\n(defonce recent-errors (atom [])) ; the last errors the REPL showed (for the Feedback tab)\n\n(defn print-line\n \"How the REPL writes what a print box received: its label (or print), then the value — a string as it is\n (what format and str make), anything else as EDN.\"\n [v label]\n (str (if (seq label) label \"print\") \": \" (if (string? v) v (pr-str v))))\n\n(defn repl-print! [cls html]\n (when (= cls \"err\")\n (let [d (js/document.createElement \"div\")]\n (set! (.-innerHTML d) html)\n (swap! recent-errors (fn [es] (vec (take-last 10 (conj es (.-textContent d))))))))\n (let [out (js/document.getElementById \"repl-out\") d (js/document.createElement \"div\")]\n (set! (.-className d) cls)\n (set! (.-innerHTML d) html)\n (.appendChild out d)\n (set! (.-scrollTop out) (.-scrollHeight out))))\n\n(defn esc [s] (-> (str s) (str/replace \"&\" \"&\") (str/replace \"<\" \"<\") (str/replace \">\" \">\") (str/replace \"\\\"\" \""\")))\n\n(defn db-failed! [e]\n (let [code (or (.-code e) \"error\")]\n (when (#{\"invalid_argument\" \"revoked\" \"not_granted\"} code)\n (swap! hist assoc :writable false :mode :readonly))\n (repl-print! \"err\" (esc (str \"Could not save to the shared history (\" code \"). Your gestures stay in this tab.\")))))\n\n(defn enqueue! [k f]\n (let [prev (get @queues k (js/Promise.resolve nil))\n p (-> prev (.then (fn [_] (f))) (.catch db-failed!))]\n (swap! queues assoc k p)))\n\n(defn node->js [n]\n (clj->js (cond-> {:parent (:parent n) :at (:at n) :author (:author n) :session (:session n) :t (:t n)\n :merge (:merge n) :events (mapv enc (:events n))}\n (:line n) (assoc :line (:line n)))))\n\n;; ───────────────────────── works: shared rooms and solo work ─────────────────────────\n;; room: rooms/<id> (metadata) · rooms/<id>/history/<segment>\n;; solo: data/users/<uid>/<id> (private) · data/users/<uid>/<id>/history/<segment>\n\n(defonce work (atom {:kind nil :id nil :name nil}))\n\n(defn uid [] (:id @me))\n\n(defn base-of [kind id]\n (case kind\n :room (str \"rooms/\" id)\n :solo (when (uid) (str \"data/users/\" (uid) \"/\" id))\n nil))\n\n(defn work-base [] (base-of (:kind @work) (:id @work)))\n(defn hist-path [] (when-let [b (work-base)] (str b \"/history\")))\n;; what belongs to one line besides its segments (its jams): the work's own place for the main line\n(defn line-base [] (when-let [b (work-base)] (if (on-main-line?) b (str b \"/lines/\" (active-line)))))\n\n(defn persist? []\n (and @dbref (:writable @hist) (#{:room :solo} (:kind @work)) (hist-path)))\n\n(defn new-id []\n (if (persist?)\n (.-id (.doc (.collection @dbref (hist-path))))\n (str \"local-\" (.toString (js/Math.floor (* (js/Math.random) 2176782336)) 36) (.toString (js/Date.now) 36))))\n\n(defn new-node! [parent at evs merge]\n (let [id (new-id)\n n (cond-> {:id id :parent parent :at at :author (my-author) :session session-id :t (js/Date.now)\n :merge merge :events (vec evs)}\n (not (on-main-line?)) (assoc :line (active-line)))]\n (swap! hist assoc-in [:nodes id] n)\n (when (and (persist?) (not (str/starts-with? id \"local-\")))\n (let [path (str (hist-path) \"/\" id) body (node->js n)]\n (enqueue! path (fn [] (.set (.doc @dbref path) body)))))\n id))\n\n(defn append-event! [nid ev]\n (swap! hist update-in [:nodes nid] (fn [n] (-> n (update :events conj ev) (assoc :t (js/Date.now)))))\n (when (and (persist?) (not (str/starts-with? nid \"local-\")))\n (let [n (node nid)\n path (str (hist-path) \"/\" nid)\n body (clj->js {:events (mapv enc (:events n)) :t (:t n)})]\n (enqueue! path (fn [] (.update (.doc @dbref path) body))))))\n\n(defn own-open-tip? [[nid idx]]\n (let [n (node nid)]\n (and n (= (node-session n) session-id) (= idx (count (:events n))) (< idx max-events))))\n\n(defn commit!\n \"Adds an event where you are. If you have just moved forward over someone else's event less than the\n simultaneity interval ago, your event is considered parallel and starts from where you were (a branch).\"\n [ev]\n (let [{:keys [pos prev-pos jumped-at]} @world\n parallel? (and prev-pos (< (- (js/Date.now) jumped-at) (:simul-ms @settings)))\n base (if parallel? prev-pos pos)]\n (if (and base (own-open-tip? base))\n (do (append-event! (first base) ev)\n (swap! world assoc :pos [(first base) (inc (second base))] :auto true :prev-pos nil))\n (let [id (new-node! (first base) (if base (second base) 0) [ev] nil)]\n (swap! world assoc :pos [id 1] :auto true :prev-pos nil)))))\n\n;; ───────────────────────── paths, front and merge ─────────────────────────\n\n(defn segments\n \"Path from the root to a position, as [[segment n] ...].\"\n [pos]\n (loop [[nid idx :as p] pos acc () guard 0]\n (let [n (node nid)]\n (if (and n (:parent n) (node (:parent n)) (< guard 512))\n (recur [(:parent n) (:at n)] (cons p acc) (inc guard))\n (vec (cons p acc))))))\n\n(defn reaches?\n \"Is `tip` reached by moving forward from `pos`?\"\n [pos tip]\n (let [[pn pi] pos]\n (boolean (some (fn [[sn si]] (and (= sn pn) (>= si pi))) (segments tip)))))\n\n(defn front-from\n \"The newest tip reached by moving forward from pos.\"\n [pos]\n (let [cands (filter (fn [t] (reaches? pos t)) (map (fn [n] (tip-of (:id n))) (vals (:nodes @hist))))]\n (when (seq cands) (apply max-key (fn [[nid _]] (or (:t (node nid)) 0)) cands))))\n\n(defn seg-events [[nid n] from]\n (let [evs (vec (take n (:events (node nid))))]\n (subvec evs (min from (count evs)))))\n\n(defn diverge\n \"Common point of two paths and the events each one adds from there.\"\n [ts ss]\n (loop [i 0]\n (let [t (nth ts i nil) s (nth ss i nil)]\n (when (and t s (= (first t) (first s)))\n (let [nt (nth ts (inc i) nil) nx (nth ss (inc i) nil)]\n (if (and (= (second t) (second s)) nt nx (= (first nt) (first nx)))\n (recur (inc i))\n (let [k (min (second t) (second s))\n extra (fn [segs] (vec (concat (seg-events (nth segs i) k) (mapcat (fn [g] (seg-events g 0)) (drop (inc i) segs)))))]\n {:base [(first t) k] :t-extra (extra ts) :s-extra (extra ss)})))))))\n\n(defn unbatch\n \"The events of a history with the changes of every [:batch …] in its place.\"\n [evs]\n (mapcat (fn [e] (if (and (vector? e) (= :batch (first e)) (sequential? (second e))) (unbatch (second e)) [e])) evs))\n\n(defn summarize [evs]\n (reduce (fn [acc [op & args]]\n (case op\n (:box :text :move :size) (update acc :mod conj (first args))\n ;; each mark, layer and projection is its own unit; a mark refers to the boxes it is anchored to\n :annot (-> acc (update :mod conj [:annot (first args)])\n (update :ref into (let [m (second args)] (filter (fn [a] (and (keyword? a) (not= a :patch)))\n (map first (concat (:pts m) (when (:at m) [(:at m)])))))))\n :layer (update acc :mod conj [:layer (first args)])\n :project (-> acc (update :mod conj [:project (first args)]) (update :ref conj (first args)))\n :delete (-> acc (update :mod conj (first args)) (update :del conj (first args)))\n (:connect :disconnect) (update acc :ref into [(first args) (nth args 2 nil)])\n :load (assoc acc :load true)\n ;; a kept buffer rewrites the whole box data; a recipe alone is its own unit\n :data (-> acc (update :mod conj (first args)) (update :ref conj (first args)) (update :whole conj (first args)))\n :kept (-> acc (update :mod conj (first args)) (update :ref conj (first args)) (update :whole conj (first args)))\n :recipe (-> acc (update :mod conj [(first args) :recipe]) (update :ref conj (first args)))\n :pin (-> acc (update :mod conj [(first args) :pin]) (update :ref conj (first args)))\n ;; in a canvas, each stroke is its own unit of change, and so is each grid;\n ;; clear or load affects the whole canvas\n :in (let [[id [iop eid]] args]\n (case iop\n (:stroke :move :stretch :erase) (-> acc (update :mod conj [id eid]) (update :ref conj id))\n :grid-x (-> acc (update :mod conj [id :grid-x]) (update :ref conj id))\n :tuning (-> acc (update :mod conj [id :tuning]) (update :ref conj id))\n :quantize (-> acc (update :mod conj [id :quant]) (update :ref conj id))\n ;; in a tree, each edited node is its own unit; inserting or removing changes its container\n ;; units: [box path kind] — :node (replaced), :kids (children added or removed, so their\n ;; indices move), :attrs (only its attributes)\n :edit (-> acc\n (update :tree into (for [[op p] eid :let [p (vec p)]]\n (case op\n :attrs [id p :attrs]\n (:insert :remove) [id (if (seq p) (pop p) p) :kids]\n [id p :node])))\n (update :ref conj id))\n (-> acc (update :mod conj id) (update :ref conj id) (update :whole conj id))))\n acc))\n {:mod #{} :ref #{} :del #{} :whole #{} :tree #{} :load false} (unbatch evs)))\n\n(defn remap-ev [m [op & args :as e]]\n (let [f (fn [x] (get m x x))]\n (case op\n (:box :text :move :size :delete :kept :recipe :data :project :pin) (into [op (f (first args))] (rest args))\n :annot (let [[id m] args fa (fn [[a x y]] [(f a) x y])]\n [op id (cond-> m (:pts m) (update :pts (fn [ps] (mapv fa ps))) (:at m) (update :at fa))])\n :in (let [[id inner] args]\n [op (f id) (if-let [ne (get-in m [:stroke-ids [id (second inner)]])] (assoc inner 1 ne) inner)])\n (:connect :disconnect) (let [[a o b i] args] [op (f a) o (f b) i])\n :batch [op (mapv (fn [x] (remap-ev m x)) (first args))]\n e)))\n\n(defn free-box-id [used]\n (loop [k 1] (let [id (keyword (str \"b\" k))] (if (used id) (recur (inc k)) id))))\n\n(defn tree-units-clash?\n \"Whether two edits of one tree touch the same thing: a replaced node and anything inside it, children\n added or removed and anything below them (their indices move), or the attributes of the same node.\"\n [[p kp] [q kq]]\n (let [prefix? (fn [a b] (and (<= (count a) (count b)) (= a (subvec b 0 (count a)))))\n proper? (fn [a b] (and (< (count a) (count b)) (prefix? a b)))\n one-way (fn [[a ka] [b kb]]\n (case ka\n :node (prefix? a b)\n :kids (or (proper? a b) (and (= a b) (= kb :kids)))\n :attrs (and (= a b) (= kb :attrs))))]\n (or (one-way [p kp] [q kq]) (one-way [q kq] [p kp]))))\n\n(defn tree-clash\n \"Edits of the same tree that touch the same thing in both branches: [[box path] …].\"\n [S T]\n (concat\n (for [[i p kp] (:tree S) [j q kq] (:tree T) :when (and (= i j) (tree-units-clash? [p kp] [q kq]))]\n [i (if (<= (count p) (count q)) p q)])\n (for [[i] (:tree S) :when (contains? (:whole T) i)] [i []])\n (for [[i] (:tree T) :when (contains? (:whole S) i)] [i []])))\n\n(defn plan-merge\n \"Which events of branch `src` must be brought to `tgt`, or why it cannot be done.\"\n [tgt src]\n (let [ts (segments tgt) ss (segments src)\n ;; what was already brought by earlier merges is not brought again\n merged (keep (fn [g] (:merge (node (first g)))) ts)\n done (last (filter (fn [m] (and (vector? m) (node (first m)) (reaches? m src))) merged))\n d (diverge ts ss)\n s-extra (if done (or (:s-extra (diverge (segments done) ss)) []) (:s-extra d))]\n (cond\n (nil? d) {:error \"Those two positions do not share an origin.\"}\n (empty? s-extra) {:error \"That branch has nothing new to bring here: it is already included.\"}\n :else\n (let [base (patch-at (:base d))\n base-ids (set (keys (:boxes base)))\n in-base? (fn [x] (if (vector? x)\n (or (#{:grid-x :tuning :quant} (second x)) (get-in base [:boxes (first x) :data :strokes (second x)]))\n (base-ids x)))\n S (summarize s-extra) T (summarize (:t-extra d))\n note-boxes (fn [X] (set (keep (fn [x] (when (vector? x) (first x))) (:mod X))))\n clash (filter in-base? (concat (clojure.set/intersection (:mod S) (:mod T))\n (clojure.set/intersection (:ref S) (:del T))\n (clojure.set/intersection (:ref T) (:del S))\n (clojure.set/intersection (:whole S) (note-boxes T))\n (clojure.set/intersection (:whole T) (note-boxes S))))\n clash-name (fn [x] (cond (not (vector? x)) (str x)\n (#{:grid-x :tuning :quant} (second x)) (str \"the \" (name (second x)) \" of \" (first x))\n :else (str \"stroke \" (second x) \" of \" (first x))))]\n (cond\n (or (and (:load S) (seq (:t-extra d))) (and (:load T) (seq s-extra)))\n {:error \"They are not compatible: one of the branches rebuilds the whole work (:load).\"}\n (seq (concat clash (tree-clash S T)))\n {:error (str \"They are not compatible: both branches change \"\n (str/join \", \" (concat (map clash-name (distinct clash))\n (map (fn [[id p]] (str \"the tree of \" id (when (seq p) (str \" at \" (pr-str p)))))\n (distinct (tree-clash S T)))))\n \".\")}\n :else\n (let [target (patch-at tgt)\n created (distinct (keep (fn [[op id]] (when (and (= op :box) (not (base-ids id))) id)) s-extra))\n m (loop [[c & more] created used (into (set (keys (:boxes target))) created) m {}]\n (cond (nil? c) m\n (contains? (:boxes target) c) (let [nid (free-box-id used)] (recur more (conj used nid) (assoc m c nid)))\n :else (recur more used m)))\n ;; new strokes in both branches with the same id: the incoming ones are renamed\n tbox (fn [id] (get-in target [:boxes (get m id id) :data :strokes]))\n created-notes (distinct (keep (fn [[op id inner]]\n (when (and (= op :in) (vector? inner) (= :stroke (first inner))\n (not (get-in base [:boxes id :data :strokes (second inner)])))\n [id (second inner)]))\n s-extra))\n nm (loop [[[id eid :as c] & more] created-notes used {} nm {}]\n (cond (nil? c) nm\n (contains? (tbox id) eid)\n (let [taken (into (set (keys (tbox id))) (get used id))\n ne (loop [k 1] (let [x (keyword (str \"t\" k))] (if (taken x) (recur (inc k)) x)))]\n (recur more (update used id (fnil conj #{}) ne eid) (assoc nm c ne)))\n :else (recur more (update used id (fnil conj #{}) eid) nm)))]\n {:events (vec (cons [:merge-from (first src) (second src)] (map (fn [e] (remap-ev (assoc m :stroke-ids nm) e)) s-extra)))\n :renamed (merge m (into {} (for [[[id eid] ne] nm] [(keyword (str (name id) \".\" (name eid))) ne])))}))))))\n","page/01-commands.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 2 of 12: commands\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── commands ─────────────────────────\n\n(defonce ui (atom {:sel nil :drag nil :wire nil :hover-in nil :dirty false :hist [] :hidx nil :follow nil}))\n\n;; What is selected: [:box id] · [:boxes #{id …}] (several, by ⇧+click or a frame) · [:line l] · nil.\n;; :insp is the box whose inspector is open (⌘/Ctrl+click): a plain click selects and moves, nothing more.\n\n(defn sel-ids\n \"The boxes selected now (a set).\"\n []\n (let [[kind v] (:sel @ui)] (case kind :box #{v} :boxes v #{})))\n\n(defn sel-of\n \"The selection made of these boxes.\"\n [ids]\n (case (count ids) 0 nil 1 [:box (first ids)] [:boxes (set ids)]))\n\n(defn fail [msg] (throw (js/Error. msg)))\n\n(defn dispatch-root!\n \"An event of the whole work (its ids already lead from the top: [:in :b5 …] for a sub-patch), wherever the\n view is: to the scratch patch, to the take in Perform, or to the history.\"\n [ev]\n (cond\n @scratch (swap! scratch step ev)\n @perf (perform-event! ev)\n (= :connecting (:mode @hist)) (fail \"Still connecting to the shared history; try again in a moment.\")\n (= :none (:mode @hist)) (fail \"Open or create a work from the session manager.\")\n :else (do (when (:follow @ui) (swap! ui assoc :follow nil))\n (commit! ev))))\n\n(defn dispatch! [ev] (dispatch-root! (wrap-in (cmd-path) ev)))\n\n(declare ensure-class!)\n\n(defn need-box [id]\n (or (get-in (current) [:boxes id]) (fail (str \"There is no box \" id))))\n\n(defn next-id []\n (let [nums (keep (fn [k] (let [m (re-matches #\"b(\\d+)\" (name k))] (when m (js/parseInt (second m) 10))))\n (keys (:boxes (current))))]\n (keyword (str \"b\" (inc (if (seq nums) (apply max nums) 0))))))\n\n(defn auto-pos []\n (let [n (count (:boxes (current)))]\n [(+ 40 (* 24 (mod n 12))) (+ 40 (* 36 (mod n 12)))]))\n\n(defn dispatch-all!\n \"Several events as one event of the history (nothing if there are none).\"\n [evs] (when-let [e (rel/as-event evs)] (dispatch! e)))\n\n(defn box\n \"Makes a box: (box \\\"osc~ 440\\\"), (box \\\"osc~ 440\\\" 40 120), or with its id, (box :b3 \\\"osc~ 440\\\" 40 120). Returns its id.\"\n ([text] (let [[x y] (auto-pos)] (box (next-id) text x y)))\n ([text x y] (box (next-id) text x y))\n ([id text x y]\n (when-not (keyword? id) (fail \"A box id is a keyword, e.g. :b3\"))\n (check-ref-text! text)\n (forget-box! id)\n (dispatch! [:box id (str text) (js/Math.round x) (js/Math.round y)])\n (ensure-class! text)\n id))\n\n(defn connect\n \"Connects outlet o of box a to inlet i of box b: (connect :b1 0 :b2 0).\"\n [a o b i]\n (let [[_ outs] (io (need-box a))\n [ins _] (io (need-box b))]\n ;; boxes with computed ports (or of classes not defined yet) accept any port\n (when-not (or (comp/dynamic? (need-box a)) (< -1 o outs)) (fail (str a \" has no outlet \" o \" (it has \" outs \")\")))\n (when-not (or (comp/dynamic? (need-box b)) (< -1 i ins)) (fail (str b \" has no inlet \" i \" (it has \" ins \")\")))\n (when (= a b) (fail \"A box cannot be connected to itself\"))\n (dispatch! [:connect a o b i])\n [a o b i]))\n\n(defn disconnect\n \"Takes away the line from outlet o of box a to inlet i of box b: (disconnect :b1 0 :b2 0).\"\n [a o b i] (dispatch! [:disconnect a o b i]) :ok)\n(defn move\n \"Moves a box to x y: (move :b3 40 120).\"\n [id x y] (need-box id) (dispatch! [:move id (js/Math.round x) (js/Math.round y)]) [x y])\n(defn text!\n \"Rewrites the text of a box (its class and arguments): (text! :b3 \\\"osc~ 220\\\").\"\n [id text] (need-box id) (check-ref-text! text) (dispatch! [:text id (str text)]) (eng/forget! (fid id)) (ensure-class! text) id)\n\n(defn delete\n \"Deletes boxes, with their lines: (delete :b3) · (delete :b3 :b4 :b7).\"\n [& ids]\n (when (empty? ids) (fail \"Which box? (delete :b3)\"))\n (doseq [id ids] (need-box id))\n (doseq [id (distinct ids)] (forget-box! id) (dispatch! [:delete id]))\n :ok)\n\n(defn- shift-ids [ids dx dy where]\n (when-not (and (sequential? ids) (seq ids)) (fail \"Give the boxes as a vector: [:b1 :b2]\"))\n (when-not (and (number? dx) (number? dy)) (fail \"dx and dy are numbers\"))\n (let [ids (distinct ids) p (current)]\n (doseq [id ids] (need-box id))\n (let [pos (for [id ids :let [b (get-in p [:boxes id])]]\n [id (if (= where :present) (:present b) [(:x b) (:y b)])])]\n (when (and (= where :present) (some (comp nil? second) pos))\n (fail (str \"Not in presentation: \" (str/join \" \" (keep (fn [[id xy]] (when-not xy id)) pos)))))\n ;; nobody goes past the top or the left edge: the group stops there together\n (let [dx (max dx (- (apply min (map (comp first second) pos))))\n dy (max dy (- (apply min (map (comp second second) pos))))]\n ;; moved together, in one event of the history\n (dispatch-all! (for [[id [x y]] pos] [where id (js/Math.round (+ x dx)) (js/Math.round (+ y dy))]))\n [(js/Math.round dx) (js/Math.round dy)]))))\n\n(defn next-mark-id []\n (let [nums (keep (fn [k] (let [m (re-matches #\"a(\\d+)\" (name k))] (when m (js/parseInt (second m) 10))))\n (keys (:marks (current))))]\n (keyword (str \"a\" (inc (if (seq nums) (apply max nums) 0))))))\n\n(defn layer\n \"A layer of the patch, over or under its boxes, shown in the patch view and/or the presentation:\n (layer :notes) · (layer :viz {:z :under :show #{:present}}) · (layer :viz nil) removes it, with its marks.\"\n ([id] (layer id {}))\n ([id opts]\n (when-not (keyword? id) (fail \"A layer is named with a keyword: (layer :notes)\"))\n (if (nil? opts)\n (dispatch! [:layer id nil])\n (dispatch! [:layer id (merge (or (get-in (current) [:layers id]) layer-default) opts)]))\n id))\n\n(defn mark\n \"An annotation on a layer. Its points are anchored to a box ([:b4 dx dy] from its top-left corner) or to\n the paper ([:patch x y]): (mark :notes :a1 {:kind :arrow :pts [[:b1 120 10] [:b4 -6 10]]}) ·\n (mark :notes {:kind :text :at [:patch 300 40] :txt \\\"breathe\\\"}) · kinds :line (a stroke), :arrow, :text, :image ({:at … :src \\\"data:image/jpeg;base64,…\\\" :w :h}, at most 48 KB: a frame kept from a room).\"\n ([layer-id m] (mark layer-id (next-mark-id) m))\n ([layer-id id m]\n (when-not (keyword? layer-id) (fail \"Which layer? (mark :notes …)\"))\n (when-not (keyword? id) (fail \"A mark id is a keyword, e.g. :a3\"))\n (let [m (sane-mark (assoc m :layer layer-id))]\n (when-not m (fail \"A mark is {:kind :line or :arrow :pts [[anchor dx dy] …]} or {:kind :text :at [anchor dx dy] :txt \\\"…\\\"}; an anchor is a box (:b4) or :patch\"))\n (dispatch! [:annot id m])\n id)))\n\n(defn unmark \"Erases marks: (unmark :a3) · (unmark :a3 :a4).\" [& ids] (doseq [id ids] (dispatch! [:annot id nil])) :ok)\n\n(defn move-mark\n \"Moves a mark by dx dy: (move-mark :a3 20 -10). Each point keeps its anchor — a point anchored to a box\n still follows it, from a little further — and a point on the paper moves on the paper.\"\n [id dx dy]\n (let [m (or (get-in (current) [:marks id]) (fail (str \"There is no mark \" id)))]\n (when-not (and (number? dx) (number? dy)) (fail \"dx and dy are numbers\"))\n (dispatch! [:annot id (shift-mark m dx dy)])\n id))\n\n(defn project\n \"Draws the view of a box again on a layer, at another size: (project :b9 :viz [40 40 800 480]) ·\n (unproject :b9). The box keeps its own place; the projection is drawn from what it shows.\"\n [id layer-id [x y w h :as rect]]\n (need-box id)\n (when-not (keyword? layer-id) (fail \"Which layer? (project :b9 :viz [x y w h])\"))\n (when-not (and (sequential? rect) (= 4 (count rect)) (every? number? rect)) (fail \"Where: [x y width height]\"))\n (when-not (own-view? (need-box id)) (fail (str id \" has no view of its own to project (a component drawn with shapes)\")))\n (dispatch! [:project id {:layer layer-id :rect (vec rect)}])\n id)\n\n(defn unproject [id] (dispatch! [:project id nil]) :ok)\n\n(defn move-by\n \"Moves several boxes together: (move-by [:b1 :b2 :b5] 40 0).\"\n [ids dx dy] (shift-ids ids dx dy :move))\n\n(declare child-dims)\n\n(defn present\n \"Shows a box in presentation (and in the panel of its sub-patch) at x y; without x y, next to the others.\"\n ([id]\n (need-box id)\n (let [p (current)\n right (for [[k b] (:boxes p) :let [[x _] (:present b)] :when (and x (not= k id))]\n (+ x (first (child-dims b))))]\n (present id (if (seq right) (+ 8 (apply max right)) 0) 0)))\n ([id x y]\n (need-box id)\n (dispatch! [:present id (js/Math.round x) (js/Math.round y)])\n [x y]))\n\n(def size-min [220 110])\n(def size-max [2400 1600])\n\n(defn resizable?\n \"Boxes drawn with a size of their own: a canvas, a freqt, a score (a freqt or a tree shown as a score)\n and an html box.\"\n [b] (contains? #{:canvas :score :html} (display-of b)))\n\n(defn resize\n \"Gives a canvas, freqt or score box a size of its own, as one event: (resize :b3 640 300). A score keeps\n the height of its notation, and its width reflows it. (resize :b3) brings back its default size.\"\n ([id]\n (need-box id)\n (dispatch! [:size id nil])\n :default)\n ([id w h]\n (let [b (need-box id)]\n (when-not (resizable? b) (fail (str id \" is not drawn with a size of its own (a canvas, a freqt, a score or an html box is)\")))\n (when-not (and (number? w) (number? h)) (fail \"A size is a width and a height: (resize :b3 640 300)\"))\n (let [[w0 h0] size-min [w1 h1] size-max\n w (js/Math.round (max w0 (min w1 w))) h (js/Math.round (max h0 (min h1 h)))]\n (dispatch! [:size id w h])\n [w h]))))\n\n(defn present-in-place\n \"Shows boxes in presentation where they are in the patch, as one event (issue #42): (present-in-place :b3 :b4).\"\n [& ids]\n (when (empty? ids) (fail \"Which boxes? (present-in-place :b3 :b4)\"))\n (let [evs (vec (for [id (distinct ids) :let [b (need-box id)]] [:present id (js/Math.round (:x b)) (js/Math.round (:y b))]))]\n (dispatch! (if (= 1 (count evs)) (first evs) [:batch evs]))\n (vec (distinct ids))))\n\n(defn unpresent \"Takes a box out of presentation.\" [id] (need-box id) (dispatch! [:present id nil]) :ok)\n\n(defn present-by\n \"Moves several presented boxes together in presentation: (present-by [:b1 :b5] 0 24).\"\n [ids dx dy] (shift-ids ids dx dy :present))\n\n(declare box-num box-num-e)\n\n;; canvases: each canvas box (or its score view) keeps a graphic buffer of frequency × time;\n;; its events arrive wrapped in [:in box event]\n\n(defn music? [b] (contains? music-classes (klass (:text b))))\n\n(defn tree-box? [b] (= \"tree\" (klass (:text b))))\n\n(defn need-canvas [id]\n (let [b (need-box id)]\n (when-not (or (music? b) (tree-box? b)) (fail (str id \" is not a canvas (nor a freqt, a score or a tree)\")))\n b))\n\n;; a tree box seen as a canvas (discussion #92): its notes as strokes, computed once per tree\n(defonce tree-views (atom {})) ; tree → view, for the last trees drawn\n\n(defn tree-view [t]\n (or (get @tree-views t)\n (let [v (tc/view-data t)]\n (swap! tree-views (fn [m] (assoc (if (> (count m) 32) {} m) t v)))\n v)))\n\n(defn canvas-data\n \"The buffer of a canvas box, or the empty one of its class (generic canvas or freqt); for a tree box,\n its notes as the strokes of a freqt (kairotic.treecanvas).\"\n [b] (if (tree-box? b)\n (tree-view (mtb/tree-of (:data b)))\n (or (:data b) (:empty (comp/model-of b)) cv/empty)))\n\n(defn canvas-dispatch!\n \"A canvas event for a box: as it is for a canvas or freqt; for a tree box, as the edits of its tree that\n make it (kairotic.treecanvas/edit-ops; opts {:free true}: ⌥, out of the measures).\"\n ([id ev] (canvas-dispatch! id ev {}))\n ([id ev opts]\n (let [b (need-box id)]\n (if (tree-box? b)\n (let [t (mtb/tree-of (:data b))\n ops (try (tc/edit-ops t ev opts) (catch :default e (fail (.-message e))))]\n (when (seq ops)\n (let [t2 (try (reduce mt/apply-op t ops) (catch :default e (fail (.-message e))))]\n (when-let [ps (seq (mt/errors t2))] (fail (first ps)))\n (dispatch! [:in id [:edit (vec ops)]]))))\n (dispatch! [:in id ev])))))\n\n;; ───── musical trees shown live (Study 19) ─────\n;; A canvas, freqt or score that receives a tree (kairotic.mt) shows it over its buffer, without\n;; touching the history; (keep! :bN) writes it into the buffer, as one event.\n\n(defonce live-trees (atom {})) ; engine id → tree\n;; trees kept (keep!) or put away (unlive!): the engine still remembers them as the last thing the box\n;; received, so they are not shown again until a different tree arrives\n(defonce dismissed-trees (atom {})) ; engine id → tree\n\n(defn live-tree [id] (get @live-trees (fid id)))\n\n(defn shown-data\n \"What a canvas or freqt draws: its buffer, or the tree it received (with the buffer's grids).\"\n [id b]\n (let [d (canvas-data b)]\n (if-let [t (live-tree id)]\n (try (if (cv/generic? d)\n (let [x (mt/->canvas t)] (assoc d :strokes (:strokes x) :ax (:ax x)))\n (assoc d :strokes (:strokes (mt/->strokes t))))\n (catch :default _ d))\n d)))\n\n(defn box-data\n \"The buffer of a canvas: {:strokes {:t1 {:pts [[x y] ...]}} :ax axes :gx grid :gy grid or tuning}.\"\n [id] (canvas-data (need-canvas id)))\n\n(defn need-stroke [id tid]\n (or (get-in (box-data id) [:strokes tid]) (fail (str id \" has no stroke \" tid))))\n\n(defn need-pitch [a]\n (or (sc/pitch a) (fail (str \"I do not understand the pitch \" (pr-str a) \". Use 60, \\\"c4\\\", \\\"f#3\\\" or \\\"bb2\\\".\"))))\n\n(defn need-pts\n ([pts] (need-pts cv/empty pts))\n ([d pts]\n (or (cv/sane-pts-for d pts)\n (fail (if (cv/generic? d)\n \"A stroke is at least two different points [x y], e.g. [[0 0] [8 1]]\"\n \"A stroke is at least two points [t hz] with increasing times, e.g. [[0 440] [1 440]]\")))))\n\n(defn need-freqt [id]\n (when (cv/generic? (box-data id)) (fail (str id \" is a generic canvas: notes, degrees and tunings belong to a freqt\")))\n id)\n\n(defn stroke\n \"Draws (or rewrites) a stroke: (stroke :b1 [[0 440] [1 440]]) or (stroke :b1 :t4 [[0 440] [2 660]]), and\n with how it looks: (stroke :b1 :t4 [[0 440] [2 660]] {:w 2 :pan -0.5 :tex :dash :tone :kairos}).\"\n ([id pts] (stroke id (cv/next-id (box-data id)) pts))\n ([id tid pts] (stroke id tid pts nil))\n ;; the fourth argument is how it looks (a map), or true / :free: drawn freehand (⌥), so that in a\n ;; measured tree box the note goes to its free voice\n ([id tid pts x]\n (need-canvas id)\n (when-not (keyword? tid) (fail \"A stroke id is a keyword, e.g. :t3\"))\n (let [look (when (map? x) x) free? (or (true? x) (= x :free))]\n (canvas-dispatch! id (if (cv/sane-look look)\n [:stroke tid (need-pts (box-data id) pts) look]\n [:stroke tid (need-pts (box-data id) pts)])\n (if free? {:free true} {})))\n tid))\n\n(defn note\n \"A horizontal stroke: (note :b1 t \\\"c4\\\" dur), with the pitch as MIDI or by name (a4 = 440 Hz).\"\n [id t pch dur]\n (need-freqt id)\n (when-not (and (number? t) (number? dur) (>= t 0) (pos? dur)) (fail \"A note is (note box t pitch duration)\"))\n (let [f (cv/round-to (cv/midi->hz (need-pitch pch)) 3)]\n (stroke id [[t f] [(+ t dur) f]])))\n\n(defn degree\n \"A horizontal stroke on degree n of the canvas tuning (0 = the reference).\"\n [id t n dur]\n (let [gy (or (:gy (box-data id)) (fail (str id \" has no tuning: use (tuning \" id \" \\\"12-tet\\\")\")))\n f (cv/round-to (cv/degree->hz gy n) 3)]\n (when-not (and (number? t) (number? dur) (>= t 0) (pos? dur)) (fail \"A degree is (degree box t n duration)\"))\n (stroke id [[t f] [(+ t dur) f]])))\n\n(defn melody\n \"A line of notes from t0 (by default, where the canvas ends): \\\"c4/1 d4/.5 r/1 c4+e4/2\\\".\"\n ([id txt] (melody id txt (cv/end-t (box-data id))))\n ([id txt t0]\n (need-canvas id)\n (need-freqt id)\n (doall (for [[t a d] (sc/parse-melody txt t0)] (note id t a d)))))\n\n(defn move-stroke\n \"Shifts a stroke by dx along X and dy along Y (in cents on a freqt or a log axis). In a measured tree,\n :free (⌥) takes the note out of the measures.\"\n ([id tid dt dc] (move-stroke id tid dt dc nil))\n ([id tid dt dc free]\n (need-stroke id tid)\n (canvas-dispatch! id [:move tid dt dc] (if free {:free true} {}))\n tid))\n\n(defn stretch\n \"Lengthens (k > 1) or shortens (k < 1) a stroke in time, from its start.\"\n [id tid k]\n (need-stroke id tid)\n (when-not (and (number? k) (pos? k)) (fail \"The stretch factor is a positive number\"))\n (canvas-dispatch! id [:stretch tid k])\n tid)\n\n(defn erase-stroke [id tid] (need-stroke id tid) (canvas-dispatch! id [:erase tid]) :ok)\n\n(defn canvas-edit!\n \"Several edits of a canvas as one event: (canvas-edit! :b1 [[:stroke :t5 [[0 1] [1 2]]] [:erase :t2]]).\n What the messages on the left inlet of a canvas become (issue #26).\"\n [id evs]\n (need-canvas id)\n (when-not (and (sequential? evs) (every? vector? evs)) (fail \"The edits are a vector of events: [[:stroke :t1 pts] …]\"))\n (canvas-dispatch! id [:batch (vec evs)])\n (count evs))\n\n(defn clear [id] (need-canvas id) (canvas-dispatch! id [:clear]) :ok)\n\n(defn grid-x\n \"Time grid: (grid-x :b1 0.25 [4]) · (grid-x :b1 0.5 \\\"3+3+2\\\") · (grid-x :b1 nil).\n The step quantizes while drawing; the cycles group (like bars, simple or additive).\"\n ([id gx] (if (nil? gx) (do (need-canvas id) (canvas-dispatch! id [:grid-x nil]) :no-grid) (fail \"Use (grid-x box step cycles) or nil\")))\n ([id step-size cycles]\n (need-canvas id)\n (let [gx (cv/sane-gx {:step step-size :cycles cycles})]\n (when-not gx (fail \"The step is a positive number\"))\n (canvas-dispatch! id [:grid-x gx])\n gx)))\n\n(defn tunings\n \"Tunings available by name (besides any Scala .scl pasted as text).\"\n [] (vec (sort (keys cv/tunings))))\n\n(defn tuning\n \"Frequency grid: a name from (tunings), the text of a .scl or {:name :cents}, and the\n reference frequency of degree 0 (by default C4 = 261.63 Hz). With nil, continuous frequency.\"\n ([id tun] (tuning id tun cv/default-ref))\n ([id tun ref]\n (need-canvas id)\n (need-freqt id)\n (if (nil? tun)\n (do (canvas-dispatch! id [:tuning nil]) :continuous)\n (let [base (cond (map? tun) tun\n (and (string? tun) (get cv/tunings (str/lower-case tun))) (get cv/tunings (str/lower-case tun))\n (string? tun) (cv/parse-scl tun)\n :else (fail \"Use a name from (tunings), the text of a .scl or a map {:name :cents}\"))\n gy (cv/sane-gy (assoc base :ref ref))]\n (when-not gy (fail \"That tuning is not valid\"))\n (canvas-dispatch! id [:tuning gy])\n (select-keys gy [:name :ref])))))\n\n(defn read-at\n \"What a canvas holds at x = v (or along :y): [[stroke value] ...], every crossing.\"\n ([id v] (read-at id :x v))\n ([id axis v] (cv/read-along (box-data id) axis v)))\n\n(defn axis\n \"Range and scale of an axis of a generic canvas: (axis :b1 :y -1 1) · (axis :b1 :x 20 20000 :log).\"\n [id k lo hi & [scale]]\n (need-canvas id)\n (when-not (cv/generic? (box-data id)) (fail (str id \" is a freqt: its axes are time and frequency\")))\n (when-not (#{:x :y} k) (fail \"The axis is :x or :y\"))\n (let [ax (assoc (:ax (box-data id)) k {:lo lo :hi hi :log (= scale :log)})\n ok (cv/sane-ax ax)]\n (when-not (= (get ok k) (get ax k)) (fail \"An axis goes from lo to hi (lo < hi; both positive if :log)\"))\n (dispatch! [:in id [:axis ok]])\n (get ok k)))\n\n(defn grid-y\n \"A regular grid on Y (values snap to it while drawing): (grid-y :b1 0.25) · (grid-y :b1 nil).\"\n [id step-size]\n (need-canvas id)\n (if (nil? step-size)\n (do (dispatch! [:in id [:grid-y nil]]) :no-grid)\n (let [gy (cv/sane-gy {:step step-size})]\n (when-not gy (fail \"The step is a positive number\"))\n (dispatch! [:in id [:grid-y gy]])\n gy)))\n\n;; code boxes: their source is data of the work; each tab compiles it locally\n\n(declare render-all!)\n\n(defn need-code-box [id]\n (let [b (need-box id) d (box-def b)]\n (when-not (= :code (:display d)) (fail (str id \" is not a code box (faust~, script…)\")))\n d))\n\n(declare tree!)\n\n(defn code-source!\n \"Writes the source of a code box (as one event).\"\n [id source]\n (let [d (need-code-box id)]\n (when-not (string? source) (fail \"The source is a string\"))\n (dispatch! [:in id [:source source]])\n (:status (cbox/compiled (:language d) source))))\n\n(defn data-source!\n \"Writes the data of a box from its text, as its model reads it (a canvas, freqt or score: the EDN of its\n buffer). What changed, and only that, is one event of the history (discussion #30).\"\n [id text]\n (let [b (need-box id) m (comp/model-of b)]\n (when-not (and (fn? (:read m)) (fn? (:diff m))) (fail (str id \" has no data that can be written as text\")))\n (when-not (string? text) (fail \"The text is a string\"))\n (let [d (or (:data b) (:empty m))\n d2 (try ((:read m) d text) (catch :default e (fail (.-message e))))\n evs ((:diff m) d d2)]\n (if (seq evs)\n (do (dispatch! [:in id [:batch (vec evs)]])\n (str (count evs) (if (= 1 (count evs)) \" edit\" \" edits\")))\n :unchanged))))\n\n(def keep-limit\n \"How long the code of a kept value may be (characters): it travels in the history, in links and to\n everyone in a room.\"\n 65536)\n\n(defn code\n \"Writes the source of a code box: (code :b7 \\\"process = os.osc(440) * 0.1;\\\"). For a tree box the text\n is read as a tree, and what changed becomes edits of its nodes (tree!). For a canvas, freqt or score\n it is the EDN of its buffer ((source :bN) gives it), and what changed becomes edits of its strokes.\"\n [id source]\n (let [b (need-box id)]\n (cond\n (= \"tree\" (klass (:text b)))\n (do (when-not (string? source) (fail \"The source is a string\"))\n (tree! id (try (mt/read-tree source) (catch :default e (fail (str \"That is not EDN: \" (.-message e)))))))\n (fn? (:read (comp/model-of b))) (data-source! id source)\n :else (code-source! id source))))\n\n(defn source\n \"The source of a code box, or the data of a canvas, freqt or score as EDN text.\"\n [id]\n (or (comp/source-of (need-box id)) (fail (str id \" has no code (faust~, script, tree…) nor a buffer (canvas, freqt, score)\"))))\n\n(defn view\n \"How a box is shown, among the views of its class: (view :b2 :roll) shows a tree as a piano roll and\n (view :b2 :score) as a score again; a freqt can be a :canvas or a :score; :next is the next one. Its\n data does not change, and its text opens from { } in its header (or (source :b2)).\"\n [id k]\n (let [b (need-box id) vs (vec (comp/views-of b))]\n (when (< (count vs) 2) (fail (str id \" has one view only\")))\n (when (and (= k :code) (tree-box? b))\n (fail (str \"A tree is seen as a score or a roll; its code opens from { } in its header, in the code window\")))\n (let [cur (view-of b)\n k (comp/view-name b k)\n k (if (= k :next)\n (nth vs (mod (inc (or (first (keep-indexed (fn [i v] (when (= v cur) i)) vs)) 0)) (count vs)))\n k)]\n (when-not (or (nil? k) (some #{k} vs))\n (fail (str id \" can be shown as \" (str/join \" or \" (map pr-str vs)))))\n (when-not (= (or k (first vs)) cur)\n (dispatch! [:view id (when-not (= k (first vs)) k)]))\n (or k (first vs)))))\n\n;; musical trees (Study 19): mt/… are the functions on trees (mt/transpose, mt/events, mt/pp …)\n;; A tree box keeps its tree and its history is made of node edits (Study 20): tree! writes the\n;; difference with what it had; tree-edit! writes exact edits.\n\n(defn need-tree-box [id]\n (let [b (need-box id)]\n (when-not (= \"tree\" (klass (:text b))) (fail (str id \" is not a tree box\")))\n b))\n\n(defn tree-data \"The tree a tree box holds (as written).\" [id] (mtb/tree-of (:data (need-tree-box id))))\n\n(defn tree!\n \"Writes a tree into a tree box: (tree! :b3 [:voice \\\"c4/1 e4 g4\\\"]). What changes is written as edits of\n its nodes, in one event of the history.\"\n [id t]\n (need-tree-box id)\n (when-let [ps (seq (mt/errors t))] (fail (first ps)))\n (doseq [w (mt/warnings t)] (repl-print! \"out\" (esc (str \"; ⚠ \" w))))\n (let [old (tree-data id)\n ops (if (some? old) (mt/diff old t) [[:set [] t]])]\n (if (seq ops)\n (do (dispatch! [:in id [:edit ops]])\n (str (count ops) (if (= 1 (count ops)) \" edit\" \" edits\") \" · \" (mt/summary t)))\n :unchanged)))\n\n(defn tree-edit!\n \"Edits the nodes of a tree box, as one event: (tree-edit! :b2 [:attrs [0 1 2] {:pitch \\\"d4\\\" :dur 1}]).\n Edits: [:set path x] · [:attrs path {…}] · [:insert path x] · [:remove path]; a path is the list of child\n indices from the root (attributes are not counted).\"\n [id & ops]\n (need-tree-box id)\n (let [t (tree-data id)\n t2 (try (reduce mt/apply-op t ops) (catch :default e (fail (.-message e))))]\n (when-let [ps (seq (mt/errors t2))] (fail (first ps)))\n (doseq [w (mt/warnings t2)] (repl-print! \"out\" (esc (str \"; ⚠ \" w))))\n (dispatch! [:in id [:edit (vec ops)]])\n (mt/summary t2)))\n\n(defn node-at \"The node of a tree box at a path: (node-at :b2 [0 1]).\" [id path] (mt/node-at (tree-data id) path))\n\n(defn as-tree\n \"A box as a tree: a tree box, the tree a canvas or score is showing, or the strokes of its buffer.\"\n [id]\n (let [b (need-box id)]\n (cond\n (= \"tree\" (klass (:text b))) (mt/expand (mtb/tree-of (:data b)))\n (live-tree id) (live-tree id)\n ;; a buffer kept from a tree, unchanged since: the tree itself, not an approximation of its strokes\n (and (:recipe b) (not (:stale (:recipe b)))) (:tree (:recipe b))\n (music? b) (mt/<-strokes (canvas-data b))\n :else (fail (str id \" is not a tree, a canvas, a freqt or a score\")))))\n\n(defn quantize\n \"What a box's score shows, as a measured tree: a freqt's strokes quantized into measures (its meter\n from its bar grid), a tree without measures quantized, a measured tree as it is. Options:\n (quantize :b1 {:meter \\\"6/8\\\" :divs [1 2 3 4 6] :merge [] :grace false}); see kairotic.quantize.\"\n ([id] (quantize id {}))\n ([id opts]\n (let [b (need-box id)\n opts (if (map? opts) opts (fail \"The options are a map: {:meter \\\"3/4\\\" :divs [1 2 3 4]}\"))]\n (try\n (cond\n (or (= \"tree\" (klass (:text b))) (live-tree id) (and (:recipe b) (not (:stale (:recipe b)))))\n (let [t (as-tree id)] (if (mt/measured? t) t (qz/quantize-tree t opts)))\n (and (music? b) (not (cv/generic? (canvas-data b)))) (qz/quantize (canvas-data b) (merge (:quant (canvas-data b)) opts))\n :else (fail (str id \" is not a tree or a freqt\")))\n (catch :default e (fail (.-message e)))))))\n\n(defn- freqt-data\n \"The buffer of a freqt box (fails for anything else).\"\n [id]\n (let [b (need-box id) d (canvas-data b)]\n (when-not (and (music? b) (not (cv/generic? d))) (fail (str id \" is not a freqt\")))\n d))\n\n(defn- quant-src\n \"What a box's score is quantized from, and where its options are kept: a freqt (its strokes, its\n buffer's :quant) or a tree box without measures (its notes, its root's :quant). {:q :gx :notes\n :quantize (fn [q] tree) :keep! (fn [q])}.\"\n [id]\n (let [b (need-box id)]\n (if (tree-box? b)\n (let [t (or (mtb/tree-of (:data b)) [:voice])\n root (mt/attrs t)]\n (when (mt/measured? t)\n (fail (str id \" is written in measures: its divisions are written. (unquantize! \" id \") makes it free time again\")))\n {:q (:quant root) :gx (:grid root) :notes (qz/tree-notes t)\n :quantize (fn [q] (qz/quantize-tree (mt/with-attrs t (dissoc root :quant)) (or q {})))\n :keep! (fn [q] (dispatch! [:in id [:edit [[:attrs [] (if (seq q) (assoc root :quant q) (dissoc root :quant))]]]]))})\n (let [d (freqt-data id)]\n {:q (:quant d) :gx (:gx d) :notes (qz/strokes->notes d)\n :quantize (fn [q] (qz/quantize d q))\n :keep! (fn [q] (dispatch! [:in id [:quantize q]]))}))))\n\n(defn quant\n \"How the score of a freqt (or of a tree box without measures) is quantized, kept in its data (one event\n of the history): (quant :b1 {:meter \\\"6/8\\\" :divs [1 2 3 4]}); (quant :b1) gives them; (quant :b1 nil)\n goes back to the defaults.\"\n ([id] (:q (quant-src id)))\n ([id opts]\n (let [src (quant-src id)]\n (when-not (or (nil? opts) (map? opts)) (fail \"The options are a map: {:meter \\\"6/8\\\" :divs [1 2 3 4]}, or nil\"))\n (try (qz/options opts nil) (catch :default e (fail (.-message e))))\n ((:keep! src) opts)\n (or opts :defaults))))\n\n(defn track!\n \"Finds the beats of a freqt (or a tree box without measures) played freely, in seconds or at any tempo\n (kairotic.tempo, issue #106), and keeps the time map in its :quant (one event of the history), so that its\n score is quantized through them and stays as it is while it is edited: (track! :b1), or with options\n for the quantizer, (track! :b1 {:meter \\\"6/8\\\"}). (quant :b1 {:time :track}) finds them each time\n instead; (track! :b1 nil) forgets them. → {:tempo bpm :beats n}.\"\n ([id] (track! id {}))\n ([id opts]\n (let [{:keys [q gx notes keep!]} (quant-src id)]\n (if (nil? opts)\n (do (keep! (not-empty (dissoc q :time))) :forgotten)\n (let [q2 (merge (dissoc q :time) opts)\n m (qz/time-map-of notes (qz/options (assoc q2 :time :track) gx))]\n (when-not m (fail (str id \": too few notes to find a beat in\")))\n (keep! (assoc q2 :time m))\n {:tempo (js/Math.round (tm/tempo-of-map m)) :beats (count m)})))))\n\n(defn enharmonic!\n \"Writes the note of a quantized score (a freqt's, or a free tree box's) that starts at beat t with MIDI\n pitch m another way (c#4 → db4 → b##3 → c#4 …), or with the name given; kept with its options (:quant\n :spell), one event of the history. (enharmonic! :b1 2 61), (enharmonic! :b1 2 61 \\\"db4\\\"),\n (enharmonic! :b1 2 61 nil): chosen again by the key.\"\n ([id t m] (enharmonic! id t m ::next))\n ([id t m nm]\n (let [{:keys [q quantize keep!]} (quant-src id) m (js/Math.round m)\n near? (fn [[[bt p] _]] (and (< (js/Math.abs (- bt t)) 1e-4) (= p m)))\n cur (or (some (fn [kv] (when (near? kv) (second kv))) (:spell q))\n (some (fn [e] (when (and (< (js/Math.abs (- (:t e) t)) 1e-4) (= m (js/Math.round (:pitch e)))) (:name e)))\n (mt/notes (quantize q))))\n names (mapv sp/->name (sp/spellings m))\n nm (cond (= nm ::next) (get names (mod (inc (max -1 (.indexOf names cur))) (count names)))\n (nil? nm) nil\n :else (or (some-> (sp/parse nm) (as-> w (when (= m (sp/->midi w)) (sp/->name w))))\n (fail (str nm \" does not sound \" (mt/pitch-name m)))))\n spell (cond-> (into {} (remove near? (:spell q))) nm (assoc [t m] nm))]\n (keep! (not-empty (cond-> (dissoc q :spell) (seq spell) (assoc :spell spell))))\n nm)))\n\n(defn divisions\n \"The ways the beat that holds beat t of a quantized score (a freqt's, a free tree box's) can be\n divided, the current one first: n (n parts), [n1 n2] (in halves), [:merge n] (with the next beat).\"\n [id t]\n (let [{:keys [q gx notes]} (quant-src id)]\n (qz/choices notes (qz/options q gx) t)))\n\n(defn division!\n \"Divides the beat that holds beat t of a quantized score the next way (see divisions), or the way\n given; the choice is kept with its options (:quant :fix), one event of the history. (division! :b1 2.5),\n (division! :b1 2.5 3), (division! :b1 2.5 nil) lets the quantizer choose again.\"\n ([id t]\n (let [{:keys [q gx notes keep!]} (quant-src id)\n {:keys [choice opts]} (qz/next-choice notes q gx t)]\n (keep! opts)\n choice))\n ([id t c]\n (let [{:keys [q gx notes keep!]} (quant-src id)\n {:keys [s pair]} (qz/choices notes (qz/options q gx) t)\n c (when (some? c) (or (qz/sane-choice c) (fail \"A division is n, [n1 n2] or [:merge n]\")))\n near? (fn [a b] (and a b (< (js/Math.abs (- a b)) 1e-6)))\n fix (into {} (remove (fn [[x _]] (or (near? x s) (near? x pair))) (:fix q)))\n fix (if c (assoc fix (if (and (vector? c) (= :merge (first c))) (or pair s) s) c) fix)]\n (keep! (not-empty (cond-> (dissoc q :fix) (seq fix) (assoc :fix fix))))\n c)))\n\n(defn quantize!\n \"Writes a tree box's free time in measures, as its score shows them (with its :quant, and opts): one\n event of the history (undo goes back). Its key, tuning, grid and name stay on the tree.\"\n ([id] (quantize! id {}))\n ([id opts]\n (let [b (need-box id)]\n (when-not (tree-box? b) (fail (str id \" is not a tree box: (to-tree! \" id \") makes one from a freqt\")))\n (let [t (mtb/tree-of (:data b)) root (mt/attrs t)]\n (when (mt/measured? t) (fail (str id \" is already written in measures\")))\n (let [q (try (qz/quantize-tree t opts) (catch :default e (fail (.-message e))))\n q (mt/update-attrs q merge (select-keys root [:name :key :tuning :grid :tempo :accidentals]))]\n (dispatch! [:in id [:edit [[:set [] q]]]])\n (mt/summary q))))))\n\n(defn unquantize!\n \"Writes a tree box's notes in free time ([:voice [:par [:note {:at …}] …]]): one event of the history.\"\n [id]\n (let [b (need-box id)]\n (when-not (tree-box? b) (fail (str id \" is not a tree box\")))\n (let [f (tc/free-form (mtb/tree-of (:data b)))]\n (dispatch! [:in id [:edit [[:set [] f]]]])\n (mt/summary f))))\n\n\n\n(defn to-tree!\n \"A new tree box beside a freqt with its strokes as notes in free time (and its grid, tuning and\n quantization as the tree's), shown as a roll: the freqt's drawing, now as a tree.\"\n [id]\n (let [b (need-box id) d (freqt-data id)\n ns (qz/strokes->notes d)\n t [:voice (cond-> {} (:gx d) (assoc :grid (:gx d)) (:gy d) (assoc :tuning (:gy d)) (:quant d) (assoc :quant (:quant d)))\n (into [:par] (for [n ns] [:note (assoc (:attrs n) :at (cv/round-to (:on n) 4) :dur (cv/round-to (- (:off n) (:on n)) 4))]))]\n [x y] [(:x b) (:y b)]\n nid (box \"tree\" (+ (or x 0) 40) (+ (or y 0) 40))]\n (tree! nid t)\n (view nid :roll)\n nid))\n\n(declare patch->code)\n\n(defn tree->buffer\n \"The buffer d with the strokes of tree t (and, in a generic canvas, axes that fit it).\"\n [d t]\n (if (cv/generic? d)\n (let [x (mt/->canvas t)] (assoc d :strokes (:strokes x) :ax (:ax x)))\n (assoc d :strokes (:strokes (mt/->strokes t)))))\n\n(defn without-meta\n \"x without metadata (a tree remembers where it was written; its recipe keeps only the tree).\"\n [x]\n (cond (map? x) (into {} (map (fn [[k v]] [(without-meta k) (without-meta v)]) x))\n (vector? x) (mapv without-meta x)\n (seq? x) (apply list (map without-meta x))\n :else x))\n\n(defn upstream-of\n \"The boxes of patch p whose output reaches box id, through any chain of lines.\"\n [p id]\n (loop [front #{id} seen #{}]\n (let [new (set (for [[a _ b _] (:lines p) :when (and (front b) (not= a id) (not (seen a)))] a))]\n (if (empty? new) seen (recur new (into seen new))))))\n\n(defn recipe-for\n \"The recipe of tree t arriving at box id of the current patch: the tree, the boxes and lines upstream\n as code (their own recipes left out), and the box it came from.\"\n [id t]\n (let [p (current)\n up (upstream-of p id)\n sub {:boxes (into (sorted-map) (for [k up :let [b (get-in p [:boxes k])] :when b] [k (dissoc b :recipe)]))\n :lines (vec (filter (fn [[a _ b _]] (and (up a) (or (up b) (= b id)))) (:lines p)))}]\n (cond-> {:tree (without-meta t)}\n (seq up) (assoc :calls (patch->code sub))\n (some (fn [[a _ b _]] (when (= b id) a)) (:lines p)) (assoc :from (some (fn [[a _ b _]] (when (= b id) a)) (:lines p))))))\n\n(defn keep!\n \"Keeps what a box is showing, as its data, in one event of the history.\n (keep! :b5): the tree a canvas, freqt or score is showing, written into its buffer with the recipe that\n made it beside it (the tree and the boxes upstream).\n (keep! :b5 d): the whole data of a box that keeps what it found (a box with :tasks and a :model, such as\n fetch: (keep! :b5 {:url \\\"https://…\\\" :json {…}})); (keep! :b5 nil) empties it.\"\n ([id]\n (let [b (need-canvas id) t (or (live-tree id) (fail (str id \" is not showing a tree: send it one first\")))]\n (dispatch! [:kept id (tree->buffer (canvas-data b) t) (recipe-for id t)])\n (swap! dismissed-trees assoc (fid id) t)\n (swap! live-trees dissoc (fid id))\n (mt/summary t)))\n ([id d]\n (let [b (need-box id) m (comp/model-of b)]\n (when-not m (fail (str id \" keeps no data\")))\n (when-not (or (nil? d) (map? d)) (fail \"The data of a box is a map, or nil to empty it\"))\n (if (= (when d ((:load m) d)) (:data b))\n :unchanged\n (do (dispatch! [:data id d]) :kept)))))\n\n(defn values!\n \"Keeps values of an html box in its data, in one event of the history (issue #146), as a knob keeps its\n value in its text: (values! :b5 {:freq 440 :name \\\"a\\\"}); nil forgets one. Its elements named so show\n them, and the work keeps them.\"\n [id m]\n (let [b (need-box id)]\n (when-not (= :html (display-of b)) (fail (str id \" is not an html box\")))\n (when-not (map? m) (fail \"The values are a map: (values! :b5 {:freq 440})\"))\n (let [vs (hic/clean-values m) old (hic/clean-values (get-in b [:data :values]))]\n (when (empty? vs) (fail \"No value that can be kept: names are words, values numbers, texts, keywords or true/false\"))\n (if (every? (fn [[k v]] (if (nil? v) (not (contains? old k)) (= v (get old k)))) vs)\n :unchanged\n (do (dispatch! [:in id [:values vs]]) :kept)))))\n\n(defn recipe\n \"The recipe kept beside a buffer: (recipe :b5) → {:tree … :calls … :from … :stale true if the buffer\n changed since}. (recipe :b5 r) sets it (the code of a work does), (recipe :b5 nil) removes it.\"\n ([id] (:recipe (need-box id)))\n ([id r] (need-box id) (dispatch! [:recipe id r]) (some? (sane-recipe r))))\n\n(defn remake!\n \"Writes the tree of a buffer's recipe back into the buffer (one event): what keep! wrote, without the\n changes made since.\"\n [id]\n (let [b (need-canvas id)\n r (or (:recipe b) (fail (str id \" has no recipe: it was not kept from a tree\")))]\n (dispatch! [:kept id (tree->buffer (canvas-data b) (:tree r)) r])\n (mt/summary (:tree r))))\n\n(defn unlive!\n \"Stops showing the tree a box received: its buffer again.\"\n [id]\n (when-let [t (live-tree id)] (swap! dismissed-trees assoc (fid id) t))\n (swap! live-trees dissoc (fid id))\n :ok)\n\n(defn compilation\n \"How the compilation of a code box went: {:status :error :info}.\"\n [id]\n (let [d (need-code-box id)]\n (select-keys (cbox/compiled (:language d) (source id)) [:status :error :info])))\n\n(defn trust-scripts\n \"Allows (or not) this tab to evaluate the script boxes of the open work. Solo and\n local works always allow it; in a shared room it has to be asked for, because a script runs the\n code of whoever wrote it inside this page.\"\n [on?]\n (reset! cbox/trust (boolean on?))\n (cbox/forget-language! \"clojurescript\")\n (cbox/forget-language! \"component\")\n (cbox/forget-language! \"pattern\")\n (render-all!)\n (boolean on?))\n\n(defn components\n \"The available box classes.\"\n [] (mapv first (comp/listing)))\n\n(defn help\n \"What a box class does: (help \\\"ramp\\\").\"\n [cls-name]\n (let [d (or (comp/lookup (str cls-name))\n (when (seq (hlp/of (str cls-name))) (assoc (hlp/of (str cls-name)) :class (str cls-name)))\n (fail (str \"There is no class \" (pr-str cls-name) \"; see (components)\")))]\n (show-help! (:class d))\n (cond-> {:class (:class d) :doc (:doc d)}\n (:usage d) (assoc :usage (:usage d))\n (vector? (:io d)) (assoc :inlets (first (:io d)) :outlets (second (:io d))))))\n\n(defn patch [] (current))\n\n(defn boxes\n ([] (keys (:boxes (current))))\n ([s] (keep (fn [[id b]] (when (str/includes? (:text b) s) id)) (:boxes (current)))))\n\n;; navigating the history (creates no events: it only changes where you are)\n\n(defn here []\n (let [p (norm (:pos @world))]\n (if p {:segment (first p) :n (second p) :moment (depth-of p)} :no-events)))\n\n(defn stop-follow! [] (when (:follow @ui) (swap! ui assoc :follow nil)))\n\n(defn children-at [nid idx]\n (filter (fn [n] (and (= (:parent n) nid) (= (:at n) idx))) (vals (:nodes @hist))))\n\n(defn leaf? [[nid idx]]\n (and (node nid) (= idx (count (:events (node nid)))) (empty? (children-at nid idx))))\n\n(defn auto-advance!\n \"With front on, moves forward to the newest tip that continues your line.\"\n []\n (let [{:keys [pos auto]} @world]\n (when (and auto pos (not (:follow @ui)))\n (let [p (norm pos) f (front-from p)]\n (when (and f (not= (norm f) p))\n (swap! world assoc :prev-pos p :pos f :jumped-at (js/Date.now)))))))\n\n(defn front\n \"Turns on or off moving forward with anyone's gestures.\"\n [on?]\n (swap! world assoc :auto (boolean on?) :prev-pos nil)\n (when on? (auto-advance!))\n (boolean on?))\n\n(declare show-leave-dialog!)\n\n(defn not-performing!\n \"Travelling in the history leaves the take behind: in Perform, it is asked for first.\"\n [] (when @perf\n (show-leave-dialog!)\n (fail \"You are in Perform: leave it first with (compose), keeping the take or not.\")))\n\n(defn perf-undo!\n \"In Perform, ◀ and Ctrl+Z take back your last changes of the take (and ▶ brings them again).\"\n [k]\n (swap! perf (fn [st]\n (loop [st st k k]\n (let [e (peek (:own st))]\n (if (or (zero? k) (nil? e) (<= (:t e) (or (:cut st) 0)))\n (perf-recompute st)\n (recur (-> st (update :own pop) (update :redo conj e)) (dec k)))))))\n (jam-push!)\n {:take (count (perf-events @perf))})\n\n(defn perf-redo! [k]\n (swap! perf (fn [st]\n (loop [st st k k]\n (let [e (peek (:redo st))]\n (if (or (zero? k) (nil? e))\n (perf-recompute st)\n ;; brought again now: it takes its place at the end of the take\n (recur (-> st (update :redo pop) (update :own conj (assoc e :t (js/Date.now)))) (dec k)))))))\n (jam-push!)\n {:take (count (perf-events @perf))})\n\n(defn goto [nid n]\n (not-performing!)\n (when-not (node nid) (fail (str \"There is no segment \" (pr-str nid))))\n (stop-follow!)\n (let [p (norm [nid n])]\n (swap! world assoc :pos p :auto (leaf? p) :prev-pos nil))\n (here))\n\n(defn rewind\n ([] (rewind 1))\n ([k]\n (if @perf\n (perf-undo! k)\n (do (stop-follow!)\n (swap! world assoc :auto false :prev-pos nil)\n (dotimes [_ k]\n (let [p (norm (:pos @world))]\n (when (and p (pos? (second p)))\n (swap! world assoc :pos (norm [(first p) (dec (second p))])))))\n (here)))))\n\n(defn undo [] (rewind 1))\n\n(defn forward\n ([] (forward 1))\n ([k]\n (if @perf\n (perf-redo! k)\n (do (stop-follow!)\n (swap! world assoc :auto false :prev-pos nil)\n (dotimes [_ k]\n (let [p (norm (:pos @world))]\n (when p\n (let [[nid idx] p n (node nid)]\n (if (< idx (count (:events n)))\n (swap! world assoc :pos [nid (inc idx)])\n (when-let [c (last (sort-by :t (children-at nid idx)))]\n (swap! world assoc :pos [(:id c) 1])))))))\n (here)))))\n\n(defn tip []\n (not-performing!)\n (stop-follow!)\n (when-let [p (norm (:pos @world))] (swap! world assoc :pos (tip-of (first p)) :auto true :prev-pos nil))\n (auto-advance!)\n (here))\n\n(defn merge-from\n \"Brings to where you are the events of the branch that goes through [segment n]. The merge is one more event.\"\n [nid n]\n (not-performing!)\n (when-not (node nid) (fail (str \"There is no segment \" (pr-str nid))))\n (when (#{:connecting :none} (:mode @hist)) (fail \"Open a work before merging.\"))\n (let [src (norm [nid n]) tgt (norm (:pos @world))]\n (when-not tgt (fail \"First place yourself at some point of the history.\"))\n (let [{:keys [error events renamed]} (plan-merge tgt src)]\n (when error (fail error))\n (stop-follow!)\n (let [id (new-node! (first tgt) (second tgt) events src)]\n (swap! world assoc :pos [id (count events)] :auto true :prev-pos nil))\n (cond-> {:events-merged (dec (count events))}\n (seq renamed) (assoc :renamed renamed)))))\n\n(defn simultaneity\n \"Interval (ms) below which two gestures are considered parallel and branch.\"\n ([] (:simul-ms @settings))\n ([ms]\n (when-not (and (number? ms) (<= 0 ms 10000)) (fail \"Use a number of milliseconds between 0 and 10000.\"))\n (swap! settings assoc :simul-ms ms)\n (when (persist?)\n (let [path (work-base)]\n (enqueue! path (fn [] (.update (.doc @dbref path) (clj->js {:simultaneity_ms ms}))))))\n ms))\n\n(defn branches []\n (let [ns (vals (:nodes @hist))\n parents (set (keep :parent ns))]\n {:segments (count ns)\n :tips (count (remove (fn [n] (parents (:id n))) ns))\n :events (reduce + (map (comp count :events) ns))}))\n\n;; ───────────────────────── projections ─────────────────────────\n\n(defn box-num [k] (let [m (re-matches #\"b(\\d+)\" (name k))] (if m (js/parseInt (second m) 10) 1e9)))\n\n(defn patch->code [p]\n (let [ids (sort-by box-num (keys (:boxes p)))]\n (str/join \"\\n\"\n (concat [\";; boxes\"]\n (for [id ids :let [{:keys [text x y]} (get-in p [:boxes id])]]\n (str \"(box \" id \" \" (pr-str text) \" \" x \" \" y \")\"))\n (let [pr (filter (fn [id] (:present (get-in p [:boxes id]))) ids)]\n (when (seq pr)\n (concat [\"\" \";; presentation\"]\n (for [id pr :let [[x y] (get-in p [:boxes id :present])]]\n (str \"(present \" id \" \" x \" \" y \")\")))))\n (let [vw (filter (fn [id] (:view (get-in p [:boxes id]))) ids)]\n (when (seq vw)\n (concat [\"\" \";; views\"]\n (for [id vw] (str \"(view \" id \" \" (pr-str (get-in p [:boxes id :view])) \")\")))))\n ;; the `patch @name` boxes pinned to a point of their line (#117)\n (let [pn (filter (fn [id] (:pin (get-in p [:boxes id]))) ids)]\n (when (seq pn)\n (concat [\"\" \";; pinned lines\"]\n (for [id pn] (str \"(pin-ref \" id \" \" (pr-str (get-in p [:boxes id :pin])) \")\")))))\n (let [sz (filter (fn [id] (:size (get-in p [:boxes id]))) ids)]\n (when (seq sz)\n (concat [\"\" \";; sizes\"]\n (for [id sz :let [[w h] (get-in p [:boxes id :size])]] (str \"(resize \" id \" \" w \" \" h \")\")))))\n (when (seq (:lines p)) [\"\" \";; lines\"])\n (for [[a o b i] (:lines p)]\n (str \"(connect \" a \" \" o \" \" b \" \" i \")\"))\n (mapcat (fn [id]\n (let [b (get-in p [:boxes id])\n ls ((:code (comp/model-of b)) id (:data b))]\n (when (seq ls) (concat [\"\" (str \";; data of \" id)] ls))))\n (filter (fn [id] (let [b (get-in p [:boxes id])] (and (:data b) (:code (comp/model-of b))))) ids))\n ;; layers, their projections and marks\n (when (or (:layers p) (:marks p) (:projections p))\n (concat [\"\" \";; layers\"]\n (for [[id l] (sort-by key (:layers p)) :when (not= l layer-default)]\n (str \"(layer \" id \" \" (pr-str l) \")\"))\n (for [[id pr] (sort-by (comp box-num key) (:projections p))]\n (str \"(project \" id \" \" (:layer pr) \" \" (pr-str (:rect pr)) \")\"))\n (for [[id m] (:marks p)]\n (str \"(mark \" (:layer m) \" \" id \" \" (pr-str (dissoc m :layer)) \")\"))))\n ;; beside the data, the recipe that made it (keep!)\n (mapcat (fn [id]\n (when-let [r (get-in p [:boxes id :recipe])]\n [\"\" (str \";; recipe of \" id (when (:stale r) \" (stale: the buffer changed since)\"))\n (str \"(recipe \" id \" \" (pr-str r) \")\")]))\n ids)))))\n\n;; ───── the work as data, pretty: what the Data view of the Code tab shows ─────\n;; Collections that fit in the width stay on one line; the others put one entry per line, aligned.\n;; Keys come in a readable order: :text :x :y first, :data last, and :b2 before :b10.\n\n(def edn-width 72)\n(def key-rank {:class 0 :text 1 :x 2 :y 3 :present 4 :view 5 :size 6 :data 98 :recipe 99})\n\n(defn natural-key\n \"A sort key for map keys: the rank of known keys, then the name split into text and numbers.\"\n [k]\n (let [nm (if (keyword? k) (str (when (namespace k) (str (namespace k) \"/\")) (name k)) (pr-str k))]\n [(get key-rank k 50)\n (if (keyword? k) 0 1)\n (vec (map (fn [[_ txt num]] (if num [1 (js/parseInt num 10)] [0 txt]))\n (re-seq #\"(\\D+)|(\\d+)\" nm)))]))\n\n(defn sorted-entries [m]\n (try (sort-by (comp natural-key key) m)\n (catch :default _ (seq m))))\n\n(defn edn-line\n \"EDN of x on one line, with the keys of its maps in the readable order.\"\n [x]\n (cond\n (map? x) (str \"{\" (str/join \" \" (for [[k v] (sorted-entries x)] (str (edn-line k) \" \" (edn-line v)))) \"}\")\n (vector? x) (str \"[\" (str/join \" \" (map edn-line x)) \"]\")\n (set? x) (str \"#{\" (str/join \" \" (map edn-line x)) \"}\")\n (seq? x) (str \"(\" (str/join \" \" (map edn-line x)) \")\")\n :else (pr-str x)))\n\n(defn pp-edn\n \"EDN of x, at most `edn-width` wide where it can be, indented from column `col`.\"\n ([x] (pp-edn x 0))\n ([x col]\n (let [flat (edn-line x)]\n (if (or (<= (+ col (count flat)) edn-width) (not (coll? x)) (empty? x))\n flat\n (let [pad (fn [n] (apply str (repeat n \" \")))]\n (cond\n (map? x)\n (str \"{\"\n (str/join (str \"\\n\" (pad (inc col)))\n (for [[k v] (sorted-entries x)]\n (let [ks (edn-line k)\n vs (pp-edn v (+ col 2 (count ks)))]\n (if (and (coll? v) (seq v) (str/includes? vs \"\\n\") (> (count ks) 12))\n (str ks \"\\n\" (pad (+ col 2)) (pp-edn v (+ col 2)))\n (str ks \" \" vs)))))\n \"}\")\n :else\n (let [[o c] (cond (vector? x) [\"[\" \"]\"] (set? x) [\"#{\" \"}\"] :else [\"(\" \")\"])\n inner (+ col (count o))]\n (str o (str/join (str \"\\n\" (pad inner)) (map (fn [e] (pp-edn e inner)) x)) c))))))))\n\n(defn patch->edn [p]\n (pp-edn {:boxes (:boxes p) :lines (vec (:lines p))}))\n\n;; ───────────────────────── sub-patches ─────────────────────────\n;; A `patch` box keeps a whole patch as its data, with its own history: editing inside it produces\n;; events [:in :b5 [:box …]] in the history of the work, and its code is (inside :b5 …).\n\n(comp/define! \"patch\"\n {:doc \"An embedded sub-patch: double-click to open it. Its inlet / outlet boxes (numbered left to right) are its ports. patch @name uses the line called name instead (its newest point, or the point it is pinned to): double-click opens its tab.\"\n :usage \"patch [label] · patch @line\"\n ;; its ports: the inlet / outlet boxes of what it holds, or of the line it uses (patch @name, #117)\n :io (fn [b] (comp/patch-io (or (eng/inner-patch b) empty-patch)))\n :dynamic-io true\n :model {:empty empty-patch :step step :load sane-patch\n :code (fn [id d] (concat [(str \"(inside \" id)]\n (map (fn [l] (if (str/blank? l) l (str \" \" l))) (str/split-lines (patch->code d)))\n [\")\"]))}})\n\n(defn need-patch-box [id]\n (let [b (need-box id)]\n (when-not (embedded? b) (fail (str id \" is not a patch box (create one with (box \\\"patch\\\" x y))\")))\n id))\n\n(defmacro inside\n \"Runs the body inside the sub-patch :bN: (inside :b5 (box \\\"inlet\\\" 20 20) (connect …)).\"\n [id & body]\n `(do (need-patch-box ~id)\n (binding [*inside* (conj *inside* ~id)] ~@body)\n ~id))\n\n(declare render-all!)\n\n(defn enter\n \"Opens the sub-patch :bN: the patch, the code and the commands now act inside it.\"\n [id]\n ;; a `patch @name` opens its line, in its tab (#117)\n (when (line-ref? (need-box id)) (fail (str id \" uses a line: (open-ref \" id \") opens it in its tab\")))\n (need-patch-box id)\n (swap! view-path conj id)\n (swap! ui assoc :sel nil :nsel nil :dirty false)\n (render-all!)\n (cmd-path))\n\n(defn up\n \"Goes back to the patch that contains this one (or n levels up).\"\n ([] (up 1))\n ([n] (swap! view-path (fn [p] (vec (drop-last (min n (count p)) p))))\n (swap! ui assoc :sel nil :nsel nil :dirty false)\n (render-all!)\n (cmd-path)))\n\n(defn top \"Goes back to the work itself.\" [] (up (count @view-path)))\n\n(defn patch->source\n \"A patch as EDN for the :patch of an abstraction.\"\n [p]\n (str \"{:boxes {\"\n (str/join \"\\n \" (for [id (sort-by box-num (keys (:boxes p)))] (str id \" \" (pr-str (get-in p [:boxes id])))))\n \"}\\n :lines \" (pr-str (:lines p)) \"}\"))\n\n(defn abstract\n \"Turns the sub-patch :bN into a class: a new component box defines it with :patch, and :bN becomes an\n instance of it. Write $1 $2 … in the texts inside to take the words of each instance.\"\n [id class-name]\n (need-patch-box id)\n (when-not (and (string? class-name) (re-matches #\"[A-Za-z][A-Za-z0-9_~+*/<>=!?-]*\" class-name))\n (fail \"The class name is one word, e.g. \\\"voice\\\"\"))\n (when (comp/lookup class-name) (fail (str \"«\" class-name \"» already exists\")))\n (let [b (need-box id)\n src (str \";; \" class-name \" · an abstraction made from a patch\\n\"\n \"{:class \" (pr-str class-name) \"\\n\"\n \" :doc \" (pr-str (str \"Abstraction made from the sub-patch \" id \".\")) \"\\n\"\n \" :usage \" (pr-str class-name) \"\\n\"\n \" :patch \" (patch->source (or (:data b) empty-patch)) \"}\")\n nid (next-id)]\n (box nid \"component\" (+ (:x b) 180) (:y b))\n (code nid src)\n (text! id class-name)\n nid))\n\n;; ───────────────────────── evaluation ─────────────────────────\n\n(defn eval-str [code] (js/scittle.core.eval_string code))\n\n(def example \"\\n(box :b1 \\\"canvas\\\" 40 60)\\n(box :b2 \\\"loadbang\\\" 40 15)\\n(box :b3 \\\"ramp 0 1 10 loop\\\" 140 15)\\n(box :b4 \\\"reader path\\\" 40 290)\\n(box :b5 \\\"freqt\\\" 500 60)\\n(box :b6 \\\"phasor~ 0.25\\\" 500 15)\\n(box :b7 \\\"reader~ norm 2 gate\\\" 500 290)\\n(box :b8 \\\"osc~\\\" 500 340)\\n(box :b9 \\\"osc~\\\" 600 340)\\n(box :b10 \\\"gain~ 0.4\\\" 500 500)\\n(box :b13 \\\"gain~\\\" 500 450)\\n(box :b14 \\\"gain~\\\" 600 450)\\n(box :b15 \\\"adsr~ 30 200 0.6 400\\\" 700 340)\\n(box :b16 \\\"adsr~ 5 120 0.4 900\\\" 870 340)\\n(box :b11 \\\"space~ 0 1\\\" 240 330)\\n(box :b12 \\\"dac~ 1 2\\\" 240 470)\\n(connect :b2 0 :b3 0)\\n(connect :b3 0 :b4 0)\\n(connect :b1 1 :b4 1)\\n(connect :b6 0 :b7 0)\\n(connect :b5 1 :b7 1)\\n(connect :b7 0 :b8 0)\\n(connect :b7 1 :b9 0)\\n(connect :b8 0 :b13 0)\\n(connect :b9 0 :b14 0)\\n(connect :b7 2 :b15 0)\\n(connect :b7 3 :b16 0)\\n(connect :b15 0 :b13 1)\\n(connect :b16 0 :b14 1)\\n(connect :b13 0 :b10 0)\\n(connect :b14 0 :b10 0)\\n(connect :b10 0 :b11 0)\\n(connect :b4 0 :b11 0)\\n(connect :b11 0 :b12 0)\\n(connect :b11 1 :b12 1)\\n(axis :b1 :x -1 1)\\n(axis :b1 :y -1 1)\\n(stroke :b1 [[0 0.9] [0.7 0.6] [0.9 -0.1] [0.5 -0.7] [-0.2 -0.85] [-0.8 -0.4] [-0.9 0.3] [-0.45 0.8] [0 0.9]])\\n(stroke :b5 [[0 220] [1 220] [2 330] [2.5 293.66] [3 440] [4 220]])\\n(stroke :b5 [[0 330] [1.5 392]])\\n(stroke :b5 [[2 261.63] [3 293.66] [4 330]])\\n(present :b1 0 0)\\n(present :b5 430 0)\\n(present :b11 0 210)\")\n\n\n\n\n\n\n(defn box-num-e [k] (cv/id-num k))\n\n(defn build\n \"Evaluates code in a scratch patch and returns the resulting patch, without touching the history.\"\n [code]\n (reset! scratch empty-patch)\n (try\n (eval-str (str \"(do \" code \"\\n nil)\"))\n (let [p @scratch] (reset! scratch nil) p)\n (catch :default e (reset! scratch nil) (throw e))))\n\n(defn run-code!\n \"Rebuilds the patch from the code: it stays as a single :load event.\"\n [code]\n (let [p (build code)] (dispatch! [:load p]) :ok))\n\n(defn load-example [] (run-code! example))\n","page/02-patch-view.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 3 of 12: patch-view\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── interface: patch ─────────────────────────\n\n(defn $ [id] (js/document.getElementById id))\n\n;; ───── embedding (Study 22): the address says what to show and how ─────\n;; ?code=… a patch (its code, compressed) · ?tutorial=id&step=n · ?help=class · ?lang=es|en\n;; ?embed only the patch, to put inside another page (an iframe, a Notion /embed block)\n;; ?present only the presentation, filling the window (with a fullscreen button)\n\n;; the same after # (issue #55): #code=…&present. What is after # never reaches the server, so a long patch\n;; is not refused there (a request line too long is answered 414); after #, a parameter wins over ?.\n\n(defn hash-part [] (subs (str (.-hash js/location)) 1))\n\n(def url-params\n (let [q (js/URLSearchParams. (.-search js/location))]\n (.forEach (js/URLSearchParams. (hash-part)) (fn [v k] (.set q k v)))\n q))\n(defn url-param [k] (.get url-params k))\n(defn raw-param\n \"A parameter as written in the address, where + stays + (code written by hand: ?src=… or #src=…).\"\n [k]\n (some (fn [part]\n (let [i (.indexOf part \"=\")]\n (when (and (pos? i) (= k (subs part 0 i)))\n (try (js/decodeURIComponent (subs part (inc i))) (catch :default _ nil)))))\n (concat (str/split (hash-part) #\"&\")\n (str/split (subs (str (.-search js/location)) 1) #\"&\"))))\n\n(def link-keys\n \"The parameters that say what a link opens: a new one after # (pasted in the same tab) opens it.\"\n #{\"code\" \"src\" \"ask\" \"tutorial\" \"help\" \"embed\" \"present\"})\n\n(.addEventListener js/window \"hashchange\"\n (fn [_]\n (let [ks (set (map (fn [part] (first (str/split part #\"=\" 2))) (str/split (hash-part) #\"&\")))]\n (when (some link-keys ks) (.reload js/location)))))\n(def embed-mode (cond (.has url-params \"present\") :present (.has url-params \"embed\") :embed))\n\n(defn wrap-px\n \"Where a point of the patch is inside the patch pane, in pixels (an embedded patch is shown scaled).\"\n [x y]\n (let [cv ($ \"canvas\")]\n (if-not (.hasAttribute cv \"viewBox\")\n [x y]\n (let [q (.createSVGPoint cv) wrap ($ \"canvas-wrap\") r (.getBoundingClientRect wrap)]\n (set! (.-x q) x)\n (set! (.-y q) y)\n (let [s (.matrixTransform q (.getScreenCTM cv))]\n [(+ (- (.-x s) (.-left r)) (.-scrollLeft wrap)) (+ (- (.-y s) (.-top r)) (.-scrollTop wrap))])))))\n\n(def box-h 24)\n(def pw 10)\n(defn box-w [text] (max 56 (+ 20 (* 7.6 (count text)))))\n(defn port-x [w n i] (if (<= n 1) 0 (* i (/ (- w pw) (dec n)))))\n\n;; ───── buffer boxes (canvas, score) and action boxes (number, msg, bang) ─────\n\n(def hdr 20)\n(def grip 8)\n(defonce score-cache (atom {})) ; box → {:key data :node <g> :h height :pieces [...] :anchors [...]}\n(defonce vrv (atom nil))\n(defonce vrv-status (atom :loading))\n\n(def code-w 260)\n(def code-lh 13)\n(def code-row 22) ; a code box shows its code as one row (issue #8): the editor opens with a double-click\n(def param-h 18)\n\n(defn code-lines [b] (str/split-lines (let [f (str (get-in b [:data :source]))] (if (str/blank? f) \" \" f))))\n\n(defn code-params [b]\n (when-let [f (:params (box-def b))] (f (comp/box-info b))))\n\n(defn code-geom\n \"Parts of a code box: its code row, the status of its compilation, its parameters. The code itself is\n written in the editor (a double-click on the row), not in the patch (issue #8).\"\n [b]\n (let [ch code-row\n y-st (+ hdr ch 13)\n y-par (+ hdr ch 20)\n ps (code-params b)]\n {:ch ch :y-st y-st :y-par y-par :params ps :h (+ y-par (* (count ps) param-h) 4)}))\n\n(defn code-gist\n \"What the code row of a box shows: its first line that says something (not a comment), and how long it is.\"\n [b]\n (let [ls (code-lines b)\n first-line (or (first (remove (fn [l] (or (str/blank? l) (re-find #\"^\\s*(;|//)\" l))) ls)) \"\")\n n (count (remove str/blank? ls))]\n [(str/trim first-line) n]))\n\n(declare panel-layout)\n\n(def html-size \"The size an html box is drawn at until it is given one (issue #146).\" [260 150])\n\n(defn box-size\n \"The size a canvas, freqt, score or html box is drawn at: the one being dragged at its corner, its own\n (:size, issue #40), or the default. For a score only the width counts: its height follows the notation.\"\n [id b]\n (let [r (:resize @ui)]\n (if (and r (= (:id r) id)) [(:w r) (:h r)] (or (:size b) (if (= :html (display-of b)) html-size [cv/W cv/H])))))\n\n(defn box-dims [id b]\n (let [t (:text b)]\n (cond\n (= :code (display-of b)) [code-w (:h (code-geom b))]\n (panel-layout b) (let [{:keys [w h]} (panel-layout b)] [w h])\n (own-view? b) (let [[w h] (comp/size-of b)] [(+ grip w) h])\n (#{:canvas :html} (display-of b)) (box-size id b)\n (= :score (display-of b)) [(first (box-size id b)) (max 90 (+ hdr 8 (or (get-in @score-cache [id :h]) 70)))]\n :else\n (case (klass t)\n \"bang\" [34 26]\n \"number\" [76 box-h]\n \"msg\" [(max 44 (+ grip 14 (* 7.6 (count (str/trim (subs (str/trim t) 3)))))) box-h]\n \"patch\" (if (line-ref? b) [(+ (box-w t) 30) box-h] [(box-w t) box-h])\n [(box-w t) box-h]))))\n\n(defn box-pos [id b]\n (let [d (:drag @ui)]\n (cond\n ;; several boxes moving together: each from where it started, by the same offset\n (and d (:moved d) (:ids d) (contains? (:ids d) id))\n (let [[x0 y0] (get (:ids d) id)] [(+ x0 (:gx d)) (+ y0 (:gy d))])\n (and d (= (:id d) id) (:moved d)) [(:x d) (:y d)]\n :else [(:x b) (:y b)])))\n\n(defn out-xy [p id o]\n (let [b (get-in p [:boxes id]) [x y] (box-pos id b) [w h] (box-dims id b) [_ n] (io b)]\n [(+ x (port-x w n o) (/ pw 2)) (+ y h)]))\n\n(defn in-xy [p id i]\n (let [b (get-in p [:boxes id]) [x y] (box-pos id b) [w _] (box-dims id b) [n _] (io b)]\n [(+ x (port-x w n i) (/ pw 2)) y]))\n\n;; ───── patching: the same feel in every patcher of Kairotic (the patch, and the patch of a faust~) ─────\n;; Wires are curves that leave an outlet downwards and reach an inlet from above; one that goes back up\n;; loops out below and above the boxes. An outlet within `reach` of the pointer can be grabbed (it lights\n;; up, and the pointer is a cross), and a wire is dropped on the nearest inlet of the box under the\n;; pointer, or of an inlet within reach above it. packages/faust-units/assets/view.mjs does the same.\n\n(def reach 10)\n\n(defn wire-d\n \"The curve of a wire from an outlet at (x1 y1) to an inlet at (x2 y2), as an SVG path.\"\n [x1 y1 x2 y2]\n (let [dy (- y2 y1)\n k (if (>= dy 24) (max 16 (* 0.45 dy)) (+ 36 (min 70 (* 0.25 (js/Math.abs (- x2 x1))))))\n r (fn [v] (/ (js/Math.round (* 10 v)) 10))]\n (str \"M\" (r x1) \",\" (r y1) \" C\" (r x1) \",\" (r (+ y1 k)) \" \" (r x2) \",\" (r (- y2 k)) \" \" (r x2) \",\" (r y2))))\n\n(defn port-near\n \"The outlet (:out) or inlet (:in) of a box in patch p nearest to (x y), within reach: [id k], or nil.\n An outlet is reached from its edge of the box a little inside and a little more outside; an inlet\n the same way from above.\"\n [p kind x y]\n (let [best (atom nil)]\n (doseq [[id b] (:boxes p)]\n (let [[bx by] (box-pos id b) [w h] (box-dims id b) [ins outs] (io b)\n n (if (= kind :out) outs ins)\n py (if (= kind :out) (+ by h) by)\n dy (if (= kind :out) (- y py) (- py y))] ; positive: outside the box\n (when (and (pos? n) (<= -4 dy (+ reach 2)) (<= (- bx reach) x (+ bx w reach)))\n (dotimes [k n]\n (let [px (+ bx (port-x w n k) (/ pw 2)) dx (js/Math.abs (- x px))]\n (when (<= dx (+ (/ pw 2) reach))\n (let [d (+ (* dx dx) (* dy dy))]\n (when (or (nil? @best) (< d (first @best))) (reset! best [d [id k]])))))))))\n (second @best)))\n\n(defn canvas-geom\n \"Where a canvas draws its data (d), in the box b (its size: issue #40) or in one of the default size.\"\n ([d] (cv/geom (or d cv/empty) hdr))\n ([d id b] (cv/geom (or d cv/empty) hdr (box-size id b))))\n\n;; a tree box shown as a score (discussion #30): its own tree, expanded, remembering where each note is\n;; written, so its notes edit it directly\n(defn own-tree [id b]\n (when-let [t (mtb/tree-of (:data b))] (try (mt/expand-source t id) (catch :default _ nil))))\n\n(defn kept-tree\n \"The tree a buffer was kept from, while the buffer has not changed since (its recipe is not stale).\"\n [b] (let [r (:recipe b)] (when (and r (not (:stale r))) (:tree r))))\n\n;; score: Verovio draws the buffer quantized into measures (kairotic.quantize); the SVG node is kept and put back on every repaint\n(defn score-entry! [id b]\n (let [tree-box? (= \"tree\" (klass (:text b)))\n d0 (if tree-box? cv/empty (canvas-data b))\n ;; a tree shown live, or the tree a buffer was kept from while it is unchanged (its recipe)\n lt (if tree-box? (own-tree id b) (or (live-tree id) (kept-tree b)))\n sw (first (box-size id b))\n d [d0 lt sw] c (get @score-cache id)]\n (cond\n (and c (= (:key c) d)) c\n (nil? @vrv) nil\n :else\n (try\n (let [tk @vrv scale 30\n ;; a measured tree as it is; a tree without measures, or the strokes of the buffer, quantized (#86)\n {:keys [mei pieces]} (cond\n lt (qz/->score lt (str (name id) \"-\"))\n (cv/generic? d0) (sc/->mei-voice (cv/->voice d0) (str (name id) \"-\"))\n :else (qz/->score d0 (str (name id) \"-\") (:quant d0)))\n g (js/document.createElementNS \"http://www.w3.org/2000/svg\" \"g\")]\n (.setOptions tk (clj->js {:pageWidth (js/Math.round (/ (* (- sw 8) 100) scale)) :pageHeight 60000\n :adjustPageHeight true :breaks \"auto\" :scale scale\n :header \"none\" :footer \"none\" :lyricSize 3.2\n :pageMarginTop 24 :pageMarginBottom 12 :pageMarginLeft 20 :pageMarginRight 20}))\n (.loadData tk mei)\n (set! (.-innerHTML g) (.renderToSVG tk 1))\n (let [sv (.querySelector g \"svg\")\n h (if sv (js/parseFloat (.getAttribute sv \"height\")) 70)\n e {:key d :node g :h (if (js/isNaN h) 70 h) :pieces pieces :anchors nil :from (:from (meta lt))}]\n (swap! score-cache assoc id e)\n e))\n (catch :default ex\n (let [e {:key d :node nil :h 40 :error (or (.-message ex) (str ex))}]\n (swap! score-cache assoc id e)\n e))))))\n\n(defn local-box\n \"Box of an SVG element in the coordinates of `ref` (without going through screen pixels,\n which change when the page is zoomed in or out).\"\n [el ref]\n (let [b (.getBBox el)\n m (.multiply (.inverse (.getScreenCTM ref)) (.getScreenCTM el))\n tp (fn [x y] (let [q (.createSVGPoint ($ \"canvas\"))] (set! (.-x q) x) (set! (.-y q) y) (.matrixTransform q m)))\n a (tp (.-x b) (.-y b))\n c (tp (+ (.-x b) (.-width b)) (+ (.-y b) (.-height b)))]\n {:left (.-x a) :top (.-y a) :right (.-x c) :bottom (.-y c) :w (- (.-x c) (.-x a))}))\n\n(defn score-anchors\n \"Time ⇄ space anchors of a placed score, in the coordinates of its box.\"\n [node pieces]\n (when (and node (.querySelector node \"svg\") (.-isConnected node))\n (->> pieces\n (keep (fn [{:keys [id t]}]\n (when-let [el (.querySelector node (str \"#\" id))]\n (let [head (or (.querySelector el \".notehead\") el)\n r (local-box head node)\n sys (or (.closest el \".system\") el)\n sr (local-box sys node)]\n (when (pos? (:w r))\n {:t t :x (:left r) :y0 (- (:top sr) 6) :y1 (+ (:bottom sr) 6) :right (:right sr)})))))\n (group-by :t)\n (map (fn [[_ as]] (apply min-key :x as)))\n (sort-by :t)\n vec)))\n\n;; ───── live layer: number values, flashes, reading cursors ─────\n\n(defn shown-flat\n \"The last thing a box (by its engine id) showed: with the engine running, up to the instant sounding now.\"\n [f]\n (if (eng/running?)\n (eng/shown-at f (eng/now))\n (last (get-in @eng/rt [:shows f]))))\n\n(defn last-shown \"The same, for a box of the current view.\" [id] (shown-flat (fid id)))\n\n(defn recent? [[at _]] (and at (eng/running?) (< (- (eng/now) at) 0.15)))\n\n(defn cursor-at\n \"A vertical line at time t of box `bid` (canvas or score), with dots on what sounds.\"\n ([p bid t cls dots?] (cursor-at p bid t cls dots? :x nil))\n ([p bid t cls dots? axis] (cursor-at p bid t cls dots? axis nil))\n ([p bid t cls dots? axis pt]\n (when-let [b (get-in p [:boxes bid])]\n (let [[x y] (box-pos bid b) d (canvas-data b)]\n (case (display-of b)\n :canvas\n (cond\n (= axis :path)\n (when pt\n (let [g (canvas-geom d bid b)]\n (str \"<circle class=\\\"sounding\\\" cx=\\\"\" (+ x (cv/t->x g (first pt))) \"\\\" cy=\\\"\" (+ y (cv/f->y g (second pt))) \"\\\" r=\\\"6\\\"></circle>\")))\n (= axis :y)\n (let [g (canvas-geom d bid b) cy (+ y (cv/f->y g (max (:ya g) (min t (:yb g)))))]\n (str \"<line class=\\\"\" cls \"\\\" x1=\\\"\" (+ x (:x0 g)) \"\\\" x2=\\\"\" (+ x (:x0 g) (:w g)) \"\\\" y1=\\\"\" cy \"\\\" y2=\\\"\" cy \"\\\"></line>\"\n (when dots?\n (apply str (for [[_ v] (cv/read-along d :y t)]\n (str \"<circle class=\\\"sounding\\\" cx=\\\"\" (+ x (cv/t->x g v)) \"\\\" cy=\\\"\" cy \"\\\" r=\\\"4\\\"></circle>\"))))))\n :else\n (let [g (canvas-geom d bid b) cx (+ x (cv/t->x g (max (:xa g) (min t (:xb g)))))]\n (str \"<line class=\\\"\" cls \"\\\" x1=\\\"\" cx \"\\\" x2=\\\"\" cx \"\\\" y1=\\\"\" (+ y (:y0 g)) \"\\\" y2=\\\"\" (+ y (:y0 g) (:h g)) \"\\\"></line>\"\n (when dots?\n (apply str (for [[_ f] (cv/read-at d t)]\n (str \"<circle class=\\\"sounding\\\" cx=\\\"\" cx \"\\\" cy=\\\"\" (+ y (cv/f->y g f)) \"\\\" r=\\\"4\\\"></circle>\")))))))\n :score (when-let [a (sc/t->pos (get-in @score-cache [bid :anchors]) t)]\n (let [cx (+ x 4 (:x a)) oy (+ y hdr 4)]\n (str \"<line class=\\\"\" cls \"\\\" x1=\\\"\" cx \"\\\" x2=\\\"\" cx \"\\\" y1=\\\"\" (+ oy (max 0 (:y0 a))) \"\\\" y2=\\\"\" (+ oy (:y1 a)) \"\\\"></line>\")))\n nil)))))\n\n(def param-x0 96)\n\n;; ───── own view of a component: its :view template filled by :derive (or what :draw returns),\n;; from the last thing it showed ─────\n\n(defn ctl-shown [id] (second (last-shown id)))\n\n(defn ctl-m*\n \"What :derive, :draw and :gesture receive, for box b known to the engine as f.\"\n [f b]\n (let [[w h] (comp/size-of b)]\n {:id f :shown (second (shown-flat f)) :state (get-in @eng/rt [:states f]) :args (comp/args-for (box-def b) (:text b))\n :text (:text b) :data (:data b) :w w :h h}))\n\n(defn ctl-m [id b] (ctl-m* (fid id) b))\n\n(defn ctl-shapes*\n \"The shapes of a component's own view: :view filled with its holes, or :draw.\"\n [m b]\n (let [d (box-def b)]\n (cond\n (some? (:view d))\n (let [derived (if-let [f (:derive d)] (f m) {})]\n (shp/fill (:view d) (merge (when (map? (:args m)) (:args m)) (select-keys m [:shown :w :h]) derived)))\n (fn? (:draw d)) ((:draw d) m)\n :else [])))\n\n(defn shapes-at\n \"The SVG of the own view of box b (engine id f) with its top-left corner at x y.\"\n [f b x y]\n (let [shape-list (try (ctl-shapes* (ctl-m* f b) b)\n (catch :default e [[:text {:x 4 :y 14 :fill :kairos :size 10} (str \"✗ \" (or (.-message e) e))]]))]\n (str \"<g class=\\\"shapes\\\" transform=\\\"translate(\" x \",\" y \")\\\">\" (shp/svg shape-list) \"</g>\")))\n\n(defn ctl-overlay\n \"The own view of a component, and the part of it under (or near) the pointer, highlighted.\"\n [id b x y]\n (str (shapes-at (fid id) b (+ x grip) y)\n (when-let [[hid k] (:hover-hit @ui)]\n (when (= hid id)\n (let [hs (try (shp/only-hit (ctl-shapes* (ctl-m id b) b) k) (catch :default _ nil))]\n (when (seq hs)\n (str \"<g class=\\\"shapes hit-hover\\\" transform=\\\"translate(\" (+ x grip) \",\" y \")\\\">\" (shp/svg hs) \"</g>\")))))))\n\n;; ───── panels: a sub-patch seen from outside shows the boxes presented inside it ─────\n\n(defn child-dims\n \"Size of a box in presentation: its own view, or a small chip with its text.\"\n [b]\n (if (own-view? b) (comp/size-of b) [(box-w (:text b)) box-h]))\n\n(def panel-pad 4)\n\n(defn panel-layout\n \"The presented boxes of a sub-patch box and the size of its panel, or nil if none is presented.\"\n [b]\n (when (comp/subpatch? b)\n (let [inner (eng/inner-patch b)\n kids (vec (for [[cid cb] (sort-by (fn [[k _]] (box-num k)) (:boxes inner))\n :let [[px py] (:present cb)] :when px]\n (let [[w h] (child-dims cb)] {:id cid :b cb :x px :y py :w w :h h})))]\n (when (seq kids)\n {:kids kids\n :w (max (box-w (:text b)) (+ (* 2 panel-pad) (apply max (map (fn [k] (+ (:x k) (:w k))) kids))))\n :h (+ hdr (* 2 panel-pad) (apply max (map (fn [k] (+ (:y k) (:h k))) kids)))}))))\n\n(defn kid-origin [x y k] [(+ x panel-pad (:x k)) (+ y hdr panel-pad (:y k))])\n\n(defn panel-svg\n \"The fixed part of a panel: its header and, for each presented box, a hit area or a chip.\"\n [id b w]\n (let [{:keys [kids]} (panel-layout b) idn (esc (name id))]\n (str \"<rect class=\\\"head\\\" x=\\\"0.5\\\" y=\\\"0.5\\\" width=\\\"\" (- w 1) \"\\\" height=\\\"\" (- hdr 1) \"\\\"></rect>\"\n \"<text class=\\\"lbl\\\" x=\\\"8\\\" y=\\\"14\\\">\" (esc (:text b)) \"</text>\"\n (apply str\n (for [k kids :let [[kx ky] (kid-origin 0 0 k)]]\n (if (own-view? (:b k))\n (str \"<rect class=\\\"pres-area\\\" data-box=\\\"\" idn \"\\\" data-kid=\\\"\" (esc (name (:id k))) \"\\\" x=\\\"\" kx \"\\\" y=\\\"\" ky\n \"\\\" width=\\\"\" (:w k) \"\\\" height=\\\"\" (:h k) \"\\\"><title>\" (esc (:text (:b k))) \"</title></rect>\")\n (str \"<rect class=\\\"chip\\\" x=\\\"\" kx \"\\\" y=\\\"\" ky \"\\\" width=\\\"\" (:w k) \"\\\" height=\\\"\" (:h k) \"\\\" rx=\\\"3\\\"></rect>\"\n \"<text x=\\\"\" (+ kx 8) \"\\\" y=\\\"\" (+ ky 16) \"\\\">\" (esc (:text (:b k))) \"</text>\")))))))\n\n(defn panel-overlay\n \"The live part of a panel: the own views of its presented boxes.\"\n [id b x y]\n (apply str (for [k (:kids (panel-layout b)) :when (own-view? (:b k)) :let [[kx ky] (kid-origin x y k)]]\n (shapes-at (eng/flat-id (conj (engine-path) id) (:id k)) (:b k) kx ky))))\n\n;; ───── presentation mode: only the presented boxes, at their presentation places ─────\n\n(defonce pres-mode (atom false))\n\n(defn view-box\n \"A box as it is placed on screen: in presentation, at its presentation place.\"\n [b]\n (if (and @pres-mode (:present b)) (assoc b :x (first (:present b)) :y (second (:present b))) b))\n\n(defn scene-of\n \"The patch that is drawn: in presentation, only its presented boxes, without lines; never the boxes\n that define components (they are in the Components tab, issue #8).\"\n [p]\n (if @pres-mode\n {:boxes (into (sorted-map) (for [[id b] (:boxes p) :when (and (:present b) (not (definition? b)))] [id (view-box b)])) :lines []}\n (update p :boxes without-definitions)))\n\n(defn presentation\n \"Switches the patch between editing and presentation (only the presented boxes, where the performer sees them).\"\n ([] (presentation (not @pres-mode)))\n ([on]\n (reset! pres-mode (boolean on))\n ;; in presentation nothing is selected (issue #57)\n (when on (swap! ui assoc :sel nil :insp nil :nsel nil :tsel nil :marquee nil))\n (.toggle (.-classList ($ \"canvas-wrap\")) \"pres\" @pres-mode)\n (.toggle (.-classList ($ \"pres-toggle\")) \"on\" @pres-mode)\n (set! (.-textContent ($ \"pres-toggle\")) (if @pres-mode \"Edit\" \"Present\"))\n (swap! ui assoc :sel nil :nsel nil)\n (render-all!)\n @pres-mode))\n\n(declare code-win-box)\n\n(defn code-view\n \"SVG of a code box: the source text, the status of its compilation and its parameters.\"\n [id b w]\n (let [d (box-def b) idn (esc (name id))\n {:keys [ch y-st y-par params]} (code-geom b)\n [gist n] (code-gist b)\n source (str (get-in b [:data :source]))\n open? (= id (code-win-box))\n r (cbox/compiled (:language d) source)\n inf (:info r)\n [st cls] (case (:status r)\n :empty [\"empty · double-click to write\" \"st-wait\"]\n :compiling [\"compiling…\" \"st-wait\"]\n :ok [(str \"✓ \" (or (:summary inf) \"ready\")) \"st-ok\"]\n :error [(str \"✗ \" (first (str/split-lines (str (:error r))))) \"st-err\"]\n [\"\" \"st-wait\"])]\n (str \"<svg x=\\\"2\\\" y=\\\"\" hdr \"\\\" width=\\\"\" (- w 4) \"\\\" height=\\\"\" ch \"\\\" overflow=\\\"hidden\\\">\"\n \"<rect class=\\\"code-area\" (when open? \" open\") \"\\\" data-box=\\\"\" idn \"\\\" x=\\\"0\\\" y=\\\"0\\\" width=\\\"\" (- w 4) \"\\\" height=\\\"\" ch \"\\\">\"\n \"<title>Double-click to edit the code</title></rect>\"\n \"<text class=\\\"code\\\" xml:space=\\\"preserve\\\" x=\\\"6\\\" y=\\\"15\\\">\"\n (esc (cond (str/blank? source) \"{ } double-click to write\"\n (> (count gist) 30) (str (subs gist 0 30) \"…\")\n :else gist))\n \"</text>\"\n (when (pos? n)\n (str \"<text class=\\\"code lines\\\" x=\\\"\" (- w 10) \"\\\" y=\\\"15\\\" text-anchor=\\\"end\\\">\"\n (if open? \"✎ open\" (str n (if (= 1 n) \" line\" \" lines\"))) \"</text>\"))\n \"</svg>\"\n \"<text class=\\\"lbl \" cls \"\\\" x=\\\"8\\\" y=\\\"\" y-st \"\\\">\" (esc (if (> (count st) 52) (str (subs st 0 52) \"…\") st))\n (when (= :error (:status r)) (str \"<title>\" (esc (:error r)) \"</title>\")) \"</text>\"\n (apply str (map-indexed\n (fn [i p]\n (let [y (+ y-par (* i param-h))]\n (str \"<text class=\\\"lbl pname\\\" x=\\\"8\\\" y=\\\"\" (+ y 12) \"\\\">\" (esc (:label p)) \"</text>\"\n \"<rect class=\\\"param\" (when (#{\"button\" \"checkbox\"} (:type p)) \" button\") \"\\\" data-box=\\\"\" idn \"\\\" data-param=\\\"\" (esc (:label p))\n \"\\\" x=\\\"\" param-x0 \"\\\" y=\\\"\" (+ y 3) \"\\\" width=\\\"\" (- w param-x0 64) \"\\\" height=\\\"11\\\" rx=\\\"2\\\"></rect>\"\n ;; its value (drawn on top, in the live layer): a double-click there types it (issue #32)\n (when-not (#{\"button\" \"checkbox\"} (:type p))\n (str \"<rect class=\\\"pval-hit\\\" data-box=\\\"\" idn \"\\\" data-param=\\\"\" (esc (:label p))\n \"\\\" x=\\\"\" (- w 62) \"\\\" y=\\\"\" (+ y 1) \"\\\" width=\\\"58\\\" height=\\\"15\\\">\"\n \"<title>Double-click to type a value</title></rect>\")))))\n params)))))\n\n(defn param-value [id b p]\n (let [v (when-let [nd (eng/node (fid id))] (get @(:values nd) (:label p)))]\n (if (number? v) v (:init p))))\n\n(defn params-overlay\n \"Fill and value of the parameters of a code box (they change while it sounds).\"\n [id b x y w]\n (let [{:keys [y-par params]} (code-geom b) tw (- w param-x0 64)]\n (apply str (map-indexed\n (fn [i p]\n (let [v (param-value id b p)\n u (if (> (:max p) (:min p)) (/ (- v (:min p)) (- (:max p) (:min p))) (if (pos? v) 1 0))\n yy (+ y y-par (* i param-h))]\n (str \"<rect class=\\\"pfill\\\" x=\\\"\" (+ x param-x0) \"\\\" y=\\\"\" (+ yy 3) \"\\\" width=\\\"\" (* tw (max 0 (min 1 u))) \"\\\" height=\\\"11\\\" rx=\\\"2\\\"></rect>\"\n \"<text class=\\\"pval\\\" x=\\\"\" (+ x (- w 8)) \"\\\" y=\\\"\" (+ yy 12) \"\\\" text-anchor=\\\"end\\\">\" (cv/fmt v) \"</text>\")))\n params))))\n\n;; ───── layers (Study 26): marks anchored to boxes or to the paper, and projections ─────\n\n(defn view-name \"Where the patch is seen now: :patch or :present (the presentation).\" [] (if @pres-mode :present :patch))\n\n(defn layer-shown? [p lid] (contains? (get-in p [:layers lid :show] #{:patch :present}) (view-name)))\n\n(defn resolve-anchor\n \"Where an anchor is on screen now: [x y], or nil if its box is not drawn (not presented, or gone).\"\n [p [a x y]]\n (if (= a :patch)\n [x y]\n (when-let [b (get-in p [:boxes a])]\n ;; in the presentation a box is where it is presented, and one that is not presented is not there\n (when-let [b (if @pres-mode (when (:present b) (view-box b)) b)]\n (let [[bx by] (box-pos a b)] [(+ bx x) (+ by y)])))))\n\n(defn mark-points\n \"The points of a mark on screen, or nil if one of them is not (then the mark is not drawn).\"\n [p m]\n (let [ps (map (fn [a] (resolve-anchor p a)) (if (#{:text :image} (:kind m)) [(:at m)] (:pts m)))]\n (when (every? some? ps) (vec ps))))\n\n(defn mark-svg [p id m]\n (when-let [ps (mark-points p m)]\n (let [r (fn [v] (/ (js/Math.round (* 10 v)) 10)) pts (str/join \" \" (map (fn [[x y]] (str (r x) \",\" (r y))) ps))\n idn (esc (name id))]\n (case (:kind m)\n :line (str \"<polyline class=\\\"amark\\\" data-mark=\\\"\" idn \"\\\" points=\\\"\" pts \"\\\"></polyline>\")\n :arrow (let [[[x1 y1] [x2 y2]] ps a (js/Math.atan2 (- y2 y1) (- x2 x1)) L 11\n h (fn [d] [(- x2 (* L (js/Math.cos (+ a d)))) (- y2 (* L (js/Math.sin (+ a d))))])]\n (str \"<line class=\\\"amark\\\" data-mark=\\\"\" idn \"\\\" x1=\\\"\" (r x1) \"\\\" y1=\\\"\" (r y1) \"\\\" x2=\\\"\" (r x2) \"\\\" y2=\\\"\" (r y2) \"\\\"></line>\"\n \"<polygon class=\\\"ahead\\\" points=\\\"\" (str/join \" \" (map (fn [[x y]] (str (r x) \",\" (r y))) [[x2 y2] (h 0.4) (h -0.4)])) \"\\\"></polygon>\"))\n :text (let [[[x y]] ps] (str \"<text class=\\\"atext\\\" data-mark=\\\"\" idn \"\\\" x=\\\"\" (r x) \"\\\" y=\\\"\" (r y) \"\\\">\" (esc (:txt m)) \"</text>\"))\n :image (let [[[x y]] ps] (str \"<image class=\\\"aimage\\\" data-mark=\\\"\" idn \"\\\" x=\\\"\" (r x) \"\\\" y=\\\"\" (r y) \"\\\" width=\\\"\" (:w m) \"\\\" height=\\\"\" (:h m) \"\\\" href=\\\"\" (esc (:src m)) \"\\\"></image>\"))\n \"\"))))\n\n(defn projection-svg\n \"The view of box id drawn again in rect, from what it shows now (its :draw or :view at that size).\"\n [p id {[x y w h] :rect}]\n (when-let [b (get-in p [:boxes id])]\n (when (own-view? b)\n (let [sh (try (ctl-shapes* (assoc (ctl-m* (fid id) b) :w w :h h) b)\n (catch :default e [[:text {:x 8 :y 18 :fill :kairos :size 11} (str \"✗ \" (or (.-message e) e))]]))]\n (str \"<g class=\\\"proj shapes\\\" transform=\\\"translate(\" x \",\" y \")\\\">\" (shp/svg sh) \"</g>\")))))\n\n(defn as-dragged\n \"Mark id as it is while it is being moved with the Annotate bar (all of it, or one end), else m.\"\n [id m]\n (let [{:keys [kind x0 y0 x y end] did :id} (:adraw @ui)]\n (if (and (= :move kind) (= did id) (number? x))\n (let [dx (- x x0) dy (- y y0)]\n (if (some? end)\n (update-in m [:pts end] (fn [[a px py]] [a (+ px dx) (+ py dy)]))\n (shift-mark m dx dy)))\n m)))\n\n(defn layers-svg\n \"The layers of patch p that go at z (:over or :under the boxes), as seen now.\"\n [p z]\n (let [ls (filter (fn [[lid l]] (and (= z (:z l)) (layer-shown? p lid))) (sort-by key (:layers p)))\n on (set (map first ls))]\n (str (apply str (for [[id pr] (:projections p) :when (on (:layer pr))] (projection-svg p id pr)))\n (apply str (for [[id m] (:marks p) :when (on (:layer m))] (mark-svg p id (as-dragged id m)))))))\n\n(declare annot-preview render-annot-bar!)\n;; html boxes (issue #146), in 19-html.cljs\n(declare html-slot-svg html-save-focus! mount-html-slots! refresh-html-boxes!)\n\n(defn render-layers! []\n (let [p (current) under ($ \"layers-under\") over ($ \"layers-over\")]\n (when under (set! (.-innerHTML under) (layers-svg p :under)))\n (when over (set! (.-innerHTML over) (str (layers-svg p :over) (annot-preview))))\n (render-annot-bar!)))\n\n(defonce probe-hooks\n ;; probes on wires (page 26-probes): is a wire probed, and the labels of the probes of a patch\n (atom {:probed? (constantly false) :labels (constantly \"\")}))\n\n(defn render-overlay! []\n (let [p (scene-of (current))\n on (eng/running?)\n ;; what each box draws over itself, in its own slot (issue #166)\n own (for [[id b] (:boxes p) :let [kc (klass (:text b)) [x y] (box-pos id b) [w h] (box-dims id b)]]\n [id (str\n (case kc\n \"number\" (let [v (or (second (last-shown id)) (get-in @eng/rt [:states (fid id)])\n (eng/num-of (first (eng/args-of (:text b)))) 0)]\n (str \"<text class=\\\"value\\\" x=\\\"\" (+ x grip 8) \"\\\" y=\\\"\" (+ y 16) \"\\\">▸ \" (esc (if (number? v) (cv/fmt v) (pr-str v))) \"</text>\"))\n (\"msg\" \"bang\") (when (recent? (last-shown id))\n (str \"<rect class=\\\"flash\\\" x=\\\"\" (+ x grip) \"\\\" y=\\\"\" y \"\\\" width=\\\"\" (- w grip) \"\\\" height=\\\"\" h \"\\\" rx=\\\"3\\\"></rect>\"))\n (\"faust~\") (params-overlay id b x y w)\n (\"reader\" \"canvas\" \"freqt\") nil\n (when (own-view? b) (ctl-overlay id b x y)))\n (when (panel-layout b) (panel-overlay id b x y)))])\n ;; reading cursors are drawn over everything: they belong to the canvas they read, not to the reader\n parts (for [[id b] (:boxes p) :let [kc (klass (:text b))]]\n (case kc\n \"reader\" (when on\n (when-let [[_ {:keys [t from axis pt]}] (last-shown id)]\n (when-let [from (and from (number? t) (local-id from))] (cursor-at p from t \"cur\" true (or axis :x) pt))))\n (\"canvas\" \"freqt\") (when on\n (when-let [[at {:keys [t]}] (last-shown id)]\n (when (and (number? t) (< (- (eng/now) at) 2)) (cursor-at p id t \"cur2\" false))))\n nil))]\n (render-layers!)\n (refresh-html-boxes!)\n (let [scene ($ \"scene\")]\n (doseq [[id html] own]\n (when-let [slot (.querySelector scene (str \"g.live[data-live=\\\"\" (esc (name id)) \"\\\"]\"))]\n ;; only when it changed (a new scene makes new slots)\n (when (not= html (aget slot \"kairoticLive\")) (aset slot \"kairoticLive\" html) (set! (.-innerHTML slot) html)))))\n (set! (.-innerHTML ($ \"cursors\"))\n (str (apply str parts)\n (when-not @pres-mode ((:labels @probe-hooks) p))\n ;; in presentation the readers are usually hidden, but their cursors still show on the canvases\n (when (and @pres-mode on)\n (apply str (for [[id b] (:boxes (current))\n :when (and (= \"reader\" (klass (:text b))) (not (get-in p [:boxes id])))]\n (when-let [[_ {:keys [t from axis pt]}] (last-shown id)]\n (when-let [from (and from (number? t) (local-id from))]\n (cursor-at p from t \"cur\" true (or axis :x) pt))))))))))\n\n;; ───── the header of a box with data: ⇄ shows it in its next view, { } opens its data as text in the\n;; code window (discussion #30) ─────\n\n(defn next-view\n \"The view after the one a box shows now, if its class has more than one.\"\n [b]\n (let [vs (vec (comp/views-of b)) cur (view-of b)]\n (when (> (count vs) 1)\n (nth vs (mod (inc (or (first (keep-indexed (fn [i v] (when (= v cur) i)) vs)) 0)) (count vs))))))\n\n(defn header-chips\n \"[[kind label title] …] for the header of a box: from right to left.\"\n [id b]\n (let [nv (next-view b)]\n (cond-> []\n (and (comp/source-of b) (not= :code (display-of b)))\n (conj [:code \"{ }\" (str \"Its data as text, in the code window: (source \" id \")\")])\n nv (conj [:view (str \"⇄ \" (name nv)) (str \"Show it as \" (name nv) \": (view \" id \" \" nv \")\")]))))\n\n(def chip-ch 6.4) ; width of a character of a chip (10.5px mono)\n\n(defn chips-svg\n \"The chips drawn from the right edge `x1` of the header; returns [svg width].\"\n [id chips x1]\n (reduce (fn [[acc right] [kind label title]]\n (let [cw (+ 10 (* chip-ch (count label))) x (- right cw)]\n [(str acc \"<g class=\\\"hchip\\\" data-chip=\\\"\" (name kind) \"\\\" data-box=\\\"\" (esc (name id)) \"\\\">\"\n \"<rect x=\\\"\" x \"\\\" y=\\\"3\\\" width=\\\"\" cw \"\\\" height=\\\"\" (- hdr 6) \"\\\" rx=\\\"3\\\"></rect>\"\n \"<text x=\\\"\" (+ x (/ cw 2)) \"\\\" y=\\\"\" (- hdr 6) \"\\\" text-anchor=\\\"middle\\\">\" (esc label) \"</text>\"\n \"<title>\" (esc title) \"</title></g>\")\n (- x 4)]))\n [\"\" x1] chips))\n\n(defn box-header [id b w]\n (let [tree-box? (= \"tree\" (klass (:text b)))\n [chips x1] (chips-svg id (header-chips id b) (- w 4))]\n (str \"<rect class=\\\"head\\\" x=\\\"0.5\\\" y=\\\"0.5\\\" width=\\\"\" (- w 1) \"\\\" height=\\\"\" (- hdr 1) \"\\\"></rect>\"\n \"<text class=\\\"lbl\\\" x=\\\"8\\\" y=\\\"14\\\">\" (esc (:text b)) \"</text>\"\n \"<text class=\\\"lbl info\\\" x=\\\"\" (- x1 (if (seq chips) 2 4)) \"\\\" y=\\\"14\\\" text-anchor=\\\"end\\\">\"\n (esc (cond\n (= :code (display-of b)) (str (:language (box-def b)) \" · ✎\")\n tree-box? (if-let [t (mtb/tree-of (:data b))] (mt/summary t) \"empty\")\n (= :html (display-of b)) (let [n (hic/outlets (hic/view-of (:data b)))] (str n (if (= 1 n) \" outlet\" \" outlets\")))\n :else (cond\n (live-tree id) (str \"tree · \" (mt/summary (live-tree id)) \" · (keep! \" id \")\")\n (kept-tree b) (str \"kept · \" (mt/summary (kept-tree b))\n (when-let [f (:from (:recipe b))] (str \" · from \" f)))\n :else (str (when (= :score (display-of b)) (if (cv/generic? (canvas-data b)) \"approx. · \" (str \"quantized\" (when (:quant (canvas-data b)) \" (quant)\") \" · alt-click: divisions · \"))) (cv/summary (canvas-data b))\n (when (:recipe b) (str \" · changed since kept (remake! \" id \")\")))))) \"</text>\"\n chips)))\n\n(declare gesture!)\n\n(defn render-crumbs!\n \"Where the patch on screen is: work › :b5 patch voice › …\"\n []\n (let [path @view-path root (root-patch)]\n (set! (.-innerHTML ($ \"crumbs\"))\n (if (empty? path)\n \"\"\n (str \"<button data-up=\\\"\" (count path) \"\\\">work</button>\"\n (apply str (map-indexed\n (fn [i id]\n (let [b (get-in (patch-in root (take i path)) [:boxes id])\n label (esc (str id \" \" (:text b)))]\n (str \" › \" (if (= i (dec (count path)))\n (str \"<span class=\\\"here\\\">\" label \"</span>\")\n (str \"<button data-up=\\\"\" (- (count path) i 1) \"\\\">\" label \"</button>\")))))\n path)))))))\n\n;; ───── Present with boxes selected (issue #42): those not in the presentation yet can join it, where they are ─────\n\n(defn pres-ask-el []\n (or ($ \"pres-ask\")\n (let [el (js/document.createElement \"div\")]\n (set! (.-id el) \"pres-ask\")\n (set! (.-className el) \"perform-pop\")\n (set! (.-hidden el) true)\n (.appendChild (.-body js/document) el)\n (.addEventListener el \"click\"\n (fn [e]\n (when-let [a (.. e -target -dataset -pres)]\n (set! (.-hidden el) true)\n (case a\n \"cancel\" nil\n \"all\" (gesture! \"(presentation true)\")\n (do (gesture! (str \"(present-in-place \" a \")\"))\n (gesture! \"(presentation true)\"))))))\n el)))\n\n(defn unpresented-selection\n \"The selected boxes that are not in the presentation yet.\"\n []\n (let [p (current)] (vec (sort (filter (fn [id] (and (get-in p [:boxes id]) (not (get-in p [:boxes id :present])))) (sel-ids))))))\n\n(defn ask-present-selection!\n \"Asks whether the selected boxes `ids` should join the presentation, where they are in the patch.\"\n [ids]\n (let [el (pres-ask-el) n (count ids)]\n (set! (.-innerHTML el)\n (str \"<p><b>Present</b> · \" (if (= 1 n) \"the selected box is\" (str \"the \" n \" selected boxes are\"))\n \" not in the presentation yet. Present \" (if (= 1 n) \"it\" \"them\") \" where \" (if (= 1 n) \"it is\" \"they are\") \" in the patch?</p>\"\n \"<div class=\\\"pp-actions\\\">\"\n \"<button class=\\\"act primary\\\" data-pres=\\\"\" (esc (str/join \" \" ids)) \"\\\">Present the selection</button>\"\n \"<button class=\\\"act\\\" data-pres=\\\"all\\\">Present without \" (if (= 1 n) \"it\" \"them\") \"</button>\"\n \"<button class=\\\"act\\\" data-pres=\\\"cancel\\\">Cancel</button>\"\n \"</div>\"))\n (set! (.-hidden el) false)))\n\n(.addEventListener ($ \"pres-toggle\") \"click\"\n (fn [_]\n (let [ids (when-not @pres-mode (unpresented-selection))]\n (if (seq ids)\n (ask-present-selection! ids)\n (do (set! (.-hidden (pres-ask-el)) true)\n (gesture! (str \"(presentation \" (not @pres-mode) \")\")))))))\n\n(.addEventListener ($ \"crumbs\") \"click\"\n (fn [e] (when-let [n (.. e -target -dataset -up)] (gesture! (str \"(up \" n \")\")))))\n\n(declare render-inspector!)\n\n(defn render-scene [p]\n (let [p (scene-of p)\n {:keys [sel wire hover-in hover-out nsel ldrag]} @ui\n chosen (sel-ids)\n _ (doseq [[id b] (:boxes p) :when (= :score (display-of b))] (score-entry! id b))\n lines (map-indexed\n (fn [idx [a o b i :as l]]\n (if (and (get-in p [:boxes a]) (get-in p [:boxes b]))\n (let [[x1 y1] (out-xy p a o) [x2 y2] (in-xy p b i)\n s (str (if (= sel [:line l]) \" sel\" \"\")\n (when (and (= o 2) (= \"freqt\" (klass (get-in p [:boxes a :text])))) \" edits\")\n (when (and (not @pres-mode) ((:probed? @probe-hooks) l)) \" probed\"))\n buf (and (= i 1) (let [k (klass (get-in p [:boxes a :text]))] (or (music-classes k) (= \"sample\" k) (= \"tree\" k))))]\n (let [d (wire-d x1 y1 x2 y2)]\n (str \"<path class=\\\"wire\" s (when buf \" buffer\") \"\\\" d=\\\"\" d \"\\\"></path>\"\n \"<path class=\\\"wire-hit\\\" data-line=\\\"\" idx \"\\\" d=\\\"\" d \"\\\"></path>\")))\n \"\"))\n (:lines p))\n ;; from the bottom of the stack to the top (issue #166): the last one drawn is the one on top\n bxs (for [[id b] (by-z (:boxes p))]\n (let [[x y] (box-pos id b) t (:text b) [w h] (box-dims id b) [ins outs] (io b)\n kc (klass t)\n music-box? (contains? #{:canvas :score :html} (display-of b))\n code-box? (= :code (display-of b))\n ctl? (own-view? b)\n action-box? (or ctl? (contains? action-classes kc))\n cls (str \"box\" (when (kairos-classes kc) \" kairos\") (when (comp/subpatch? b) \" sub\") (when (line-ref? b) (str \" ref\" (when (:pin b) \" pinned\") (when (ref-warning b) \" warn\"))) (when (or music-box? code-box?) \" mus\") (when code-box? \" code\")\n (when action-box? (str \" act \" (if ctl? \"ctl\" kc)))\n (when (contains? chosen id) \" sel\") (when (= id (first hover-in)) \" drop\")\n (when (and (:present b) (not @pres-mode)) \" presented\") (when (panel-layout b) \" panel\"))\n idn (esc (name id))\n d (if (music? b) (shown-data id b) (canvas-data b))\n content (case (if music-box? (display-of b) kc)\n :canvas (let [dr (when (and ldrag (= (:box ldrag) id)) ldrag)\n g (if dr (:g dr) (canvas-geom d id b))]\n (cv/svg idn d g (when (= (first nsel) id) (second nsel))\n (when (and dr (= :move (:kind dr)) (:moved dr)) {(:tid dr) (:pts dr)})\n (when (and dr (= :draw (:kind dr))) (:pts dr))))\n :score (let [c (get @score-cache id)]\n (str \"<rect class=\\\"paper mus-body\\\" data-box=\\\"\" idn \"\\\" x=\\\"2\\\" y=\\\"\" hdr \"\\\" width=\\\"\" (- w 4) \"\\\" height=\\\"\" (- h hdr 2) \"\\\"></rect>\"\n \"<g class=\\\"score-slot\\\" data-box=\\\"\" idn \"\\\" transform=\\\"translate(4,\" (+ hdr 4) \")\\\"></g>\"\n (cond\n (nil? c) (str \"<text class=\\\"wait\\\" x=\\\"12\\\" y=\\\"\" (+ hdr 26) \"\\\">\"\n (if (= :error @vrv-status)\n \"Could not load Verovio (the notation): ⇄ shows it another way\"\n \"Loading the notation (Verovio, about 8 MB)…\")\n \"</text>\")\n (:error c) (str \"<text class=\\\"wait\\\" x=\\\"12\\\" y=\\\"\" (+ hdr 26) \"\\\">\"\n (esc (str \"Could not draw: \" (:error c))) \"</text>\"))))\n :html (html-slot-svg id b w h)\n \"bang\" (str \"<circle class=\\\"bangc\\\" cx=\\\"\" (+ grip (/ (- w grip) 2)) \"\\\" cy=\\\"\" (/ h 2) \"\\\" r=\\\"7\\\"></circle>\")\n \"msg\" (str \"<text x=\\\"\" (+ grip 6) \"\\\" y=\\\"16\\\">\" (esc (str/trim (subs (str/trim t) 3))) \"</text>\")\n (when ctl?\n (str \"<rect class=\\\"ctl-area\\\" x=\\\"\" grip \"\\\" y=\\\"0\\\" width=\\\"\" (- w grip) \"\\\" height=\\\"\" h \"\\\"><title>\"\n (esc (str t (when-let [u (:doc (box-def b))] (str \" — \" u)))) \"</title></rect>\")))]\n (str \"<g class=\\\"\" cls \"\\\" data-box=\\\"\" idn \"\\\" transform=\\\"translate(\" x \",\" y \")\\\">\"\n \"<rect class=\\\"body\\\" width=\\\"\" w \"\\\" height=\\\"\" h \"\\\" rx=\\\"3\\\"></rect>\"\n (cond code-box? (str (box-header id b w) (code-view id b w))\n music-box? (str (box-header id b w) content\n (when-not @pres-mode\n (str \"<path class=\\\"resize-corner\\\" data-box=\\\"\" idn \"\\\" d=\\\"M\" (- w 14) \" \" (- h 3) \" L\" (- w 3) \" \" (- h 14)\n \" L\" (- w 3) \" \" (- h 3) \" Z\\\"><title>Drag to resize\"\n (when (= :score (display-of b)) \" (its width; the height follows the notation)\")\n \" · double-click: default size</title></path>\")))\n (panel-layout b) (panel-svg id b w)\n action-box? (str \"<rect class=\\\"grip\\\" x=\\\"0\\\" y=\\\"0\\\" width=\\\"\" grip \"\\\" height=\\\"\" h \"\\\" rx=\\\"2\\\"></rect>\" content)\n ;; a patch @name: its line, followed (↻) or pinned (⌖ moment), ⚠ when something is wrong (#117)\n (line-ref? b) (str \"<text x=\\\"10\\\" y=\\\"16\\\">\" (esc t) \"</text>\"\n \"<text class=\\\"ref-badge\\\" x=\\\"\" (- w 8) \"\\\" y=\\\"16\\\" text-anchor=\\\"end\\\">\" (esc (ref-badge b)) \"</text>\"\n \"<title>\" (esc (or (ref-warning b)\n (let [r (resolve-ref b)]\n (str \"the line \" (line-name (:line r)) (if (:pinned r) \", pinned to a point of its history\" \", at its newest point\")\n \" · double-click opens it\"))))\n \"</title>\")\n :else (str \"<text x=\\\"10\\\" y=\\\"16\\\">\" (esc t) \"</text>\"))\n (apply str (for [i (range ins)]\n (str \"<rect class=\\\"port in\" (when (= hover-in [id i]) \" target\") \"\\\" data-box=\\\"\" idn \"\\\" data-in=\\\"\" i \"\\\" x=\\\"\" (port-x w ins i) \"\\\" y=\\\"-1\\\" width=\\\"\" pw \"\\\" height=\\\"4\\\"></rect>\")))\n (apply str (for [o (range outs)]\n (str \"<rect class=\\\"port out\" (when (= hover-out [id o]) \" hot\") \"\\\" data-box=\\\"\" idn \"\\\" data-out=\\\"\" o \"\\\" x=\\\"\" (port-x w outs o) \"\\\" y=\\\"\" (- h 3) \"\\\" width=\\\"\" pw \"\\\" height=\\\"4\\\"></rect>\")))\n ;; its id, over its top right corner: shown when it is hovered or selected, or for all with I\n ;; (issue #163)\n (when-not @pres-mode\n (str \"<text class=\\\"idtag\\\" x=\\\"\" w \"\\\" y=\\\"-5\\\" text-anchor=\\\"end\\\">\" idn \"</text>\"))\n ;; what changes while it plays (a value, a flash, its own view) is drawn here, in the box,\n ;; so that a box over it covers it too (issue #166); in patch coordinates\n \"<g class=\\\"live\\\" data-live=\\\"\" idn \"\\\" transform=\\\"translate(\" (- x) \",\" (- y) \")\\\"></g>\"\n \"</g>\")))\n temp (when (and wire (get-in p [:boxes (:from wire)]))\n (let [[x1 y1] (out-xy p (:from wire) (:out wire))]\n (str \"<path class=\\\"wire temp\\\" d=\\\"\" (wire-d x1 y1 (:x wire) (:y wire)) \"\\\"></path>\")))]\n ;; html boxes keep their own elements (issue #146): taken out before the scene is written, put back after\n (html-save-focus!)\n (set! (.-innerHTML ($ \"scene\")) (str (apply str lines) (apply str bxs) temp))\n (mount-html-slots!)\n ;; the paper grows with what is on it (with room to keep going), so nothing at the edge is cut off\n (let [[mx my] (reduce (fn [[mx my] [id b]]\n (let [[x y] (box-pos id b) [w h] (box-dims id b)]\n [(max mx (+ x w)) (max my (+ y h))]))\n [0 0] (:boxes p))\n cv ($ \"canvas\") st (.-style cv)]\n (if (and embed-mode (seq (:boxes p)))\n ;; embedded: the whole patch in the frame, scaled (a patch only shrinks; a presentation fills it)\n (let [[x0 y0] (reduce (fn [[ax ay] [id b]] (let [[x y] (box-pos id b)] [(min ax x) (min ay y)]))\n [js/Infinity js/Infinity] (:boxes p))\n pad 14 x0 (- x0 pad) y0 (- y0 pad)\n bw (- (+ mx pad) x0) bh (- (+ my pad) y0)\n wrap ($ \"canvas-wrap\") cw (max 1 (.-clientWidth wrap)) ch (max 1 (.-clientHeight wrap))\n fill? (= embed-mode :present)\n [vw vh] (if fill? [bw bh] [(max bw cw) (max bh ch)])]\n (.setAttribute cv \"viewBox\" (str x0 \" \" y0 \" \" vw \" \" vh))\n (.setAttribute cv \"preserveAspectRatio\" (if fill? \"xMidYMid meet\" \"xMinYMin meet\"))\n (set! (.-width st) \"100%\")\n (set! (.-height st) \"100%\"))\n (do (.removeAttribute cv \"viewBox\")\n ;; at least as wide as the pane (wider with the panel on the right hidden: issue #40)\n (set! (.-width st) (str (max 900 (or (some-> ($ \"canvas-wrap\") .-clientWidth) 0) (+ mx 160)) \"px\"))\n (set! (.-height st) (str (max 680 (+ my 200)) \"px\")))))\n (render-crumbs!)\n ;; scores already drawn are put back in their box, with the chosen stroke marked\n (doseq [slot (array-seq (.querySelectorAll ($ \"scene\") \".score-slot\"))]\n (let [id (keyword (.. slot -dataset -box)) c (get @score-cache id)]\n (when-let [node (:node c)]\n (.appendChild slot node)\n ;; the note selected for editing (Study 20)\n (doseq [el (array-seq (.querySelectorAll node \".tsel\"))] (.remove (.-classList el) \"tsel\"))\n (when-let [ts (:tsel @ui)]\n (when (= (:score ts) id)\n (when-let [pid (tsel-piece-id ts (:pieces c))]\n (when-let [el (.querySelector node (str \"#\" pid))] (.add (.-classList el) \"tsel\")))))\n (when (empty? (:anchors c))\n (swap! score-cache assoc-in [id :anchors] (score-anchors node (:pieces c))))\n (doseq [el (array-seq (.querySelectorAll node \"g.note.sel\"))] (.remove (.-classList el) \"sel\"))\n (when (= (first nsel) id)\n (doseq [el (array-seq (.querySelectorAll node (str \"[id^=\\\"n-\" (name id) \"-\" (name (second nsel)) \"-\\\"]\")))]\n (.add (.-classList el) \"sel\"))))))\n (render-overlay!)\n (render-inspector!)))\n\n;; ───── inspector: the selected box, editable from the patch ─────\n;; Under a box opened with ⌘/Ctrl+click (a plain click only selects and moves it): its class and usage,\n;; one field per declared argument (:args) and its whole text. Changing a field rewrites the box with\n;; (text! …), as if it had been typed.\n\n(defonce insp-key (atom nil))\n\n(defn arg-kind [v] (cond (boolean? v) :flag (or (number? v) (keyword? v)) :num :else :word))\n\n(defn spec-of [d]\n (let [sp (:args d)] (when (and (sequential? sp) (seq sp) (every? (fn [x] (and (vector? x) (keyword? (first x)))) sp)) sp)))\n\n(defn insp-field [a v cur]\n (case (arg-kind v)\n :flag (str \"<label><input type=\\\"checkbox\\\" data-arg=\\\"\" (name a) \"\\\"\" (when cur \" checked\") \"> \" (name a) \"</label>\")\n :num (str \"<label>\" (name a) \" <input data-arg=\\\"\" (name a) \"\\\" value=\\\"\" (if (number? cur) (cv/fmt cur) \"\") \"\\\" size=\\\"6\\\" inputmode=\\\"decimal\\\"></label>\")\n (str \"<label>\" (name a) \" <input data-arg=\\\"\" (name a) \"\\\" value=\\\"\" (esc (if (keyword? cur) (name cur) (str (or cur \"\")))) \"\\\" size=\\\"8\\\"></label>\")))\n\n(defonce insp-busy (atom false))\n\n(defn insp-commit! [input]\n (let [id (first @insp-key) b (when id (get-in (current) [:boxes id]))]\n (when b\n (let [d (box-def b) role (.. input -dataset -role) arg (.. input -dataset -arg)]\n (reset! insp-busy true)\n (try (cond\n (= role \"text\")\n (let [v (str/trim (.-value input))]\n (when (and (seq v) (not= v (:text b))) (gesture! (str \"(text! \" id \" \" (pr-str v) \")\"))))\n arg\n (let [a (keyword arg) sv (some (fn [[k v]] (when (= k a) v)) (spec-of d))\n vals (comp/args-for d (:text b)) raw (str/trim (.-value input))\n nv (case (arg-kind sv)\n :flag (.-checked input)\n :num (let [n (js/parseFloat raw)] (if (js/isNaN n) (get vals a) n))\n (when (seq raw) (keyword raw)))\n t (comp/args-text d (klass (:text b)) (assoc vals a nv))]\n (when (not= t (:text b)) (gesture! (str \"(text! \" id \" \" (pr-str t) \")\")))))\n (finally (reset! insp-busy false)))))))\n\n(defn render-inspector! []\n (let [old ($ \"inspector\") [kind id] (:sel @ui)\n moving? (let [d (:drag @ui)] (and d (:moved d))) ; hidden while a box is being moved\n b (when (and (= kind :box) (= id (:insp @ui)) (not @pres-mode) (not moving?)) (get-in (current) [:boxes id]))\n k (when b [id (:text b) (:x b) (:y b) (cmd-path)])\n focused (.-activeElement js/document)]\n ;; a field being edited is applied before the inspector goes away or is redrawn\n (when (and old (not @insp-busy) (not= k @insp-key) (.contains old focused) (= \"INPUT\" (.-tagName focused)))\n (insp-commit! focused))\n (cond\n (nil? b) (do (reset! insp-key nil) (when old (.remove old)))\n (= k @insp-key) nil\n :else\n (let [d (box-def b) spec (spec-of d) vals (when spec (comp/args-for d (:text b)))\n [_ h] (box-dims id b)\n el (or old (let [el (js/document.createElement \"div\")]\n (set! (.-id el) \"inspector\")\n (.addEventListener el \"change\" (fn [e] (insp-commit! (.-target e))))\n ;; what a patch box can do with lines (#117): extract it to one, or pin, follow, inline the one it uses\n (.addEventListener el \"click\"\n (fn [e]\n (when-let [a (some-> (.closest (.-target e) \"[data-insp-act]\") (.getAttribute \"data-insp-act\"))]\n (let [id (first @insp-key)]\n (if (= a \"extract-line\")\n (let [nm (str/trim (.-value (.querySelector el \"[data-role=line-name]\")))]\n (when (seq nm) (gesture! (str \"(extract-line \" id \" \" (pr-str nm) \")\"))))\n (gesture! (str \"(\" a \" \" id \")\")))))))\n (.addEventListener el \"keydown\"\n (fn [e] (case (.-key e)\n \"Enter\" (.blur (.-target e))\n \"Escape\" (do (reset! insp-key nil) (swap! ui assoc :insp nil) (render-inspector!))\n nil)))\n (.appendChild ($ \"canvas-wrap\") el)\n el))]\n (reset! insp-key k)\n (set! (.-title el) (or (:doc d) \"\"))\n (let [[px py] (wrap-px (:x b) (+ (:y b) h 8))]\n (set! (.. el -style -left) (str px \"px\"))\n (set! (.. el -style -top) (str py \"px\")))\n (set! (.-innerHTML el)\n (str \"<div class=\\\"insp-head\\\"><b>\" (esc (klass (:text b))) \"</b> <span>\" (esc (or (:usage d) \"\")) \"</span></div>\"\n (when spec (str \"<div class=\\\"insp-args\\\">\" (apply str (for [[a v] spec] (insp-field a v (get vals a)))) \"</div>\"))\n \"<input class=\\\"insp-text\\\" data-role=\\\"text\\\" spellcheck=\\\"false\\\" value=\\\"\" (esc (:text b)) \"\\\">\"\n (cond\n (line-ref? b)\n (str \"<div class=\\\"insp-acts\\\">\"\n (if (:pin b)\n \"<button class=\\\"act\\\" data-insp-act=\\\"follow-ref\\\" title=\\\"Follow its line again (its newest point)\\\">Follow</button>\"\n \"<button class=\\\"act\\\" data-insp-act=\\\"pin-ref\\\" title=\\\"Keep it at the point of its line it reads now\\\">Pin</button>\")\n \"<button class=\\\"act\\\" data-insp-act=\\\"inline-ref\\\" title=\\\"A copy of the line inside this box, detached from it\\\">Inline</button>\"\n \"<button class=\\\"act\\\" data-insp-act=\\\"open-ref\\\" title=\\\"Open its line, in its tab\\\">Open line</button></div>\")\n (and (embedded? b) (not @perf) (not @scratch))\n (str \"<div class=\\\"insp-acts\\\"><input data-role=\\\"line-name\\\" placeholder=\\\"line name\\\" size=\\\"12\\\" spellcheck=\\\"false\\\" aria-label=\\\"Name of the new line\\\">\"\n \"<button class=\\\"act\\\" data-insp-act=\\\"extract-line\\\" title=\\\"A new line with what this patch has, and its history inside the box; the box uses it\\\">Extract to line</button></div>\")\n :else \"\")))))))\n\n;; ───── engine: start, stop and messages ─────\n\n(defn transport-info! []\n (let [on (eng/running?)]\n (set! (.-textContent ($ \"transport-info\"))\n (cond (not on) \"engine stopped\"\n ;; it plays another line than the one on screen (#117): which\n (playing-elsewhere?) (let [n (count (view-instances))]\n (str \"playing \" (line-name (playing-line))\n (case n 0 \"\" 1 (str \" · \" (line-name (active-line)) \" inside it\")\n (str \" · \" (line-name (active-line)) \" ×\" n \": what you play goes to all\"))))\n :else \"engine running\"))\n (.toggle (.-classList ($ \"play\")) \"on\" on)))\n\n(declare sync-live-trees!)\n\n(defn live! []\n (when (eng/running?)\n (when (sync-live-trees!) (render-scene (current)))\n (render-overlay!)\n (let [ps (eng/take-prints!)]\n (doseq [[_ v label] (take 12 ps)] (repl-print! \"out\" (esc (print-line v label))))\n (when (> (count ps) 12) (repl-print! \"out\" (esc (str \"print: … and \" (- (count ps) 12) \" more\")))))\n (js/requestAnimationFrame (fn [_] (live!)))))\n\n(defn play\n \"Starts the engine and fires the loadbang boxes. Everything else acts when messages reach it.\"\n []\n (let [was-on (eng/running?)]\n ;; the line on screen is the one that plays from now on (#117, decision 6)\n (swap! line-state assoc :playing (active-line))\n (eng/start! engine-patch true)\n (transport-info!)\n (when-not was-on (js/requestAnimationFrame (fn [_] (live!))))\n :running))\n\n(defn stop\n \"Stops the engine: silence, and ramps, metros and counters go back to their initial state.\"\n []\n (eng/stop!)\n (transport-info!)\n (render-overlay!)\n ;; back to the initial state: the data boxes send what they hold again, so what depends on them has it\n (refill-data!)\n :stopped)\n\n(defn send!\n \"Sends a message to a box, as if it came through a line: (send! :b5 2.5) · (send! :b4 0 [0 8 2]) · (send! :b8 :bang).\"\n ([id v] (send! id 0 v))\n ([id inlet v]\n (need-box id)\n (let [was-on (eng/running?)]\n (let [[tid ti] (target id inlet)] (inject-local! tid ti v))\n (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!))))\n v)))\n\n;; ───── the Code tab and the REPL line: CodeMirror once it is loaded (14-editor.cljs), a textarea and an\n;; input until then (or if it cannot be loaded). Everything reads and writes them through these.\n\n(defonce code-ed (atom nil)) ; the editor of the Code tab\n(defonce repl-ed (atom nil)) ; the editor of the REPL line\n\n(defn code-text [] (if-let [e @code-ed] (.getValue e) (.-value ($ \"code\"))))\n(declare code-tab-refresh!)\n(defn set-code-text! [v] (if-let [e @code-ed] (when (not= v (.getValue e)) (.setValue e v) (code-tab-refresh!)) (set! (.-value ($ \"code\")) v)))\n(defn repl-text [] (if-let [e @repl-ed] (.getValue e) (.-value ($ \"repl-in\"))))\n(defn set-repl-text! [v] (if-let [e @repl-ed] (do (.setValue e v) (.cursorToEnd e)) (set! (.-value ($ \"repl-in\")) v)))\n(defn focus-repl! [] (if-let [e @repl-ed] (.focus e) (.focus ($ \"repl-in\"))))\n\n(defonce data-ed (atom nil)) ; the read-only editor of the Data view of the Code tab\n\n(defn data-view? [] (= :data (:code-view @ui)))\n\n(defn set-data-text! [v]\n (if-let [e @data-ed]\n (when (not= v (.getValue e)) (.setValue e v))\n (when (not= v (.-textContent ($ \"edn\"))) (set! (.-textContent ($ \"edn\")) v))))\n\n(defn render-code [p]\n (let [{:keys [dirty]} @ui data (data-view?)]\n (when-not dirty (set-code-text! (patch->code p)))\n ;; the data is written only while it is shown: it is the whole state, pretty-printed\n (when data (set-data-text! (patch->edn p)))\n (let [st ($ \"code-state\")]\n (set! (.-textContent st) (cond data \"read-only: the state the history produces\"\n dirty \"edited: run it to apply it to the patch\"\n :else \"in sync with the patch\"))\n (set! (.-className st) (if (and dirty (not data)) \"state dirty\" \"state\")))\n (set! (.-hidden ($ \"code-run\")) data)\n (set! (.-hidden ($ \"code-revert\")) data)\n (set! (.-disabled ($ \"code-run\")) (not dirty))\n (set! (.-disabled ($ \"code-revert\")) (not dirty))))\n","page/03-history-view.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 4 of 12: history-view\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── interface: history ─────────────────────────\n\n(def palette [\"#2f55d4\" \"#b4472e\" \"#2e7d4f\" \"#8a4fbf\" \"#b07a12\" \"#167c88\" \"#c0457e\"])\n\n(defn hash-color [s]\n (nth palette (mod (reduce (fn [a c] (mod (+ (* a 31) (.charCodeAt c 0)) 1000003)) 7 (str s)) (count palette))))\n\n(defn author-color [a] (or (not-empty (get-in @profiles [a :color])) (hash-color a)))\n(defn session-color [s] (hash-color (str \"session\" s)))\n(defn peer-color [p] (session-color (or (:session p) (:peer p))))\n(defn person-name [a] (or (not-empty (get-in @profiles [a :name])) (if (= a (my-author)) \"you\" \"someone\")))\n\n(defn valid-pos? [p] (and (vector? p) (= 2 (count p)) (string? (first p)) (number? (second p))))\n\n(defn same-line?\n \"Is peer p on the line on screen? (A position is a point of one line: the others' are not drawn here.)\"\n [p] (= (or (:line p) main-line) (active-line)))\n\n(defn lane-layout\n \"One lane per line: the first segment that continues at the tip of another shares its lane;\n the other children (branches) open a new lane.\"\n []\n (let [ns (vals (:nodes @hist))\n ids (set (map :id ns))\n kids (group-by :parent ns)\n roots (sort-by (fn [n] (or (:t n) 0)) (filter (fn [n] (or (nil? (:parent n)) (not (ids (:parent n))))) ns))\n lane-of (atom {})\n order (atom [])\n counter (atom -1)\n visit (fn visit [n lane seen]\n (when-not (seen (:id n))\n (swap! lane-of assoc (:id n) lane)\n (swap! order conj n)\n (let [cs (sort-by (fn [c] [(:at c) (or (:t c) 0)]) (get kids (:id n)))\n cont (first (filter (fn [c] (= (:at c) (count (:events n)))) cs))\n seen2 (conj seen (:id n))]\n (when cont (visit cont lane seen2))\n (doseq [c cs :when (not= (:id c) (:id cont))]\n (visit c (swap! counter inc) seen2)))))]\n (doseq [r roots] (visit r (swap! counter inc) #{}))\n {:order @order :lane-of @lane-of :lanes (inc @counter)}))\n\n(def hx 18)\n(def hy 26)\n(def hx0 30)\n(def hy0 34)\n\n(declare mark-picked!) ; 16-release.cljs: the points chosen to be forgotten (issue #45)\n\n(defn render-tree! []\n (let [{:keys [order lane-of lanes]} (lane-layout)\n ls order\n svg ($ \"tree\")\n h @hist\n show-empty (and (empty? ls) (:loaded h) (#{:shared :readonly :solo :local} (:mode h)))]\n (set! (.-hidden ($ \"hist-empty\")) (not show-empty))\n (set! (.. svg -style -display) (if (empty? ls) \"none\" \"block\"))\n (when (seq ls)\n (let [starts (into {} (for [n ls] [(:id n) (start-of (:id n))]))\n X (fn [d] (+ hx0 (* d hx)))\n Y (fn [i] (+ hy0 (* i hy)))\n maxd (apply max 1 (for [n ls] (+ (starts (:id n)) (count (:events n)))))\n w (+ (X maxd) 48)\n ht (+ (Y (dec lanes)) 24)\n ticks (for [d (range 0 (inc maxd) 8)]\n (str \"<line class=\\\"tick\\\" x1=\\\"\" (X d) \"\\\" x2=\\\"\" (X d) \"\\\" y1=\\\"20\\\" y2=\\\"\" (- ht 6) \"\\\"></line>\"\n \"<text class=\\\"axis\\\" x=\\\"\" (X d) \"\\\" y=\\\"13\\\" text-anchor=\\\"middle\\\">\" d \"</text>\"))\n body (for [n ls]\n (let [i (lane-of (:id n)) s (starts (:id n)) cnt (count (:events n)) y (Y i)\n c (session-color (node-session n)) nid (esc (:id n))\n who (person-name (:author n))\n pl (when (:parent n) (lane-of (:parent n)))\n [mn mk] (when (vector? (:merge n)) (:merge n))\n ml (when mn (lane-of mn))]\n (str (when (and pl (not= pl i))\n (str \"<path class=\\\"fork\\\" stroke=\\\"\" c \"\\\" d=\\\"M\" (X s) \" \" (Y pl) \" V\" y \"\\\"></path>\"))\n (when (and ml (starts mn))\n (let [x1 (X (+ (starts mn) mk)) y1 (Y ml) x2 (X (+ s 1))]\n (str \"<path class=\\\"merge\\\" stroke=\\\"\" c \"\\\" d=\\\"M\" x1 \" \" y1 \" C\" (+ x1 30) \" \" y1 \" \" (- x2 30) \" \" y \" \" x2 \" \" y \"\\\"></path>\")))\n (when (pos? cnt)\n (str \"<line class=\\\"lane\\\" stroke=\\\"\" c \"\\\" stroke-opacity=\\\"0.5\\\" x1=\\\"\" (X s) \"\\\" x2=\\\"\" (X (+ s cnt)) \"\\\" y1=\\\"\" y \"\\\" y2=\\\"\" y \"\\\"></line>\"))\n (when-not pl\n (str \"<circle class=\\\"origin\\\" data-goto=\\\"\" nid \"|0\\\" cx=\\\"\" (X s) \"\\\" cy=\\\"\" y \"\\\" r=\\\"4.5\\\"><title>origin</title></circle>\"))\n (apply str\n (map-indexed\n (fn [k ev]\n (let [mark? (= :merge-from (first ev))\n ;; a snapshot, or a take kept from Perform: a keyframe of the work\n key? (= :mark (first ev))\n xk (X (+ s k 1))]\n (cond\n key?\n (let [{:keys [label kind]} (when (map? (second ev)) (second ev))]\n (str \"<rect class=\\\"ev keyframe\" (when (= kind :take) \" take\") \"\\\" data-goto=\\\"\" nid \"|\" (inc k) \"\\\"\"\n \" x=\\\"\" (- xk 5.5) \"\\\" y=\\\"\" (- y 5.5) \"\\\" width=\\\"11\\\" height=\\\"11\\\" rx=\\\"2\\\" stroke=\\\"\" c \"\\\">\"\n \"<title>\" (esc (str who \" · \" (if (= kind :take) \"take kept from Perform\" \"snapshot\")\n (when (seq (str label)) (str \": \" label)))) \"</title></rect>\"))\n :else\n (str \"<\" (if mark? \"rect\" \"circle\") \" class=\\\"ev\" (when mark? \" mergemark\") \"\\\" data-goto=\\\"\" nid \"|\" (inc k) \"\\\"\"\n (if mark?\n (str \" x=\\\"\" (- xk 5) \"\\\" y=\\\"\" (- y 5) \"\\\" width=\\\"10\\\" height=\\\"10\\\" transform=\\\"rotate(45 \" xk \" \" y \")\\\"\")\n (str \" cx=\\\"\" xk \"\\\" cy=\\\"\" y \"\\\" r=\\\"4.5\\\"\"))\n \" fill=\\\"\" c \"\\\">\"\n \"<title>\" (esc (str who \" · \" (if mark? \"merge\" (let [t (pr-str ev)] (if (> (count t) 90) (str (subs t 0 90) \"…\") t))))) \"</title></\"\n (if mark? \"rect\" \"circle\") \">\"))))\n (:events n))))))\n mark (fn [pos r cls color]\n (let [p (norm pos)]\n (when (and p (lane-of (first p)))\n (str \"<circle class=\\\"\" cls \"\\\" cx=\\\"\" (X (+ (starts (first p)) (second p))) \"\\\" cy=\\\"\" (Y (lane-of (first p)))\n \"\\\" r=\\\"\" r \"\\\"\" (when color (str \" stroke=\\\"\" color \"\\\"\")) \"></circle>\"))))\n others (filter (fn [p] (and (not (:same p)) (:pos p) (same-line? p))) @peers)\n peer-marks (map-indexed (fn [k p] (mark (:pos p) (+ 11 (* 3 k)) \"peer\" (peer-color p))) others)]\n (.setAttribute svg \"width\" w)\n (.setAttribute svg \"height\" ht)\n (set! (.-innerHTML svg)\n (str (apply str ticks) (apply str body) (apply str peer-marks) (mark (:pos @world) 8 \"here\" nil)\n ;; in Perform: the point the take starts from\n (when-let [st @perf] (mark (:origin st) 13 \"perform-at\" nil))))\n (mark-picked! svg)))))\n\n(defn scroll-to-here! []\n (let [p (norm (:pos @world)) wrap ($ \"hist-wrap\")]\n (when p\n (let [x (+ hx0 (* hx (depth-of p)))\n l (.-scrollLeft wrap) vw (.-clientWidth wrap)]\n (when (or (< x (+ l 30)) (> x (- (+ l vw) 30)))\n (set! (.-scrollLeft wrap) (max 0 (- x (/ vw 2)))))))))\n\n(defn render-peers! []\n (let [others (remove (fn [p] (or (:same p) (= \"agent\" (:kind p)))) @peers)\n f (:follow @ui)]\n (set! (.-innerHTML ($ \"peers\"))\n (str \"<span class=\\\"chip me\\\"><span class=\\\"dot\\\" style=\\\"background:\" (esc (session-color session-id)) \"\\\"></span>you</span>\"\n (apply str\n (for [p others]\n (let [nm (if (:me p) \"you, another tab\" (or (not-empty (get-in @profiles [(:by p) :name])) \"Someone\"))\n col (peer-color p)\n on (= f (:peer p))\n nm (if (same-line? p) nm (str nm \" · on \" (line-name (:line p))))]\n (str \"<button class=\\\"chip\" (when on \" following\") \"\\\" data-peer=\\\"\" (esc (:peer p))\n \"\\\" title=\\\"\" (if on \"Stop following\" \"Follow their position in the history\") \"\\\">\"\n \"<span class=\\\"dot\\\" style=\\\"background:\" (esc col) \"\\\"></span>\" (esc nm) (when on \" · following\") \"</button>\"))))))))\n\n(defn render-foot! []\n (let [{:keys [mode nodes]} @hist\n p (norm (:pos @world))\n total (reduce + (map (comp count :events) (vals nodes)))\n n (when p (node (first p)))\n ahead (when n (- (count (:events n)) (second p)))\n mine? (and n (= (node-session n) session-id))\n who (when n (if mine? \"by this session\" (str \"by \" (person-name (:author n)) (when (= (:author n) (my-author)) \", another session\"))))\n kids (when (and n (zero? ahead)) (children-at (first p) (second p)))]\n (set! (.-innerHTML ($ \"hist-foot\"))\n (str \"<span>\" (if p (str \"Moment \" (depth-of p) \" · segment \" (esc who)) \"No events yet\") \"</span>\"\n \"<span>\" (count nodes) (if (= 1 (count nodes)) \" segment · \" \" segments · \") total \" events</span>\"\n (cond\n (:merge-pick @ui)\n \"<span class=\\\"ahead\\\">Pick in the tree the point of the branch you want to bring here · Esc to cancel</span>\"\n (and ahead (pos? ahead))\n (str \"<span class=\\\"ahead\\\">\" ahead (if (= 1 ahead) \" event\" \" events\") \" further along this branch: if you act here, you open a new branch</span>\")\n (seq kids)\n \"<span class=\\\"ahead\\\">This line continues further on: if you act here, you open a new branch</span>\"\n (:auto @world)\n \"<span>Following the front: you move forward with anyone's gestures</span>\")\n \"<span style=\\\"margin-left:auto\\\">\"\n (case mode\n :shared \"Shared room: whoever enters it sees and extends the same tree.\"\n :solo \"Solo: only you see this work.\"\n :readonly \"You can walk through the history; your branches stay in this tab.\"\n :local \"Local mode: the history lives only in this tab.\"\n :none \"Open or create a work from the session manager.\"\n \"Connecting to the shared history…\")\n \"</span>\"))))\n\n(defn render-status! []\n (let [{:keys [mode]} @hist p (current) n (count (remove :same @peers))]\n (set! (.-innerHTML ($ \"status\"))\n (str (case mode\n :shared \"<b class=\\\"on\\\">● shared room</b>\"\n :solo \"<b class=\\\"on\\\">● solo</b>\"\n :readonly \"<b class=\\\"off\\\">● read only</b>\"\n :local \"<b class=\\\"off\\\">● local</b>\"\n :none \"<b>○ no work open</b>\"\n \"<b>○ connecting…</b>\")\n \" · \" (count (:boxes p)) \" boxes · \" (count (:lines p)) \" wires\"\n (when (pos? n) (str \" · \" (inc n) \" in the room\"))))))\n\n(declare render-comp!)\n\n;; ───── data that flows by itself (Study 21) ─────\n;; A tree box sends its tree whenever it changes (an edit, the history moving, someone in the room), at\n;; most once per moment and only if it really changed; `tree manual` waits for a bang. A tree box that\n;; receives edits or trees changes itself through a gesture of the work; one that keeps being rewritten\n;; by messages (a loop without time) is stopped.\n\n(defonce sent-trees (atom {})) ; engine id → the tree it last sent\n(defonce sent-data (atom {})) ; engine id → [text data] a data box (a class with :sends) last sent\n(defonce emit-timer (atom nil))\n(defonce msg-edits (atom {})) ; box → instants it was changed by messages; :stopped #{boxes}\n(defonce echoed (atom {})) ; engine id → the text a gesture here wrote after sending its value\n\n(defn drain-prints!\n \"What boxes printed (and the loops the engine cut), written in the REPL when the engine is off too.\"\n []\n (doseq [[_ v label] (eng/take-prints!)]\n (let [t (if (string? v) v (pr-str v))]\n (if (and (nil? label) (re-find #\"^(loop cut|too many messages)\" t))\n (repl-print! \"err\" (esc (str \"; \" t)))\n (repl-print! \"out\" (esc (print-line v label)))))))\n\n(declare sync-live-trees!)\n\n(defonce sent-shape (atom nil)) ; the boxes and lines the trees were last sent through\n\n(defn reaching\n \"The boxes from which one of `goal` can be reached along `lines` (the goal boxes included).\"\n [lines goal]\n (loop [acc (set goal)]\n (let [more (into acc (keep (fn [[a _ b _]] (when (acc b) a)) lines))]\n (if (= (count more) (count acc)) acc (recur more)))))\n\n(defn emit-trees!\n \"Every tree box sends its tree when it changed. When the patch changed (a new line, a box new or with a\n new text), a tree goes again only toward what needs it: along its lines that lead to one of those\n boxes (Study 23). A control whose value stays in its text (:persist, a knob) sends it when that text\n changes: from another tab, a jam or a moment of the history (issue #11); not after a drag here,\n which already sent it.\"\n []\n (reset! emit-timer nil)\n (let [p (eng/flat (engine-patch))\n shape [(:lines p) (into {} (map (fn [[id b]] [id (:text b)])) (:boxes p))]\n [old-lines old-texts] @sent-shape\n changed (when (not= shape @sent-shape)\n (into (set (for [[f text] (second shape) :when (not= text (get old-texts f))] f))\n (let [olds (set old-lines)] (for [l (:lines p) :when (not (olds l))] (nth l 2)))))\n upstream (when (seq changed) (reaching (:lines p) changed))]\n (when changed\n ;; a box that is new, or whose text changed, starts empty: nothing of what an earlier box with\n ;; that id showed or held\n (doseq [[f text] (second shape) :when (not= text (get old-texts f))]\n (eng/forget! f)\n (swap! live-trees dissoc f)\n (swap! score-cache dissoc f))\n (reset! sent-shape shape)\n (doseq [[f text] (second shape)\n :when (and old-texts (contains? old-texts f) (not= text (get old-texts f))\n (:persist (comp/lookup (klass text))))]\n (if (= text (get @echoed f))\n (swap! echoed dissoc f)\n (try (eng/inject! engine-patch f 0 :bang)\n (catch :default e (js/console.error e))))))\n (doseq [[f b] (:boxes p)\n :when (and (= \"tree\" (klass (:text b))) (not (some #{:manual} (eng/args-of (:text b)))))]\n (let [t (mtb/tree-of (:data b))]\n (when (some? t)\n (try\n (cond\n ;; the tree changed: it goes everywhere\n (or (not= t (get @sent-trees f)) (contains? changed f))\n (do (swap! sent-trees assoc f t)\n (eng/emit! engine-patch f 0 (mt/expand-source t f)))\n ;; the patch after it changed: only along the lines that lead there\n upstream\n (let [targets (set (for [[a o bb ii] (:lines p) :when (and (= a f) (= o 0) (upstream bb))] [bb ii]))]\n (when (seq targets)\n (eng/emit-to! engine-patch f 0 (mt/expand-source t f) targets))))\n (catch :default e (js/console.error e))))))\n ;; the same for the data boxes of other classes: a class with :sends (fn [box] value) sends that\n ;; value when the text or data of the box changed (a pbind sends its pattern), and again only toward\n ;; what changed after it. A value that is not ready yet (a source still compiling) goes once it is.\n (doseq [[f b] (:boxes p)\n :let [d (comp/lookup (klass (:text b)))]\n :when (fn? (:sends d))]\n (let [k [(:text b) (:data b)]\n v (try ((:sends d) {:id f :text (:text b) :args (comp/args-for d (:text b)) :data (:data b)})\n (catch :default e (js/console.error e) nil))]\n (when (some? v)\n (try\n (cond\n (or (not= k (get @sent-data f)) (contains? changed f))\n (do (swap! sent-data assoc f k)\n (eng/emit! engine-patch f 0 v))\n upstream\n (let [targets (set (for [[a o bb ii] (:lines p) :when (and (= a f) (= o 0) (upstream bb))] [bb ii]))]\n (when (seq targets)\n (eng/emit-to! engine-patch f 0 v targets))))\n (catch :default e (js/console.error e)))))))\n (when (sync-live-trees!) (render-scene (current)))\n (drain-prints!))\n\n(defn schedule-emit! [] (when-not @emit-timer (reset! emit-timer (js/setTimeout emit-trees! 30))))\n\n(defn refill-data! \"Every tree box (and data box) sends its value again (after ■).\" [] (reset! sent-trees {}) (reset! sent-data {}) (schedule-emit!))\n\n(defn forget-box!\n \"A box that is created or deleted starts from nothing: what a box with its id showed and held is forgotten.\"\n [id]\n (let [f (fid id)]\n (eng/forget! f)\n (swap! live-trees dissoc f)\n (swap! dismissed-trees dissoc f)\n (swap! sent-trees dissoc f)\n (swap! sent-data dissoc f)\n (swap! score-cache dissoc id)))\n\n(defn resume!\n \"Lets a tree box be changed by messages again, after a loop was stopped: (resume! :b2).\"\n [id] (swap! msg-edits (fn [m] (-> m (update :stopped disj id) (dissoc id)))) :ok)\n\n(defn tree-effect!\n \"A tree box or a canvas asked (by a message) to change: done as a gesture, unless it keeps happening.\"\n [f [k x] _]\n (js/setTimeout\n (fn []\n (let [id f now (js/Date.now)\n times (filterv (fn [t] (> t (- now 10000))) (get @msg-edits id))]\n (cond\n (not (get-in (current) [:boxes id]))\n (repl-print! \"err\" (esc (str \"; \" (name f) \" is inside a sub-patch: edits by message reach only the boxes of the patch on screen\")))\n (contains? (:stopped @msg-edits) id) nil\n (>= (count times) 20)\n (do (swap! msg-edits update :stopped (fnil conj #{}) id)\n (repl-print! \"err\" (esc (str \"; loop stopped: \" id \" was rewritten by messages 20 times in 10 seconds. Look for a line that brings its own tree back to it; (resume! \" id \") lets messages change it again.\"))))\n :else\n (do (swap! msg-edits assoc id (conj times now))\n (case k\n :tree-edit (gesture! (str \"(tree-edit! \" id \" \" (str/join \" \" (map pr-str x)) \")\"))\n :tree-set (gesture! (str \"(tree! \" id \" \" (pr-str x) \")\"))\n :canvas-edit (gesture! (str \"(canvas-edit! \" id \" \" (pr-str x) \")\"))\n ;; what a box found (a task's outcome), kept as its data: only if it can be written back as\n ;; it is (the history is code) and is not too long for the history and the room\n :keep (let [code (str \"(keep! \" id \" \" (pr-str x) \")\")]\n (cond\n (> (count code) keep-limit)\n (repl-print! \"err\" (esc (str \"; \" id \": too long to keep in the work (\" (count code) \" characters, \"\n keep-limit \" at most); it is still sent, and kept only in this tab\")))\n (not= x (try (clojure.edn/read-string (pr-str x)) (catch :default _ ::unreadable)))\n (repl-print! \"err\" (esc (str \"; \" id \": what it found cannot be written as EDN, so it is not kept in the work\")))\n :else (gesture! code)))\n nil)))))\n 0))\n\n(swap! eng/rt assoc :effect-hook tree-effect!)\n(js/setInterval (fn [] (when-not (eng/running?) (drain-prints!))) 200)\n\n(defn sync-live-trees!\n \"Takes the trees that canvases and freqts have received from the engine. True if any changed.\"\n []\n (let [changed (atom false)]\n (doseq [[id b] (:boxes (current)) :when (#{\"canvas\" \"freqt\"} (klass (:text b)))]\n (let [f (fid id) t (:tree (second (shown-flat f)))]\n (when (and t (not= t (get @live-trees f)) (not= t (get @dismissed-trees f)))\n (swap! dismissed-trees dissoc f)\n (swap! live-trees assoc f t)\n (reset! changed true))))\n @changed))\n\n(defn render-all! []\n (sync-live-trees!)\n (schedule-emit!)\n (let [p (current)\n ;; the classes of the line that plays too, while it plays from another tab (#117)\n changed (lib/sync! (eng/flat (if @scratch (root-patch) (engine-patch))))]\n (when changed (reset! eng/flat-cache [nil nil]))\n ;; the Components tab lists the definitions of the work: drawn again when they or their status change\n (render-comp! true)\n (render-scene p)\n (render-code p)\n (render-tree!)\n (render-peers!)\n (render-foot!)\n (render-status!)\n (update-trust-bar!)))\n\n;; ───────────────────────── presence and following ─────────────────────────\n\n(defonce named-room (atom nil))\n\n(defn publish-presence! []\n (when-let [room @named-room]\n ;; also with no position (an empty line): the others still learn which line you are on\n (let [p (:pos @world)]\n ;; in a jam (Perform in a shared room): from which point, so others can be invited to it\n (let [{:keys [jam origin]} @perf]\n (.catch (.presence room (clj->js (cond-> {:pos p :session session-id :line (active-line)}\n jam (assoc :jam jam :jamAt (or (:at @perf) origin)))))\n (fn [_] nil))))))\n\n(defn sync-follow! []\n (when-let [f (:follow @ui)]\n (if-let [p (first (filter (fn [p] (= (:peer p) f)) @peers))]\n (let [pos (:pos p)]\n ;; following someone onto another line: their tab first (#117)\n (when-not (same-line? p) (switch-line! (:line p)))\n (when (and (valid-pos? pos) (node (first pos)) (not= pos (:pos @world)))\n (swap! world assoc :pos pos)))\n (swap! ui assoc :follow nil))))\n\n(defonce asked (atom #{}))\n\n(defn want-profiles! []\n (when-let [u @userref]\n (let [ids (disj (set (concat (keep :author (vals (:nodes @hist))) (keep :by @peers))) \"local\" nil)]\n (when (and (seq ids) (not= ids @asked))\n (reset! asked ids)\n (-> (.profiles u (clj->js (vec ids)))\n (.then (fn [ps]\n (reset! profiles\n (into {} (for [k (array-seq (.keys js/Object ps))]\n (let [p (aget ps k)] [k {:name (.-name p) :color (.-color p)}])))))))))))\n\n(defn render-controls! []\n (set! (.-checked ($ \"auto\")) (boolean (:auto @world)))\n (let [inp ($ \"simul\")]\n (when-not (= inp (.-activeElement js/document))\n (set! (.-value inp) (str (:simul-ms @settings)))))\n (let [b ($ \"merge-btn\")]\n (set! (.-textContent b) (if (:merge-pick @ui) \"Cancel merge\" \"Merge…\"))\n (.toggle (.-classList b) \"primary\" (boolean (:merge-pick @ui)))))\n\n(add-watch hist ::render (fn [_ _ _ _] (reset! cache {}) (auto-advance!) (render-all!) (want-profiles!)))\n(add-watch world ::render (fn [_ _ o n] (render-all!) (render-controls!) (scroll-to-here!) (when (not= (:pos o) (:pos n)) (publish-presence!))))\n(add-watch settings ::render (fn [_ _ _ _] (render-controls!)))\n(add-watch peers ::render (fn [_ _ _ _] (sync-follow!) (render-tree!) (render-peers!) (render-status!) (want-profiles!)))\n(add-watch profiles ::render (fn [_ _ _ _] (render-tree!) (render-peers!) (render-foot!)))\n(add-watch ui ::render\n (fn [_ _ o n]\n (when (not= (select-keys o [:sel :insp :drag :wire :hover-in :nsel :ldrag]) (select-keys n [:sel :insp :drag :wire :hover-in :nsel :ldrag]))\n (render-scene (current)))\n (when (not= (:follow o) (:follow n)) (render-peers!))\n (when (not= (:merge-pick o) (:merge-pick n)) (render-controls!) (render-foot!))))\n\n;; ───────────────────────── REPL ─────────────────────────\n\n(defn repl-eval! [code source]\n ;; a gesture that writes a long source (a package copied into the work) is shown shortened\n (repl-print! (str \"in\" (when (= source :patch) \" from-patch\"))\n (str \"<span class=\\\"p\\\">\" (if (= source :patch) \"⟵\" \"λ\") \"</span>\"\n (esc (if (and (= source :patch) (> (count code) 240)) (str (subs code 0 200) \" … (\" (count code) \" characters)\") code))))\n (try\n (let [v (eval-str code)]\n (when (= source :repl) (repl-print! \"out\" (esc (pr-str v)))))\n (catch :default e\n (repl-print! \"err\" (esc (or (.-message e) (str e)))))))\n\n(defn gesture! [code] (repl-eval! code :patch))\n\n(defn repl-submit!\n \"Evaluates what is written in the REPL line, keeps it in its history and empties the line.\"\n []\n (let [code (str/trim (repl-text))]\n (when (seq code)\n (swap! ui (fn [u] (-> u (update :hist conj code) (assoc :hidx nil))))\n (set-repl-text! \"\")\n (repl-eval! code :repl))))\n\n(defn repl-recall!\n \"↑ / ↓ in the REPL line: the earlier or later expressions written there.\"\n [up?]\n (let [{:keys [hist hidx]} @ui n (count hist)]\n (when (pos? n)\n (let [i (if up?\n (if (nil? hidx) (dec n) (max 0 (dec hidx)))\n (if (nil? hidx) nil (if (>= (inc hidx) n) nil (inc hidx))))]\n (swap! ui assoc :hidx i)\n (set-repl-text! (if (nil? i) \"\" (nth hist i)))\n true))))\n\n(.addEventListener ($ \"repl-in\") \"keydown\"\n (fn [e]\n (let [k (.-key e)]\n (cond\n (= k \"Enter\") (repl-submit!)\n (or (= k \"ArrowUp\") (= k \"ArrowDown\")) (when (repl-recall! (= k \"ArrowUp\")) (.preventDefault e))))))\n","page/04-panels.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 5 of 12: panels\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── component library ─────────────────────────\n;; Whatever is imported or taken from the library is copied into a component box of the work.\n\n(defonce shared-lib (atom {})) ; class → {:class :source :doc :version :author :t}\n\n(defn doc-id [cls-name] (str/replace (str cls-name) #\"[^A-Za-z0-9_\\-]\" \"_\"))\n\n(defn component-slot\n \"Where a new component box goes. A definition is not drawn in the patch (it is listed in the Components\n tab, issue #8), so its place on the paper means nothing: the corner.\"\n [] [0 0])\n\n(defn new-definition!\n \"Creates, as gestures written in code, a component box with this source.\"\n [source]\n (let [id (next-id) [x y] (component-slot)]\n (gesture! (str \"(box \" id \" \\\"component\\\" \" x \" \" y \")\"))\n (gesture! (str \"(code \" id \" \" (pr-str source) \")\"))\n id))\n\n(declare select-tab! open-code-editor-at! wrap-path render-comp!)\n\n(defn new-component!\n \"A new component of the work, from a template (or the source given), opened in the code window, with\n the Components tab in sight.\"\n ([] (new-component! lib/template))\n ([source]\n (let [id (new-definition! source)]\n (select-tab! \"comp\")\n (js/setTimeout (fn [] (open-code-editor-at! (cmd-path) id)) 0)\n id)))\n\n(defn definitions-in\n \"The component boxes of patch p and of the patches embedded in it: [[path id box] …], path being the\n way down from the patch the work starts at.\"\n ([p] (definitions-in p []))\n ([p path]\n (let [bs (sort-by (fn [[k _]] (box-num k)) (:boxes p))]\n (concat (for [[id b] bs :when (definition? b)] [path id b])\n (mapcat (fn [[id b]] (when (embedded? b) (definitions-in (or (:data b) empty-patch) (conj path id))))\n bs)))))\n\n(defn definitions\n \"The components this work defines, as the Components tab lists them: [[path id class status] …].\"\n []\n (vec (for [[path id b] (definitions-in (root-patch))\n :let [r (cbox/compiled \"component\" (str (get-in b [:data :source])))]]\n [path id (get-in r [:info :class]) (:status r)])))\n\n(defn import!\n \"Copies a published component into the work: \\\"npm:package@version/path.mjs\\\" (jsDelivr) or a file\n of this page (\\\"kairotic/packages/controls.mjs\\\"). It stays as an editable component box.\"\n [origin]\n (-> (lib/import-module origin)\n (.then (fn [m]\n (if (:package m)\n (let [id (new-definition! (lib/package-source m origin))]\n (repl-print! \"out\" (esc (str \"; imported \" (:package m) \" \" (:version m) \" (\"\n (str/join \", \" (map :class (:components m))) \") into \" id))))\n (let [id (new-definition! (str (lib/header m origin) (:source m)))]\n (repl-print! \"out\" (esc (str \"; imported «\" (:class m) \"» into \" id)))))))\n (.catch (fn [e] (repl-print! \"err\" (esc (str \"Could not import \" origin \": \" (or (.-message e) e)))))))\n :importing)\n\n;; ───── official packages: brought into the work when one of their classes is written ─────\n\n(defonce fetching (atom #{}))\n\n(defn work-package?\n \"Whether the work (at its top level or the sub-patch on screen) already carries package `pkg`.\"\n [pkg]\n (let [needle (str \":package \" (pr-str pkg))]\n (some (fn [p] (some (fn [[_ b]] (and (= \"component\" (klass (:text b)))\n (str/includes? (str (get-in b [:data :source])) needle)))\n (:boxes p)))\n [(current) (root-patch)])))\n\n(defn add-package!\n \"Brings an official package into the work, as one component box pinned to its version:\n (add-package! \\\"@kairotic/synth\\\"). It is looked for on npm and, if it is not there yet, in this page.\"\n [pkg]\n (when-not (get lib/packages pkg) (fail (str \"Unknown package \" pkg \": see (packages)\")))\n (when-not (or (@fetching pkg) (work-package? pkg))\n (swap! fetching conj pkg)\n (let [line (active-line)]\n (-> (lib/import-package pkg)\n (.then (fn [[m origin]]\n ;; into the line it was asked for: if another one is on screen by now, it comes when that\n ;; one is back (switch-line! brings what its boxes need)\n (when-not (or (work-package? pkg) (not= line (active-line)))\n (let [src (lib/package-source m origin)\n _ (swap! cbox/trusted conj src) ; official: it runs without asking\n id (new-definition! src)]\n (repl-print! \"out\" (esc (str \"; \" pkg \" \" (:version m) \" (\"\n (str/join \", \" (map :class (:components m))) \") is now in the work: \" id\n (when-not (str/starts-with? origin \"npm:\") \" · from this page\"))))))))\n (.catch (fn [e] (repl-print! \"err\" (esc (str \"Could not bring \" pkg \": \" (or (.-message e) e))))))\n (.finally (fn [] (swap! fetching disj pkg))))))\n pkg)\n\n(defn packages\n \"The official packages and their classes: [[package version [class …]] …].\"\n []\n (vec (for [[n p] (sort-by key lib/packages)] [n (:version p) (vec (sort (:classes p)))])))\n\n(defn ensure-class!\n \"If box text t uses a class nobody defines yet but an official package does, brings it into the work.\"\n [t]\n (let [k (klass t)]\n (when-let [[pkg _] (and (not (comp/lookup k)) (lib/package-of k))]\n (add-package! pkg))))\n\n(defn publish\n \"Saves the definition of a component box to the shared library of this space (a new version).\"\n [id]\n (let [b (need-box id)]\n (when-not (= \"component\" (klass (:text b))) (fail (str id \" is not a component box\")))\n (let [source (str (get-in b [:data :source])) r (cbox/compiled \"component\" source)]\n (when-not (= :ok (:status r)) (fail \"The definition does not compile yet: fix it before publishing it\"))\n (when-not (and @dbref (:writable @hist)) (fail \"No shared library available (you need to be signed in and able to write)\"))\n (let [cls-name (get-in r [:info :class]) prev-entry (get @shared-lib cls-name)\n v (inc (or (:version prev-entry) 0))]\n (-> (.set (.doc @dbref (str \"library/\" (doc-id cls-name)))\n (clj->js {:class cls-name :source source :doc (str (:doc (:value r))) :version v\n :author (my-author) :t (js/Date.now)}))\n (.then (fn [_] (repl-print! \"out\" (esc (str \"; «\" cls-name \"» version \" v \" published to the library\")))))\n (.catch db-failed!))\n [cls-name v]))))\n\n(defn library\n \"The components of the shared library: [[class version doc] …].\"\n []\n (vec (for [[c m] (sort-by key @shared-lib)] [c (:version m) (:doc m)])))\n\n(defn use!\n \"Copies a component of the shared library into the work.\"\n [cls-name]\n (let [m (or (get @shared-lib (str cls-name)) (fail (str \"The library has no «\" cls-name \"»: see (library)\")))]\n (new-definition! (str \";; \" (:class m) \" v\" (:version m) \" · from the library of this space\\n\" (:source m)))))\n\n(defn listen-library! [db]\n (.onSnapshot (.collection db \"library\")\n (fn [snap]\n (reset! shared-lib (into {} (for [d (array-seq (.-docs snap)) :when (.-exists d)\n :let [m (js->clj (.data d) :keywordize-keys true)]\n :when (and (string? (:class m)) (string? (:source m)))]\n [(:class m) m]))))\n (fn [_] nil)))\n\n(defonce chosen-def (atom nil)) ; [path id]: the component chosen in the tab (for Claude's \"change the selected component\")\n\n(defn def-row\n \"A row of the Components tab for the component box id (in the sub-patch at path): what it defines,\n whether it compiles, and what can be done with it.\"\n [path id b]\n (let [r (cbox/compiled \"component\" (str (get-in b [:data :source])))\n cls (get-in r [:info :class])\n f (eng/flat-id (into (view-prefix) path) id)\n used (when cls (get @lib/work-classes cls))\n where (str (when (seq path) (str \"in \" (str/join \" › \" (map name path)) \" · \")) \"box \" (name id))\n attr (str \" data-path=\\\"\" (esc (pr-str path)) \"\\\" data-id=\\\"\" (esc (name id)) \"\\\"\")]\n (str \"<li class=\\\"def\" (when (= :error (:status r)) \" err\") (when (= @chosen-def [path id]) \" chosen\") \"\\\"\" attr\n \" title=\\\"Click to choose it (Claude can then change it); Edit opens its code\\\">\"\n \"<code>\" (esc (or cls \"—\")) \"</code>\"\n \"<span title=\\\"\" (esc (str where (when (:error r) (str \" · \" (:error r))))) \"\\\">\"\n (esc (case (:status r)\n :ok (str (or (get-in r [:info :summary]) \"ready\")\n (when (and used (not= (first used) f)) (str \" · not used: \" (name (first used)) \" defines it first\"))\n (when-let [d (:doc (second used))] (when (= (first used) f) (str \" · \" d))))\n :compiling \"compiling…\"\n :empty \"empty: write its definition\"\n (str \"✗ \" (first (str/split-lines (str (:error r)))))))\n \" <small>\" (esc where) \"</small></span>\"\n \"<button class=\\\"act\\\" data-def=\\\"edit\\\" title=\\\"Its code, in the code window\\\">Edit</button>\"\n (when (and (= :ok (:status r)) (empty? path) (not (:package (:value r))))\n \"<button class=\\\"act\\\" data-def=\\\"publish\\\" title=\\\"To the shared library of this space\\\">Publish</button>\")\n \"<button class=\\\"act\\\" data-def=\\\"delete\\\" title=\\\"Remove it from the work (one event of the history)\\\" aria-label=\\\"Delete\\\">×</button>\"\n \"</li>\")))\n\n(defonce comp-shown (atom nil)) ; what the tab last drew: it is drawn again only when that changes\n\n(defn render-comp!\n ([] (render-comp! false))\n ([only-if-changed?]\n (when-let [el ($ \"comp-list\")]\n (let [defs (definitions-in (root-patch))\n core-defs (filter (fn [[_ d]] (= :core (:origin d))) (sort-by key @comp/registry))\n sig [@chosen-def (vec (for [[path id b] defs] [path id (cbox/compiled \"component\" (str (get-in b [:data :source])))]))\n @lib/work-classes @shared-lib]\n row (fn [label detail button]\n (str \"<li><code>\" (esc label) \"</code><span>\" (esc detail) \"</span>\" button \"</li>\"))]\n (when-not (and only-if-changed? (= sig @comp-shown))\n (reset! comp-shown sig)\n (set! (.-innerHTML el)\n (str \"<h4>In this work</h4>\"\n (if (seq defs)\n (str \"<ul>\" (apply str (for [[path id b] defs] (def-row path id b))) \"</ul>\")\n \"<p class=\\\"empty\\\">None yet. The boxes that define components are kept here, not in the patch: they have no inlets nor outlets.</p>\")\n \"<p class=\\\"comp-new\\\"><button class=\\\"act primary\\\" data-def=\\\"new\\\">New component</button> \"\n \"<small>or import one, or ask Claude for it</small></p>\"\n \"<h4>Shared library</h4>\"\n (if (seq @shared-lib)\n (str \"<ul>\" (apply str (for [[c m] (sort-by key @shared-lib)]\n (row c (str \"v\" (:version m) (when (seq (:doc m)) (str \" · \" (:doc m))))\n (str \"<button class=\\\"act\\\" data-use=\\\"\" (esc c) \"\\\">Use</button>\"))))\n \"</ul>\")\n \"<p class=\\\"empty\\\">Empty: publish a definition of the work here to use it in others.</p>\")\n \"<h4>Import</h4>\"\n \"<form id=\\\"comp-import\\\"><input id=\\\"comp-origin\\\" placeholder=\\\"npm:package@1.0.0/comp.mjs or kairotic/packages/controls.mjs\\\" value=\\\"kairotic/packages/controls.mjs\\\">\"\n \"<button class=\\\"act\\\">Import</button></form>\"\n \"<h4>Core</h4><p class=\\\"core-defs\\\">\"\n (str/join \" \" (for [[c d] core-defs] (str \"<code class=\\\"help-link\\\" data-help=\\\"\" (esc c) \"\\\" title=\\\"\" (esc (:doc d)) \"\\\">\" (esc c) \"</code>\")))\n \"</p>\")))))))\n\n(defn choose-definition!\n \"Chooses a component box of the work in the Components tab (nil: none).\"\n [path id]\n (reset! chosen-def (when id [(vec path) id]))\n (render-comp!))\n\n(defn edit-definition!\n \"Opens the code of a component box of the work (in the sub-patch at path) in the code window.\"\n [path id]\n (choose-definition! path id)\n ;; from a sub-patch that does not hold it, the work is seen from its top first\n (when-not (= (cmd-path) (vec (take (count (cmd-path)) path))) (gesture! \"(top)\"))\n (open-code-editor-at! path id))\n\n(add-watch shared-lib ::comp (fn [_ _ _ _] (render-comp!)))\n\n(.addEventListener ($ \"panel-comp\") \"click\"\n (fn [e]\n (when-let [b (.closest (.-target e) \"[data-help]\")]\n (show-help! (.getAttribute b \"data-help\")))\n (when-let [b (.closest (.-target e) \"[data-use]\")]\n (gesture! (str \"(use! \" (pr-str (.getAttribute b \"data-use\")) \")\")))\n (when-let [b (.closest (.-target e) \"[data-publish]\")]\n (gesture! (str \"(publish :\" (.getAttribute b \"data-publish\") \")\")))\n (when-let [b (.closest (.-target e) \"[data-def]\")]\n (let [li (.closest b \"li[data-id]\")\n path (when li (clojure.edn/read-string (.getAttribute li \"data-path\")))\n id (when li (keyword (.getAttribute li \"data-id\")))]\n (case (.getAttribute b \"data-def\")\n \"new\" (gesture! \"(new-component!)\")\n \"edit\" (edit-definition! path id)\n \"publish\" (gesture! (str \"(publish \" id \")\"))\n \"delete\" (do (when-not (= (cmd-path) (vec (take (count (cmd-path)) path))) (gesture! \"(top)\"))\n (when (= @chosen-def [path id]) (reset! chosen-def nil))\n (gesture! (wrap-path path (str \"(delete \" id \")\"))))\n nil)))\n ;; a click on the row itself chooses it\n (when-let [li (and (not (.closest (.-target e) \"button\")) (.closest (.-target e) \"li.def[data-id]\"))]\n (let [path (clojure.edn/read-string (.getAttribute li \"data-path\")) id (keyword (.getAttribute li \"data-id\"))]\n (choose-definition! (when-not (= @chosen-def [path id]) path) (when-not (= @chosen-def [path id]) id))))))\n\n(.addEventListener ($ \"panel-comp\") \"submit\"\n (fn [e]\n (.preventDefault e)\n (let [v (str/trim (.-value ($ \"comp-origin\")))]\n (when (seq v) (gesture! (str \"(import! \" (pr-str v) \")\"))))))\n\n;; ───────────────────────── code panel ─────────────────────────\n\n(defn run-panel-code! []\n (let [code (code-text)]\n (try\n (run-code! code)\n (swap! ui assoc :dirty false)\n (render-code (current))\n (repl-print! \"out\" \"; code run: the patch has been rebuilt (1 :load event)\")\n (catch :default e\n (repl-print! \"err\" (esc (str \"Error in the code: \" (or (.-message e) (str e)))))))))\n\n(.addEventListener ($ \"code\") \"input\" (fn [_] (when-not (:dirty @ui) (swap! ui assoc :dirty true) (render-code (current)))))\n(.addEventListener ($ \"code\") \"keydown\"\n (fn [e] (when (and (= (.-key e) \"Enter\") (or (.-ctrlKey e) (.-metaKey e)))\n (.preventDefault e) (run-panel-code!))))\n(.addEventListener ($ \"code-run\") \"click\" (fn [_] (run-panel-code!)))\n(.addEventListener ($ \"code-revert\") \"click\" (fn [_] (swap! ui assoc :dirty false) (render-code (current))))\n\n;; Calls / Data: the Code tab shows the work as calls (editable, run with Ctrl/⌘+Enter) or as data (the\n;; state the history produces, read-only). Edits not run yet stay in the calls while the data is shown.\n(defn show-code-view!\n \"Shows the work in the Code tab as :calls or :data.\"\n [v]\n (let [data (= v :data)\n panel ($ \"panel-code\")\n ;; once the editor is loaded, the hosts it put in place of the text area and the <pre>\n calls-el (or (.querySelector panel \".code-host\") ($ \"code\"))\n data-el (or (.querySelector panel \".data-host\") ($ \"edn\"))]\n (swap! ui assoc :code-view (if data :data :calls))\n (set! (.-hidden calls-el) data)\n (set! (.-hidden data-el) (not data))\n (.setAttribute ($ \"view-calls\") \"aria-pressed\" (str (not data)))\n (.setAttribute ($ \"view-data\") \"aria-pressed\" (str data))\n (render-code (current))))\n\n(.addEventListener ($ \"view-calls\") \"click\" (fn [_] (show-code-view! :calls)))\n(.addEventListener ($ \"view-data\") \"click\" (fn [_] (show-code-view! :data)))\n\n;; ───── the panel on the right (issue #40): hidden or shown, and as wide as you drag it ─────\n;; {:open bool :w px-or-nil}: nil keeps the proportion of the page. It is a preference of this browser, kept in\n;; localStorage, not part of the work. Opening a tab (Help with ? or F1, the Code tab…) shows it again.\n\n(defonce side\n (atom (merge {:open true :w nil}\n (try (some-> (.getItem js/localStorage \"kairotic.side\") (clojure.edn/read-string)\n (select-keys [:open :w]))\n (catch :default _ nil)))))\n\n(def side-min 260) ; the panel is never narrower than this\n(def patch-min 320) ; nor the patch\n\n(defn side-width-ok\n \"A width for the panel that leaves room for the patch, in a page area `total` wide.\"\n [w total] (js/Math.round (max side-min (min w (- total patch-min 12)))))\n\n(defn render-side! []\n (let [{:keys [open w]} @side wk (.querySelector js/document \".work\") t ($ \"side-toggle\")]\n (when wk\n (.toggle (.-classList wk) \"side-off\" (not open))\n (.toggle (.-classList wk) \"sized\" (boolean (and open w)))\n (if (and open w)\n (.setProperty (.-style wk) \"--side-w\" (str (side-width-ok w (.-clientWidth wk)) \"px\"))\n (.removeProperty (.-style wk) \"--side-w\")))\n (when t\n (set! (.-textContent t) (if open \"›\" \"‹\"))\n (set! (.-title t) (if open \"Hide the panel\" \"Show the panel (Code, Components, Help…)\"))\n (.setAttribute t \"aria-expanded\" (str (boolean open))))))\n\n(defn save-side! []\n (try (.setItem js/localStorage \"kairotic.side\" (pr-str @side)) (catch :default _ nil)))\n\n(defn set-side! [m]\n (when (not= (merge @side m) @side)\n (swap! side merge m)\n (save-side!)\n (render-side!)\n ;; the patch can use the room it gets (or gives back)\n (js/requestAnimationFrame (fn [_] (render-scene (current))))))\n\n(defn side-panel\n \"The panel on the right: (side-panel false) hides it, (side-panel true) shows it, (side-panel 480) shows it\n 480 px wide, (side-panel :auto) back to its proportion of the page. Without arguments, how it is.\"\n ([] @side)\n ([x]\n (cond (boolean? x) (set-side! {:open x})\n (number? x) (set-side! {:open true :w x})\n (= x :auto) (set-side! {:open true :w nil})\n :else (fail \"Use (side-panel true), (side-panel false), (side-panel 480) or (side-panel :auto).\"))\n @side))\n\n(.addEventListener ($ \"side-toggle\") \"click\" (fn [e] (.stopPropagation e) (side-panel (not (:open @side)))))\n(.addEventListener ($ \"side-hide\") \"click\" (fn [_] (side-panel false)))\n\n;; dragging the splitter: the panel takes the width from there to the right edge of the work\n(let [split ($ \"side-split\") drag (atom nil)]\n (.addEventListener split \"pointerdown\"\n (fn [e]\n (when (and (:open @side) (not (.closest (.-target e) \"button\"))\n (not (.-matches (.matchMedia js/window \"(max-width: 860px)\"))))\n (.preventDefault e)\n (.setPointerCapture split (.-pointerId e))\n (.add (.-classList split) \"dragging\")\n (reset! drag true))))\n (.addEventListener split \"pointermove\"\n (fn [e]\n (when @drag\n (let [wk (.querySelector js/document \".work\") r (.getBoundingClientRect wk)]\n (swap! side assoc :w (side-width-ok (- (.-right r) (.-clientX e) 6) (.-width r)))\n (render-side!)))))\n (doseq [ev [\"pointerup\" \"pointercancel\"]]\n (.addEventListener split ev\n (fn [_]\n (when @drag\n (reset! drag nil)\n (.remove (.-classList split) \"dragging\")\n (save-side!)\n (render-scene (current))))))\n (.addEventListener split \"dblclick\"\n (fn [e] (when-not (.closest (.-target e) \"button\") (side-panel (not (:open @side)))))))\n\n(.addEventListener js/window \"resize\" (fn [_] (render-side!)))\n(render-side!)\n\n(doseq [t (array-seq (.querySelectorAll js/document \".tab\"))]\n (.addEventListener t \"click\"\n (fn [_]\n (let [tab (.. t -dataset -tab)]\n ;; a tab asked for (a click, ? or F1, (docs …)) shows the panel if it was hidden\n (when-not (:open @side) (set-side! {:open true}))\n (doseq [x (array-seq (.querySelectorAll js/document \".tab\"))]\n (.setAttribute x \"aria-selected\" (str (= x t))))\n (doseq [[k pid] [[\"code\" \"panel-code\"] [\"comp\" \"panel-comp\"] [\"claude\" \"panel-claude\"] [\"help\" \"panel-help\"] [\"feedback\" \"panel-feedback\"] [\"talk\" \"panel-talk\"]]]\n (set! (.-hidden ($ pid)) (not= k tab)))\n ;; opened by itself, the Help tab shows its index (or the page it was on)\n (when (= tab \"help\") (refresh-help!))))))\n\n;; ───────────────────────── gestures in the history ─────────────────────────\n\n(.addEventListener ($ \"nav-back\") \"click\" (fn [_] (gesture! \"(rewind)\")))\n(.addEventListener ($ \"nav-fwd\") \"click\" (fn [_] (gesture! \"(forward)\")))\n(.addEventListener ($ \"nav-tip\") \"click\" (fn [_] (gesture! \"(tip)\")))\n(.addEventListener ($ \"start-example\") \"click\" (fn [_] (gesture! \"(load-example)\")))\n\n(declare toggle-pick!)\n\n(.addEventListener ($ \"tree\") \"click\"\n (fn [e]\n (when-let [el (.closest (.-target e) \"[data-goto]\")]\n (let [[nid k] (str/split (.getAttribute el \"data-goto\") #\"\\|\")]\n (cond\n ;; ⇧+click: a point chosen to be forgotten (issue #45)\n (and (.-shiftKey e) (not (:merge-pick @ui))) (toggle-pick! nid (js/parseInt k 10))\n (:merge-pick @ui)\n (do (swap! ui assoc :merge-pick false)\n (.remove (.-classList ($ \"hist-wrap\")) \"picking\")\n (gesture! (str \"(merge-from \" (pr-str nid) \" \" k \")\")))\n :else (gesture! (str \"(goto \" (pr-str nid) \" \" k \")\")))))))\n\n(.addEventListener ($ \"merge-btn\") \"click\"\n (fn [_]\n (let [on (not (:merge-pick @ui))]\n (swap! ui assoc :merge-pick on)\n (.toggle (.-classList ($ \"hist-wrap\")) \"picking\" on))))\n\n(.addEventListener ($ \"auto\") \"change\"\n (fn [e] (gesture! (str \"(front \" (.. e -target -checked) \")\"))))\n\n(.addEventListener ($ \"simul\") \"change\"\n (fn [e]\n (let [v (js/parseInt (.. e -target -value) 10)]\n (if (js/isNaN v)\n (render-controls!)\n (gesture! (str \"(simultaneity \" v \")\"))))))\n\n(.addEventListener ($ \"peers\") \"click\"\n (fn [e]\n (when-let [el (.closest (.-target e) \"[data-peer]\")]\n (let [pr (.getAttribute el \"data-peer\")]\n (swap! ui assoc :follow (if (= pr (:follow @ui)) nil pr))\n (sync-follow!)))))\n","page/05-gestures.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 6 of 12: gestures\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── gestures in the patch ─────────────────────────\n\n(def svg ($ \"canvas\"))\n\n(defn pt\n \"Pointer position in patch coordinates (even when the patch is shown scaled).\"\n [e]\n (let [p (.createSVGPoint svg)]\n (set! (.-x p) (.-clientX e))\n (set! (.-y p) (.-clientY e))\n (let [q (.matrixTransform p (.inverse (.getScreenCTM svg)))]\n [(.-x q) (.-y q)])))\n\n(defn closest [e sel] (.closest (.-target e) sel))\n\n;; on touch screens the pointer is captured: look at what is under the finger\n(defn under [e sel]\n (when-let [el (.elementFromPoint js/document (.-clientX e) (.-clientY e))] (.closest el sel)))\n\n(defn drop-target\n \"Where a wire would land: the box under the pointer (other than the source one) and its inlet nearest\n to the cursor, or else an inlet within reach above a box.\"\n [e wire]\n (or (when-let [el (under e \".box\")]\n (let [id (keyword (.. el -dataset -box)) b (get-in (current) [:boxes id])]\n (when (and b (not= id (:from wire)))\n (let [[ins _] (io b) [w _] (box-dims id b) [x _] (pt e)]\n (when (pos? ins)\n [id (apply min-key (fn [i] (js/Math.abs (- x (+ (:x b) (port-x w ins i) (/ pw 2))))) (range ins))])))))\n (let [[x y] (pt e) t (port-near (current) :in x y)]\n (when (and t (not= (first t) (:from wire))) t))))\n\n(declare upgrade-repl-line! close-repl-line!)\n\n(defn repl-line-run!\n \"Runs a line of the REPL written on the patch: in the REPL's history, printed in the REPL as usual, and what it\n gave shown in element out (in red if it is an error).\"\n [code out]\n (swap! ui (fn [u] (-> u (update :hist conj code) (assoc :hidx nil))))\n (let [n (.-childElementCount ($ \"repl-out\"))]\n (repl-eval! code :repl)\n (let [new (drop n (array-seq (.-children ($ \"repl-out\"))))\n last-el (last (filter (fn [k] (#{\"out\" \"err\"} (.-className k))) new))]\n (set! (.-className out) (str \"edit-out\" (when (and last-el (= \"err\" (.-className last-el))) \" err\")))\n (set! (.-textContent out) (if last-el (.-textContent last-el) \"\")))))\n\n(defn open-editor!\n \"The field to write a box (a new one at x y, or the text of box id). What starts with ( is a line of the REPL\n instead (issue #163): Enter evaluates it, shows what it gave under the field and leaves it open for the next\n one (↑ ↓ go through the REPL's history); Esc, or Enter on an empty line, closes it.\"\n [{:keys [id x y text]}]\n (when-let [old ($ \"box-edit\")] (.remove old))\n (when-let [old ($ \"box-edit-out\")] (.remove old))\n (close-repl-line!)\n (let [inp (js/document.createElement \"input\") done (atom false)\n out (js/document.createElement \"div\")\n repl? (atom false) hidx (atom nil)\n ;; once: removing the field makes it lose the focus, and its blur closes it too\n close! (fn [] (when-not @done (reset! done true) (.remove inp) (.remove out)))\n set-repl! (fn [on]\n (reset! repl? on)\n (.toggle (.-classList inp) \"as-repl\" on)\n (set! (.-placeholder inp) (if on \"(command) · Enter runs it · Esc closes\" \"canvas, reader, ramp 0 8 4, number, msg 1, synth~… · ( for a command\")))\n ;; a line of the REPL: run, print in the REPL as usual, and show what it gave here\n run! (fn [code] (reset! hidx nil) (repl-line-run! code out))\n finish (fn [commit?]\n (when-not @done\n (let [v (str/trim (.-value inp))]\n (cond\n (and @repl? commit? (seq v)) (do (run! v) (set! (.-value inp) \"\") (.focus inp))\n @repl? (close!)\n :else\n (do\n (close!)\n (when (and commit? (seq v) (not= v text))\n (cond\n ;; a component is defined in the Components tab, not drawn in the patch (issue #8)\n (and (= \"component\" (klass v)) (nil? id)) (gesture! \"(new-component!)\")\n id (do (gesture! (str \"(text! \" id \" \" (pr-str v) \")\"))\n (when (= \"component\" (klass v))\n (select-tab! \"comp\")\n (js/setTimeout (fn [] (open-code-editor-at! (cmd-path) id)) 0)))\n :else (gesture! (str \"(box \" (pr-str v) \" \" (js/Math.round x) \" \" (js/Math.round y) \")\")))))))))\n recall! (fn [dir]\n (let [h (:hist @ui) n (count h)]\n (when (pos? n)\n (let [i (case dir :up (max 0 (dec (or @hidx n))) :down (min n (inc (or @hidx n))))]\n (reset! hidx i)\n (set! (.-value inp) (if (< i n) (nth h i) \"\"))))))]\n (set! (.-id inp) \"box-edit\")\n (set! (.-className inp) \"edit\")\n (.setAttribute inp \"spellcheck\" \"false\")\n (set! (.-value inp) (or text \"\"))\n (set! (.-id out) \"box-edit-out\")\n (set! (.-className out) \"edit-out\")\n (set-repl! (and (nil? id) (str/starts-with? (str text) \"(\")))\n (let [[px py] (wrap-px x (- y 4))]\n (set! (.. inp -style -left) (str px \"px\"))\n (set! (.. inp -style -top) (str py \"px\"))\n (set! (.. out -style -left) (str px \"px\"))\n (set! (.. out -style -top) (str (+ py 32) \"px\")))\n (.appendChild ($ \"canvas-wrap\") inp)\n (.appendChild ($ \"canvas-wrap\") out)\n (.focus inp)\n (if @repl?\n (let [n (count (.-value inp))] (.setSelectionRange inp n n))\n (.select inp))\n ;; a new box whose text starts with ( is a line of the REPL; once it is one, it stays one, and becomes the\n ;; code editor of a line of the REPL (23-ids.cljs) as soon as that is loaded\n (when @repl? (upgrade-repl-line! inp x y close!))\n (.addEventListener inp \"input\"\n (fn [_] (when (and (nil? id) (not @repl?) (str/starts-with? (str/triml (.-value inp)) \"(\"))\n (set-repl! true)\n (upgrade-repl-line! inp x y close!))))\n (.addEventListener inp \"keydown\"\n (fn [e] (case (.-key e)\n \"Enter\" (do (.preventDefault e) (finish true))\n \"Escape\" (do (.preventDefault e) (finish false))\n \"ArrowUp\" (when @repl? (.preventDefault e) (recall! :up))\n \"ArrowDown\" (when @repl? (.preventDefault e) (recall! :down))\n nil)))\n ;; leaving it writes the box; a line of the REPL is closed without running it\n (.addEventListener inp \"blur\" (fn [_] (if @repl? (close!) (finish true))))))\n\n;; ───── typing a number into a numeric control (issue #32) ─────\n;; A double-click on a number box, on a component whose :gesture gives numbers (a knob), on a parameter\n;; of a code box (its slider or its value) or on such a control presented in the panel of a sub-patch\n;; opens a small field with its value. Enter, or leaving the field, applies what is typed as the same\n;; gesture a drag leaves in the history; Esc closes it with no change.\n\n(defn typed-number\n \"The number written in s, or nil: 440, -3.5, .25, 1e-3, a decimal comma (0,5) or a ratio (3/2).\"\n [s]\n (let [t (str/replace (str/trim (str s)) #\"\\s+\" \"\")\n t (if (and (str/includes? t \",\") (not (str/includes? t \".\"))) (str/replace t \",\" \".\") t)\n num (fn [u] (when (re-matches #\"[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?\" u)\n (let [v (js/Number u)] (when (js/isFinite v) v))))]\n (if-let [[_ a b] (re-matches #\"([^/]+)/([^/]+)\" t)]\n (let [x (num a) y (num b)] (when (and x y (not (zero? y))) (/ x y)))\n (num t))))\n\n(defn typed-str\n \"A typed number as it is written in the field and in the code of the gesture: up to six decimals, so\n it is kept as typed (a drag rounds what it sends to three) without the noise of a float.\"\n [v] (let [r (cv/round-to v 6)] (if (= r (js/Math.round r)) (str (js/Math.round r)) (str r))))\n\n(defn open-number-input!\n \"A small field over a numeric control at x y (patch coordinates), with its value. Enter, or leaving the\n field, gives the number typed to commit!; Esc closes it and calls cancel!, if given (it undoes what\n the first click of the double-click did). What is not a number is not applied: on Enter the field\n stays open and says so; on leaving it, it closes as with Esc. The field opens after the click that\n asked for it has ended, so that click does not take the focus away from it.\"\n [{:keys [x y value commit! cancel!]}]\n (js/setTimeout\n (fn []\n (when-let [old ($ \"num-edit\")] (.remove old))\n (let [inp (js/document.createElement \"input\") done (atom false)\n close! (fn [] (reset! done true) (.remove inp))\n finish (fn [how]\n (when-not @done\n (let [v (typed-number (.-value inp))]\n (cond\n (and (not= how :cancel) (some? v)) (do (close!) (commit! v))\n (= how :enter) (do (.add (.-classList inp) \"bad\")\n (set! (.-title inp) \"Not a number (440, -3.5, 0,5, 3/2) · Esc closes\"))\n :else (do (close!) (when cancel! (cancel!)))))))]\n (set! (.-id inp) \"num-edit\")\n (set! (.-className inp) \"edit num\")\n (.setAttribute inp \"inputmode\" \"decimal\")\n (.setAttribute inp \"aria-label\" \"Value\")\n (set! (.-value inp) (if (number? value) (typed-str value) \"\"))\n (let [[px py] (wrap-px x y)]\n (set! (.. inp -style -left) (str px \"px\"))\n (set! (.. inp -style -top) (str py \"px\")))\n (.appendChild ($ \"canvas-wrap\") inp)\n (.focus inp)\n (.select inp)\n (.addEventListener inp \"input\" (fn [_] (.remove (.-classList inp) \"bad\") (set! (.-title inp) \"\")))\n (.addEventListener inp \"keydown\"\n (fn [e] (case (.-key e)\n \"Enter\" (do (.preventDefault e) (finish :enter))\n \"Escape\" (do (.preventDefault e) (finish :cancel))\n nil)))\n (.addEventListener inp \"blur\" (fn [_] (finish :blur)))))\n 0))\n\n(defn double-click-on\n \"When this pointerdown is the second of a double-click on control k, the first click [k ms before];\n otherwise nil, and this click is remembered (with `before`, the value the control had before it). The\n first click redraws the box, so the browser's dblclick does not reach it: as for the code row, the\n double-click is detected here.\"\n [k before]\n (let [now (js/Date.now) [lk lt :as first-click] (:num-click @ui)]\n (if (and (= lk k) (< (- now lt) 450))\n (do (swap! ui assoc :num-click nil) first-click)\n (do (swap! ui assoc :num-click [k now before]) nil))))\n\n(defn el-box [el]\n (let [id (keyword (.. el -dataset -box)) b (get-in (current) [:boxes id])] [id (when b (view-box b))]))\n\n(defn pos-click!\n \"Ask a buffer for an exact position: the box sends it through its left outlet (and marks it).\"\n [id t]\n (gesture! (str \"(send! \" id \" \" (cv/fmt (max 0 t)) \")\")))\n\n(defn pts-code [pts] (str \"[\" (str/join \" \" (map (fn [[t f]] (str \"[\" (cv/fmt t) \" \" (cv/fmt f) \"]\")) pts)) \"]\"))\n\n;; ───── editing a tree from its score (Study 20) ─────\n;; A score that shows a tree coming from a tree box knows, for every note it draws, where that note is\n;; written (kairotic.mt/expand-source). Click a note to select it; ↑ ↓ change its pitch (⇧ an octave),\n;; + − double or halve its duration, ← → select the previous or next one, Delete turns it into a rest.\n;; A rest can be selected too: Enter makes it a note (the pitch of the note before it), ↑ ↓ a note a step\n;; above or below that one (⇧ an octave), and a letter a…g the nearest note of that name; on a note, a\n;; letter changes its pitch to the nearest one of that name.\n;; Every change is one (tree-edit! …) of the tree box: a node edit in its history.\n\n(defn tsel-piece-id\n \"The id, in the drawn score, of the selected note (it changes when the score is drawn again).\"\n [ts pieces]\n (or (when (some (fn [pc] (= (:id pc) (:id ts))) pieces) (:id ts))\n (:id (first (filter (fn [pc] (= (:src pc) (:src ts))) pieces)))))\n\n(defn select-tree-note! [score-id piece from]\n (swap! ui assoc :sel nil :nsel nil :tsel {:score score-id :from from :src (:src piece) :id (:id piece)})\n (render-scene (current)))\n\n(defn writable-target\n \"Edits that make a written note editable (a melody string becomes its nodes) and the path of the note:\n [ops path], or nil if it comes from a fragment (:defs).\"\n [t {:keys [src sub use rtm]}]\n (cond\n (or use rtm (nil? src)) nil\n (nil? sub) [[] src]\n :else (let [s (mt/node-at t src) nodes (mt/melody s) parent (pop src) idx (peek src)]\n [(into [[:remove src]] (map-indexed (fn [k n] [:insert (conj parent (+ idx k)) n]) nodes))\n (into (conj parent (+ idx (first sub))) (rest sub))])))\n\n(defn piece-midi\n \"The pitch (MIDI) of a piece of a score drawn from a tree, read from the written tree t; nil for a rest.\"\n [t {:keys [src sub]}]\n (let [n (mt/node-at t src)\n n (if (and sub (string? n))\n (let [x (nth (mt/melody n) (first sub) nil)] (if (next sub) (nth (mt/kids x) (second sub) nil) x))\n n)\n n (if (= :chord (mt/tag n)) (first (filter (fn [k] (= :note (mt/tag k))) (mt/kids n))) n)]\n (when (= :note (mt/tag n)) (mt/midi-of (mt/attrs n)))))\n\n(def letter-pcs {\"c\" 0 \"d\" 2 \"e\" 4 \"f\" 5 \"g\" 7 \"a\" 9 \"b\" 11})\n\n(defn nearest-pc\n \"The pitch nearest m whose pitch class is pc.\"\n [m pc]\n (let [r (js/Math.round m)]\n (first (sort-by (fn [x] (js/Math.abs (- x m))) (filter (fn [x] (= pc (mod x 12))) (range (- r 6) (+ r 7)))))))\n\n(defn tree-key!\n \"A key on the selected note (or rest) of a score.\"\n [k shift?]\n (let [{:keys [score from] :as ts} (:tsel @ui)\n pieces (get-in @score-cache [score :pieces])\n cur (tsel-piece-id ts pieces)\n order (vec (filter :src pieces))\n i (first (keep-indexed (fn [i pc] (when (= (:id pc) cur) i)) order))]\n (cond\n (= k \"Escape\") (do (swap! ui assoc :tsel nil) (render-scene (current)))\n (#{\"ArrowLeft\" \"ArrowRight\"} k)\n (when i (let [j (max 0 (min (dec (count order)) (+ i (if (= k \"ArrowLeft\") -1 1))))]\n (select-tree-note! score (nth order j) from)))\n :else\n (let [t (tree-data from)\n [pre target] (or (writable-target t (:src ts))\n (fail (if (:rtm (:src ts))\n \"That note comes from a proportional rhythm (:rtm): edit its :shares or :pitches\"\n \"That note comes from a fragment (:defs): edit the fragment, or write it out\")))\n t1 (reduce mt/apply-op t pre)\n n (mt/node-at t1 target)\n parent (mt/node-at t1 (pop target))\n in-chord? (= :chord (mt/tag parent))\n dur-path (if in-chord? (pop target) target)\n dn (mt/node-at t1 dur-path)\n eff (or (:dur (mt/attrs dn)) (:dur (mt/attrs (mt/node-at (mt/explicit t1) dur-path))) 1)\n nxt-path (conj (pop dur-path) (inc (peek dur-path)))\n nxt (mt/node-at t1 nxt-path)\n keep-next (when (and (mt/node? nxt) (#{:note :rest :chord} (mt/tag nxt)) (nil? (:dur (mt/attrs nxt))))\n [[:attrs nxt-path (assoc (mt/attrs nxt) :dur eff)]])\n ;; the pitch a rest becomes: from the note before it in the score (or after it), else B4\n staff (:staff (nth order (or i 0) nil))\n same (fn [pcs] (filter (fn [pc] (= staff (:staff pc))) pcs))\n near (or (last (keep (fn [pc] (piece-midi t (:src pc))) (same (take (or i 0) order))))\n (first (keep (fn [pc] (piece-midi t (:src pc))) (same (drop (inc (or i 0)) order))))\n 71)\n to-note (fn [m] [[:set dur-path (mt/make :note (assoc (dissoc (mt/attrs n) :dur) :pitch (mt/pitch-name (js/Math.round m)) :dur eff) [])]])\n letter (get letter-pcs (str/lower-case k))\n edits (case (if (and (= :rest (mt/tag n)) (#{\"ArrowUp\" \"ArrowDown\" \"Enter\"} k)) :rest->note (if letter :letter k))\n :rest->note\n (into (to-note (case k \"ArrowUp\" (+ near (if shift? 12 1)) \"ArrowDown\" (- near (if shift? 12 1)) near)) keep-next)\n :letter\n (case (mt/tag n)\n :rest (into (to-note (nearest-pc near letter)) keep-next)\n :note [[:attrs target (mt/set-midi (mt/attrs n) (nearest-pc (mt/midi-of (mt/attrs n)) letter))]]\n nil)\n (\"ArrowUp\" \"ArrowDown\")\n (when (= :note (mt/tag n))\n (let [m (mt/midi-of (mt/attrs n)) d (* (if shift? 12 1) (if (= k \"ArrowUp\") 1 -1))]\n [[:attrs target (mt/set-midi (mt/attrs n) (+ m d))]]))\n ;; another name for the same sound: c#4 → db4 → b##3 …\n \"#\"\n (when (= :note (mt/tag n))\n (let [a (mt/attrs n) m (js/Math.round (mt/midi-of a))\n names (mapv sp/->name (sp/spellings m))\n cur (some-> (mt/spelling-of a) sp/->name)]\n [[:attrs target (assoc a :pitch (get names (mod (inc (max -1 (.indexOf names cur))) (count names))))]]))\n (\"+\" \"=\" \"-\")\n (into [[:attrs dur-path (assoc (mt/attrs dn) :dur (* eff (if (= k \"-\") 0.5 2)))]] keep-next)\n (\"Delete\" \"Backspace\")\n (if (and in-chord? (> (count (filter mt/node? (mt/kids parent))) 1))\n [[:remove target]]\n (into [[:set dur-path [:rest {:dur eff}]]] keep-next))\n nil)]\n (when (seq edits)\n (let [ops (into pre edits)]\n (if (= score from)\n ;; a tree box shown as a score (discussion #30): its notes edit its own tree, directly\n (do (swap! ui assoc :tsel (assoc ts :src {:src (if (#{\"Delete\" \"Backspace\"} k) dur-path target)} :id nil))\n (gesture! (str \"(tree-edit! \" from \" \" (str/join \" \" (map pr-str ops)) \")\")))\n ;; a score box: the edits leave it by its third outlet; connected back to the tree box, they\n ;; change it, and the tree, changed, comes back to the score\n (do (when-not (some (fn [[a o]] (and (= a score) (= o 2))) (:lines (current)))\n (fail (str \"To edit \" from \" from this score, connect the score's third outlet (edits) to \" from\n \", or show \" from \" itself as a score: (view \" from \" :score)\")))\n (swap! ui assoc :tsel (assoc ts :src {:src (if (#{\"Delete\" \"Backspace\"} k) dur-path target)} :id nil))\n (eng/emit! engine-patch (fid score) 2 [:edit ops])))\n (render-scene (current))))))))\n\n(defn score-click!\n \"Click on a score: a note picks its stroke; elsewhere, the nearest position of that system is requested.\"\n [e id b x y]\n (let [gn (or (.closest (.-target e) \"g.note\") (.closest (.-target e) \"g.rest\"))\n m (when gn (re-matches #\"n-([^-]+)-([^-]+)-(\\d+)\" (str (.-id gn))))\n tid (when m (keyword (nth m 2)))\n c (get @score-cache id)\n piece (when (and gn (:from c)) (first (filter (fn [pc] (= (:id pc) (.-id gn))) (:pieces c))))\n ;; a note or rest of a freqt's own strokes, quantized: alt-click divides its beat another way\n qpiece (when (and gn (.-altKey e) (not (:from c)) (not (live-tree id)) (not (kept-tree b)))\n (first (filter (fn [pc] (= (:id pc) (.-id gn))) (:pieces c))))]\n (cond\n (and piece (:src piece))\n (select-tree-note! id piece (:from c))\n (and qpiece (.-shiftKey e) (:midi qpiece))\n (let [nm (enharmonic! id (:t qpiece) (:midi qpiece))]\n (repl-print! \"out\" (esc (str \"; \" id \" · the note at \" (cv/fmt (:t qpiece)) \" written \" nm \" (shift-alt-click again: another name)\"))))\n qpiece\n (let [ch (division! id (:t qpiece))]\n (repl-print! \"out\" (esc (str \"; \" id \" · the beat at \" (cv/fmt (:t qpiece)) \" divided \" (pr-str ch) \" (alt-click again: another way; (division! \" id \" \" (cv/fmt (:t qpiece)) \" nil): the quantizer's)\"))))\n (and tid (get-in b [:data :strokes tid]))\n (swap! ui assoc :sel nil :nsel [id tid])\n :else\n (let [lx (- x (:x b) 4) ly (- y (:y b) hdr 4)\n as (filter (fn [a] (<= (:y0 a) ly (:y1 a))) (get-in @score-cache [id :anchors]))]\n (swap! ui assoc :sel nil :nsel nil :tsel nil)\n (when (seq as)\n (pos-click! id (:t (apply min-key (fn [a] (js/Math.abs (- (:x a) lx))) as))))))))\n\n(defn snap-t [d t] (let [q (cv/quantize-t (:gx d) t)] (if (cv/generic? d) q (max 0 q))))\n(defn snap-f [d f] (cv/quantize-f (:gy d) f))\n\n(defn number-value [id b]\n (let [v (or (second (last-shown id)) (get-in @eng/rt [:states (fid id)]) (eng/num-of (first (eng/args-of (:text b)))) 0)]\n (if (number? v) v 0)))\n\n;; the code of a box opens in the editor window (14-editor.cljs)\n(declare open-code-editor!)\n\n(defn data-header?\n \"Is (x, y) on the right half of the header of a box whose data can be edited as text (not a code box,\n whose code row opens it)? There a double-click opens its data in the code window (discussion #30).\"\n [id b x y]\n (let [[w _] (box-dims id b)]\n (boolean (and (comp/source-of b) (not= :code (display-of b))\n (<= (:y b) y (+ (:y b) hdr)) (> x (+ (:x b) (/ w 2)))))))\n\n(defn param-k\n \"How a parameter is named in a message: a keyword if possible (:cutoff), otherwise a string.\"\n [label] (if (re-matches #\"[A-Za-z][A-Za-z0-9_\\-]*\" (str label)) (keyword label) (str label)))\n\n(defn param-of [b label] (first (filter (fn [p] (= (:label p) label)) (code-params b))))\n\n(defn value-at-x [b p x]\n (let [[w _] (box-dims nil b) tw (- w param-x0 64)\n u (max 0 (min 1 (/ (- x (:x b) param-x0) tw)))\n v (+ (:min p) (* u (- (:max p) (:min p))))\n st (:step p)]\n (cv/round-to (if (and (number? st) (pos? st)) (* st (js/Math.round (/ v st))) v) 4)))\n\n(defn send-quiet! [id v]\n (let [was-on (eng/running?)]\n (inject-local! (fid id) 0 v)\n (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!))))\n (render-overlay!)))\n\n(defn send-flat-quiet! [f v]\n (let [was-on (eng/running?)]\n (inject-local! f 0 v)\n (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!))))\n (render-overlay!)))\n\n(defn ctl-gesture!\n \"Calls the :gesture of the box being dragged; if the value changes, sends it to its inlet 0.\"\n [x y fine]\n (when-let [{:keys [f b ox oy x0 y0 start hit] :as cd} (:ctldrag @ui)]\n (let [v (try ((:gesture (box-def b))\n (assoc (ctl-m* f b) :start start :x (- x ox) :y (- y oy) :dx (- x x0) :dy (- y y0) :fine (boolean fine) :hit hit))\n (catch :default e (js/console.error \"gesture\" e) nil))]\n (swap! ui update :ctldrag assoc :x x :y y :fine (boolean fine))\n (when (and (some? v) (not= v (:v cd)))\n (swap! ui assoc-in [:ctldrag :v] v)\n (send-flat-quiet! f v)))))\n\n(defn ctl-release-value\n \"On release, the :gesture of the box is asked once more with :up true; what it returns is the value\n that stays in the history. A :gesture that ignores :up returns the last value, as before.\"\n [{:keys [f b ox oy x0 y0 x y fine start v hit]}]\n (let [x (or x x0) y (or y y0)\n u (try ((:gesture (box-def b))\n (assoc (ctl-m* f b) :start start :x (- x ox) :y (- y oy) :dx (- x x0) :dy (- y y0)\n :fine (boolean fine) :up true :hit hit))\n (catch :default e (js/console.error \"gesture\" e) v))]\n (if (some? u) u v)))\n\n(defn ctl-commit!\n \"Leaves the value v of a control in the history, as its drag does on release: a box whose class keeps\n it (:persist, a knob) is rewritten with its new arguments (this tab already sent the value); any other\n sends it as a gesture, whose code starts with `echo` ((send! :b3 … or (send-to! :b7.b4 …), the number\n written by `fmt`.\"\n [{:keys [f id echo]} v fmt]\n (let [b (when id (get-in (current) [:boxes id])) d (when b (box-def b))]\n (if (and b (:persist d))\n (when (some? v)\n (let [t (comp/args-text d (klass (:text b)) (merge (comp/args-for d (:text b)) ((:persist d) v)))]\n ;; this tab already sent the value: the new text need not send it again\n (swap! echoed assoc f t)\n (when (not= t (:text b)) (gesture! (str \"(text! \" id \" \" (pr-str t) \")\")))))\n (gesture! (str echo (cond (number? v) (fmt v) (some? v) (pr-str v) :else \":bang\") \")\")))))\n\n(defn send-to!\n \"Sends a message to inlet 0 of a box inside a sub-patch of this view: (send-to! :b7.b4 0.5).\"\n [rel v]\n (let [was-on (eng/running?)]\n (inject-local! (eng/flat-id (engine-path) rel) 0 v)\n (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!))))\n v))\n\n(defn start-ctl-drag!\n ([f b ox oy x y echo] (start-ctl-drag! f b ox oy x y echo false))\n ([f b ox oy x y echo fine]\n (swap! ui assoc :sel nil :nsel nil\n :ctldrag {:f f :b b :ox ox :oy oy :x0 x :y0 y :start (second (shown-flat f)) :v nil :echo echo\n ;; the part of its view pressed (a shape with :hit), worked out from the shapes themselves\n :hit (try (shp/hit-near (ctl-shapes* (ctl-m* f b) b) [(- x ox) (- y oy)]) (catch :default _ nil))})\n (ctl-gesture! x y fine)))\n\n;; ───── the number typed, for each kind of control (issue #32) ─────\n\n(defn ctl-number\n \"The number a control with a :gesture (engine id f) holds now, or nil if its gesture does not give\n numbers (a keyboard gives notes): what it last showed, its state, or what its gesture gives at rest.\"\n [f b]\n (let [g (:gesture (box-def b))]\n (when (fn? g)\n (let [m (ctl-m* f b)\n at-rest (try (g (assoc m :start (:shown m) :x 0 :y 0 :dx 0 :dy 0 :fine false))\n (catch :default _ nil))]\n (when (number? at-rest)\n (first (filter number? [(:shown m) (:state m) at-rest])))))))\n\n(defn ctl-typed!\n \"A number typed into a control with a :gesture (cd as for a drag: :f :b :id :echo). One that keeps its\n value in its text (a knob) gets it first, so the text keeps what its :receive made of it (a knob keeps\n it between its min and max); any other is sent it by the gesture itself.\"\n [{:keys [f b id] :as cd} v]\n (if (and id (:persist (box-def b)))\n (do (send-flat-quiet! f v)\n (let [st (get-in @eng/rt [:states f])] (ctl-commit! cd (if (number? st) st v) typed-str)))\n (ctl-commit! cd v typed-str)))\n\n(defn type-ctl!\n \"Opens the field over a control with a :gesture whose top-left corner is at x y and size [w h].\"\n [cd x y [w h] v]\n (open-number-input! {:x x :y (+ y (max 0 (- (/ h 2) 13))) :value v :commit! (fn [n] (ctl-typed! cd n))}))\n\n(defn type-number-box!\n \"Opens the field over the number box id.\"\n [id b]\n (open-number-input! {:x (+ (:x b) grip) :y (- (:y b) 2) :value (number-value id b)\n ;; like a knob's: sent, and kept in its text\n :commit! (fn [n] (ctl-typed! {:f (fid id) :b b :id id :echo (str \"(send! \" id \" \")} n))}))\n\n(defn param-typed-value\n \"A typed value for parameter p of a code box, kept between its min and max (Faust clamps it too: so\n the history keeps what sounds).\"\n [p v] (if (< (:min p) (:max p)) (max (:min p) (min (:max p) v)) v))\n\n(defn send-param! [id label v]\n (gesture! (str \"(send! \" id \" [\" (pr-str (param-k label)) \" \" (typed-str v) \"])\")))\n\n(defn type-param!\n \"Opens the field over parameter `label` of code box id. `before` is the value it had before the first\n click of the double-click (a click on the slider moves it there): Esc puts that back.\"\n [id b label before]\n (let [{:keys [y-par params]} (code-geom b)\n i (or (first (keep-indexed (fn [i q] (when (= (:label q) label) i)) params)) 0)\n p (nth params i nil)]\n (when p\n (open-number-input!\n {:x (+ (:x b) param-x0) :y (+ (:y b) y-par (* i param-h) -4) :value before\n :commit! (fn [n] (send-param! id label (param-typed-value p n)))\n :cancel! (fn [] (when (and (number? before) (not= before (param-value id b p))) (send-param! id label before)))}))))\n\n;; ───── selection: one box, several (⇧+click or a frame drawn on the paper), moved or deleted together ─────\n;; A plain click selects a box and moves it; ⌘/Ctrl+click also opens its inspector (its arguments and text).\n\n(defn scene-boxes\n \"The boxes on screen, where they are drawn (their presentation places, in presentation).\"\n [] (:boxes (scene-of (current))))\n\n(defn group-drag\n \"Several boxes start moving together from the pointer at x y (nil if none of them is on screen).\"\n [ids x y]\n (let [bs (scene-boxes)\n from (into {} (for [id ids :let [b (get bs id)] :when b] [id [(:x b) (:y b)]]))]\n (when (seq from) {:ids from :x0 x :y0 y :gx 0 :gy 0 :moved false})))\n\n;; In presentation (issue #57) the paper is for playing: no new boxes, no wires, no selection with the mouse\n;; (no frame, ⇧+click, ⌘/Ctrl+click, ⌘/Ctrl+A; a click does not select, so Delete cannot remove a box). In the\n;; editor's Present a box can still be dragged to a new place, one at a time; in a Release/Perform embed not.\n\n(defn locked? \"In presentation: the paper is for playing.\" [] (boolean @pres-mode))\n\n;; ⌥/Alt held at the last press: in presentation, only ⌥+drag moves a box (a plain drag plays it, or\n;; does nothing), so that a freqt, a canvas or a knob is not moved by its header or its grip by mistake\n(defonce alt-press (atom false))\n\n(defn pick-box!\n \"A plain click on a box: if it is one of several selected, they all start moving; otherwise it alone is\n selected (its inspector closed) and starts moving. `extra` is merged into the ui state. In presentation\n nothing is selected: in the editor ⌥+drag moves the box to a new place (a plain drag leaves it where it\n is), in an embed it stays.\"\n ([id b x y] (pick-box! id b x y nil))\n ([id b x y extra]\n (let [ids (sel-ids)]\n (cond\n (locked?)\n (swap! ui merge {:sel nil :insp nil :nsel nil\n :drag (when (and (not embed-mode) @alt-press)\n {:id id :dx (- x (:x b)) :dy (- y (:y b)) :x (:x b) :y (:y b) :moved false})}\n extra)\n (and (> (count ids) 1) (contains? ids id))\n ;; released without moving, the click selects that box alone (see end-gesture!)\n (swap! ui merge {:nsel nil :drag (some-> (group-drag ids x y) (assoc :clicked id))} extra)\n :else\n (swap! ui merge {:sel [:box id] :insp nil :nsel nil\n :drag {:id id :dx (- x (:x b)) :dy (- y (:y b)) :x (:x b) :y (:y b) :moved false}}\n extra)))))\n\n(defn inspect-box!\n \"⌘/Ctrl+click on a box: selects it, opens its inspector, and it can be moved.\"\n [id b x y]\n (swap! ui assoc :sel [:box id] :insp id :nsel nil :tsel nil\n :drag {:id id :dx (- x (:x b)) :dy (- y (:y b)) :x (:x b) :y (:y b) :moved false}))\n\n(defn shift-pick\n \"The box a ⇧+click adds to (or takes out of) the selection; nil where ⇧ already means something else\n (on the drawing area of a canvas or a freqt it draws a straight stroke; on the body of a box with a\n :gesture it is part of the gesture, fine control or a chord: there the grip selects).\"\n [e]\n (when (and (.-shiftKey e) (not (closest e \".port\")) (not (locked?)))\n (when-let [el (closest e \".box\")]\n (let [[id b] (el-box el)]\n (when (and b (not (and (closest e \".mus-body\") (= :canvas (display-of b))))\n (not (and (closest e \".box.act\") (not (closest e \".grip\")) (fn? (:gesture (box-def b))))))\n id)))))\n\n(defn toggle-box!\n \"⇧+click: the box joins the selection, or leaves it; what stays selected can be dragged at once.\"\n [id x y]\n (let [ids (sel-ids) now (if (contains? ids id) (disj ids id) (conj ids id))]\n (swap! ui assoc :sel (sel-of now) :insp nil :nsel nil :tsel nil\n :drag (when (contains? now id) (group-drag now x y)))))\n\n(defn group-offset\n \"The offset of a group being dragged, stopped so that no box goes past the top or the left edge.\"\n [{:keys [ids x0 y0]} x y]\n [(max (- x x0) (- (apply min (map first (vals ids)))))\n (max (- y y0) (- (apply min (map second (vals ids)))))])\n\n;; the frame: drawn from an empty place of the paper, it selects every box it touches (⇧ adds to the selection)\n\n(defn marquee-rect [{:keys [x0 y0 x y]}]\n [(min x0 x) (min y0 y) (js/Math.abs (- x x0)) (js/Math.abs (- y y0))])\n\n(defn marquee-hits\n \"The boxes on screen that the frame touches.\"\n [m]\n (let [[mx my mw mh] (marquee-rect m)]\n (set (for [[id b] (scene-boxes)\n :let [[w h] (box-dims id b)]\n :when (and (< mx (+ (:x b) w)) (< (:x b) (+ mx mw)) (< my (+ (:y b) h)) (< (:y b) (+ my mh)))]\n id))))\n\n(defn mark-hits!\n \"Marks on screen the boxes the frame is touching (without drawing the whole patch again).\"\n [hits]\n (doseq [el (array-seq (.querySelectorAll ($ \"scene\") \".box\"))]\n (.toggle (.-classList el) \"hit\" (contains? hits (keyword (.. el -dataset -box))))))\n\n(defn draw-marquee! [m]\n (let [r (or ($ \"marquee\")\n (let [r (js/document.createElementNS \"http://www.w3.org/2000/svg\" \"rect\")]\n (.setAttribute r \"id\" \"marquee\")\n (.setAttribute r \"class\" \"marquee\")\n (.appendChild svg r)\n r))\n [x y w h] (marquee-rect m)]\n (.setAttribute r \"x\" x)\n (.setAttribute r \"y\" y)\n (.setAttribute r \"width\" w)\n (.setAttribute r \"height\" h)\n (mark-hits! (marquee-hits m))))\n\n(defn end-marquee! [m]\n (when-let [r ($ \"marquee\")] (.remove r))\n (mark-hits! #{})\n (let [hits (if (:moved m) (marquee-hits m) #{})]\n (swap! ui assoc :marquee nil :insp nil :sel (sel-of (if (:add m) (into (:base m) hits) hits)))))\n\n;; on a Mac, Ctrl+click is also a right click: on a box it opens the inspector, not the browser's menu\n;; ───── annotating (Study 26): marks drawn on a layer, anchored to the box nearest each point ─────\n;; (:annot @ui) = {:tool :draw|:arrow|:text|:move|:erase :layer :notes} while the Annotate bar is open;\n;; (:adraw @ui) the mark being drawn. What is drawn stays in the history as (mark …).\n\n(defn drawn-boxes\n \"The boxes on screen now, with their place and size: [[id [x y w h]] …].\"\n []\n (let [p (scene-of (current))]\n (for [[id b] (:boxes p)] (let [[x y] (box-pos id b) [w h] (box-dims id b)] [id [x y w h]]))))\n\n(defn anchor-of\n \"Where a point of a mark is anchored: to the box nearest it (within 150 px), from its top-left corner, or to the paper.\"\n [[x y]]\n (let [d (fn [[bx by bw bh]] (js/Math.hypot (max 0 (- bx x) (- x (+ bx bw))) (max 0 (- by y) (- y (+ by bh)))))\n [id [bx by] :as best] (first (sort-by (fn [[_ r]] (d r)) (drawn-boxes)))\n r1 (fn [v] (/ (js/Math.round (* 10 v)) 10))]\n (if (and best (< (d (second best)) 150))\n [id (r1 (- x bx)) (r1 (- y by))]\n [:patch (r1 x) (r1 y)])))\n\n(defn annot-layer [] (or (:layer (:annot @ui)) (first (keys (:layers (current)))) :notes))\n\n(defn mark-hit\n \"The mark of a shown layer under [x y], or nil.\"\n [[x y :as q]]\n (let [p (current)\n sd (fn [[px py] [ax ay] [bx by]]\n (let [dx (- bx ax) dy (- by ay) L2 (+ (* dx dx) (* dy dy))\n u (if (zero? L2) 0 (max 0 (min 1 (/ (+ (* (- px ax) dx) (* (- py ay) dy)) L2))))]\n (js/Math.hypot (- px (+ ax (* u dx))) (- py (+ ay (* u dy))))))]\n (->> (:marks p)\n (filter (fn [[_ m]] (layer-shown? p (:layer m))))\n (keep (fn [[id m]]\n (when-let [ps (mark-points p m)]\n (let [dist (if (= :text (:kind m))\n (let [[[tx ty]] ps] (if (and (<= (- tx 4) x (+ tx (* 8 (count (:txt m))))) (<= (- ty 16) y (+ ty 5))) 0 99))\n (apply min 99 (map (fn [a b] (sd q a b)) ps (rest ps))))]\n (when (< dist 8) [dist id])))))\n (sort-by first) first second)))\n\n(defn annot-preview []\n (when-let [{:keys [kind px]} (:adraw @ui)]\n (let [pts (str/join \" \" (map (fn [[x y]] (str (js/Math.round x) \",\" (js/Math.round y))) px))]\n (case kind\n :draw (str \"<polyline class=\\\"amark new\\\" points=\\\"\" pts \"\\\"></polyline>\")\n :arrow (str \"<polyline class=\\\"amark new\\\" points=\\\"\" pts \"\\\"></polyline>\")\n \"\"))))\n\n(defn annot-down! [x y]\n (let [{:keys [tool]} (:annot @ui) lid (annot-layer)]\n (case tool\n :draw (swap! ui assoc :adraw {:kind :draw :px [[x y]]})\n :arrow (swap! ui assoc :adraw {:kind :arrow :px [[x y] [x y]]})\n :text (let [t (str/trim (str (some-> ($ \"annot-text\") .-value)))]\n (if (seq t)\n (gesture! (str \"(mark \" lid \" \" (next-mark-id) \" \" (pr-str {:kind :text :at (anchor-of [x y]) :txt t}) \")\"))\n (some-> ($ \"annot-text\") .focus)))\n :erase (do (swap! ui assoc :adraw {:kind :erase})\n (when-let [id (mark-hit [x y])] (gesture! (str \"(unmark \" id \")\"))))\n ;; moving a mark: pressed near one end of a line or an arrow, only that end (it is anchored again where\n ;; it is let go); anywhere else on the mark, all of it (each point keeps its anchor)\n :move (when-let [id (mark-hit [x y])]\n (let [p (current) m (get-in p [:marks id]) ps (when (:pts m) (mark-points p m))\n near (fn [i] (when-let [[px py] (and ps (nth ps i nil))] (< (js/Math.hypot (- x px) (- y py)) 9)))\n end (cond (not ps) nil (near 0) 0 (near (dec (count ps))) (dec (count ps)) :else nil)]\n (swap! ui assoc :adraw {:kind :move :id id :x0 x :y0 y :x x :y y :end end})))\n nil)\n (render-layers!)))\n\n(defn annot-move! [x y]\n (when-let [{:keys [kind px]} (:adraw @ui)]\n (case kind\n :draw (let [[lx ly] (peek px)]\n (when (> (js/Math.hypot (- x lx) (- y ly)) 3)\n (swap! ui update-in [:adraw :px] conj [x y])\n (render-layers!)))\n :arrow (do (swap! ui assoc-in [:adraw :px 1] [x y]) (render-layers!))\n :move (do (swap! ui update :adraw assoc :x x :y y) (render-layers!))\n :erase (when-let [id (mark-hit [x y])] (gesture! (str \"(unmark \" id \")\")))\n nil)))\n\n(defn annot-up! []\n (when-let [{:keys [kind px id x0 y0 x y end]} (:adraw @ui)]\n (swap! ui assoc :adraw nil)\n (let [lid (annot-layer)]\n (case kind\n :draw (when (> (count px) 1)\n (let [ps (cv/simplify (vec px) 1.2)]\n (gesture! (str \"(mark \" lid \" \" (next-mark-id) \" \" (pr-str {:kind :line :pts (mapv anchor-of ps)}) \")\"))))\n :arrow (let [[a b] px]\n (when (> (js/Math.hypot (- (first b) (first a)) (- (second b) (second a))) 8)\n (gesture! (str \"(mark \" lid \" \" (next-mark-id) \" \" (pr-str {:kind :arrow :pts [(anchor-of a) (anchor-of b)]}) \")\"))))\n :move (let [r1 (fn [v] (/ (js/Math.round (* 10 v)) 10)) dx (r1 (- x x0)) dy (r1 (- y y0))\n p (current) m (get-in p [:marks id])]\n (when (and m (> (+ (js/Math.abs dx) (js/Math.abs dy)) 2))\n (if (some? end)\n ;; one end: anchored again where it was let go (to the box nearest it, or to the paper)\n (let [[ex ey] (nth (mark-points p m) end)]\n (gesture! (str \"(mark \" (:layer m) \" \" id \" \" (pr-str (dissoc (set-point m end (anchor-of [(+ ex dx) (+ ey dy)])) :layer)) \")\")))\n (gesture! (str \"(move-mark \" id \" \" dx \" \" dy \")\")))))\n nil))\n (render-layers!)))\n\n(defn render-annot-bar!\n \"The Annotate bar: its tool, its layer and how that layer is shown.\"\n []\n (let [bar ($ \"annot-bar\") a (:annot @ui)]\n (when bar\n (set! (.-hidden bar) (nil? a))\n (.toggle (.-classList ($ \"annot-toggle\")) \"on\" (some? a))\n (.toggle (.-classList js/document.body) \"annotating\" (some? (:tool a)))\n (.toggle (.-classList js/document.body) \"annot-move\" (= :move (:tool a)))\n (when a\n (let [p (current) lid (annot-layer) l (or (get-in p [:layers lid]) layer-default)\n inp ($ \"annot-layer\")]\n (doseq [btn (array-seq (.querySelectorAll bar \"[data-atool]\"))]\n (.setAttribute btn \"aria-pressed\" (str (= (name (or (:tool a) \"\")) (.. btn -dataset -atool)))))\n (when-not (= inp (.-activeElement js/document)) (set! (.-value inp) (name lid)))\n (set! (.-innerHTML ($ \"annot-layers\")) (apply str (for [k (sort (map name (keys (:layers p))))] (str \"<option value=\\\"\" (esc k) \"\\\"></option>\"))))\n (set! (.-textContent ($ \"annot-z\")) (name (:z l)))\n (set! (.-checked ($ \"annot-show-patch\")) (contains? (:show l) :patch))\n (set! (.-checked ($ \"annot-show-present\")) (contains? (:show l) :present)))))))\n\n(defn annotate\n \"Opens the Annotate bar (with a tool: :draw :arrow :text :erase), or closes it: (annotate) · (annotate :arrow) · (annotate false).\"\n ([] (annotate (if (:annot @ui) false :draw)))\n ([tool]\n (if (false? tool)\n (swap! ui assoc :annot nil :adraw nil)\n (swap! ui assoc :annot {:tool (keyword tool) :layer (annot-layer)} :sel nil))\n (render-layers!)\n (boolean (:annot @ui))))\n\n(.addEventListener ($ \"annot-toggle\") \"click\" (fn [_] (annotate)))\n(.addEventListener ($ \"annot-done\") \"click\" (fn [_] (annotate false)))\n(.addEventListener ($ \"annot-bar\") \"click\"\n (fn [e] (when-let [b (.closest (.-target e) \"[data-atool]\")] (annotate (.. b -dataset -atool)))))\n(.addEventListener ($ \"annot-layer\") \"change\"\n (fn [e] (let [v (str/trim (.. e -target -value))]\n (when (re-matches #\"[A-Za-z][A-Za-z0-9_-]*\" v) (swap! ui assoc-in [:annot :layer] (keyword v)))\n (render-layers!))))\n(.addEventListener ($ \"annot-z\") \"click\"\n (fn [_] (let [lid (annot-layer) l (or (get-in (current) [:layers lid]) layer-default)]\n (gesture! (str \"(layer \" lid \" {:z \" (if (= :over (:z l)) \":under\" \":over\") \"})\")))))\n(doseq [[el k] [[\"annot-show-patch\" :patch] [\"annot-show-present\" :present]]]\n (.addEventListener ($ el) \"change\"\n (fn [e] (let [lid (annot-layer) l (or (get-in (current) [:layers lid]) layer-default)\n show ((if (.. e -target -checked) conj disj) (:show l) k)]\n (gesture! (str \"(layer \" lid \" {:show \" (pr-str show) \"})\"))))))\n\n(.addEventListener svg \"contextmenu\"\n (fn [e] (when (and (.-ctrlKey e) (closest e \".box\")) (.preventDefault e))))\n\n(defonce corner-click (atom nil)) ; the last press on the corner of a box: {:id :t} (a double-click resets it)\n\n(.addEventListener svg \"pointerdown\"\n (fn [e]\n (reset! alt-press (boolean (.-altKey e)))\n (let [[x y] (pt e) mod? (or (.-metaKey e) (.-ctrlKey e))\n ;; an outlet within reach of the pointer (not only right on it) starts a wire\n out (when-not (or (locked?) (:annot @ui)) (port-near (current) :out x y))]\n (cond\n ;; annotating: the pointer draws marks (the Annotate bar is open)\n (and (:annot @ui) (:tool (:annot @ui)))\n (do (.preventDefault e) (annot-down! x y))\n\n out\n (do (.preventDefault e)\n (.add (.-classList svg) \"wiring\")\n (swap! ui assoc :wire {:from (first out) :out (second out) :x x :y y}))\n\n ;; the corner of a canvas, freqt or score: drag to resize it (issue #40)\n (closest e \".resize-corner\")\n (let [[id b] (el-box (closest e \".resize-corner\"))]\n (when b\n (.preventDefault e)\n (let [[w h] (box-size id b) now (js/Date.now) {pid :id pt :t} @corner-click]\n (reset! corner-click {:id id :t now})\n (if (and (= pid id) (< (- now pt) 400))\n ;; a double-click on the corner: back to its default size\n (do (reset! corner-click nil)\n (when (:size b) (gesture! (str \"(resize \" id \")\"))))\n (swap! ui assoc :sel nil :nsel nil :drag nil\n :resize {:id id :x0 x :y0 y :w0 w :h0 h :w w :h h :moved false})))))\n\n ;; ⌘/Ctrl+click anywhere on a box: select it and open its inspector\n (and mod? (closest e \".box\") (not (closest e \".port\")) (not (locked?)))\n (let [[id b] (el-box (closest e \".box\"))]\n (when b\n (.preventDefault e)\n (inspect-box! id b x y)))\n\n ;; ⇧+click: add the box to the selection, or take it out\n (shift-pick e)\n (do (.preventDefault e)\n (toggle-box! (shift-pick e) x y))\n\n ;; the chips of a header (discussion #30): ⇄ shows the box in its next view, { } opens its data as text\n (closest e \".hchip\")\n (let [el (closest e \".hchip\") [id b] (el-box el)]\n (when b\n (.preventDefault e)\n (swap! ui assoc :drag nil)\n (case (.. el -dataset -chip)\n \"view\" (gesture! (str \"(view \" id \" \" (next-view b) \")\"))\n \"code\" (js/setTimeout (fn [] (open-code-editor! id)) 0)\n nil)))\n\n ;; a control presented in the panel of a sub-patch\n (closest e \".pres-area\")\n (let [el (closest e \".pres-area\") [id b] (el-box el) kid (keyword (.. el -dataset -kid))\n k (when b (first (filter (fn [k] (= (:id k) kid)) (:kids (panel-layout b)))))]\n (when (and k (fn? (:gesture (box-def (:b k)))))\n (.preventDefault e)\n (let [[kx ky] (kid-origin (:x b) (:y b) k)\n f (eng/flat-id (conj (engine-path) id) kid)\n echo (str \"(send-to! \" (eng/flat-id [id] kid) \" \")\n v (ctl-number f (:b k))]\n ;; a double-click on a numeric control: its value is typed (issue #32)\n (if (and (number? v) (double-click-on [:kid f] v))\n (type-ctl! {:f f :b (:b k) :echo echo} kx ky [(:w k) (:h k)] v)\n (start-ctl-drag! f (:b k) kx ky x y echo (.-shiftKey e))))))\n\n ;; action boxes: the grip selects and moves them (⌘/Ctrl+click opens the inspector), the body only plays\n (and (closest e \".box.act\") (not (closest e \".grip\")) (not (closest e \".port\")))\n (let [[id b] (el-box (closest e \".box.act\"))]\n (when b\n (.preventDefault e)\n (swap! ui (fn [u] (assoc u :nsel nil :sel (when-not (= (:sel u) [:box id]) (:sel u)))))\n (let [num-box? (= \"number\" (klass (:text b)))\n ctl? (fn? (:gesture (box-def b)))\n cval (when (and ctl? (not num-box?)) (ctl-number (fid id) b))\n ;; a double-click on a number box, or on a control whose gesture gives numbers:\n ;; its value is typed (issue #32); the first click did what a click does\n again? (and (or num-box? (some? cval)) (some? (double-click-on [:box id] nil)))]\n (cond\n (and again? num-box?) (type-number-box! id b)\n again? (type-ctl! {:f (fid id) :b b :id id :echo (str \"(send! \" id \" \")}\n (+ (:x b) grip) (:y b) (comp/size-of b) cval)\n num-box? (swap! ui assoc :numdrag {:id id :y0 y :v0 (number-value id b) :v nil})\n ctl? (do (start-ctl-drag! (fid id) b (+ (:x b) grip) (:y b) x y (str \"(send! \" id \" \") (.-shiftKey e))\n (swap! ui assoc-in [:ctldrag :id] id))\n :else (gesture! (str \"(send! \" id \" :bang)\"))))))\n\n ;; the first click selects the box and redraws it, so the double click is detected here\n (closest e \".code-area\")\n (let [[id b] (el-box (closest e \".code-area\")) now-ms (js/Date.now) [lid lt] (:last-click @ui)]\n (when b\n (if (and (= lid id) (< (- now-ms lt) 450))\n (do (.preventDefault e)\n (swap! ui assoc :last-click nil :drag nil)\n (js/setTimeout (fn [] (open-code-editor! id)) 0))\n (pick-box! id b x y {:last-click [id now-ms]}))))\n\n (closest e \".param\")\n (let [el (closest e \".param\") [id b] (el-box el) label (.. el -dataset -param) p (param-of b label)]\n (when p\n (.preventDefault e)\n (swap! ui assoc :sel nil :nsel nil)\n (case (:type p)\n \"button\" (do (send-quiet! id [(param-k label) 1])\n (swap! ui assoc :paramdrag {:id id :label label :button true}))\n \"checkbox\" (let [v (if (pos? (param-value id b p)) 0 1)]\n (gesture! (str \"(send! \" id \" [\" (pr-str (param-k label)) \" \" v \"])\")))\n ;; a slider: a double-click types its value (issue #32), the one it had before the first click\n (if-let [[_ _ before] (double-click-on [:param id label] (param-value id b p))]\n (type-param! id b label before)\n (let [v (value-at-x b p x)]\n (send-quiet! id [(param-k label) v])\n (swap! ui assoc :paramdrag {:id id :label label :p p :v v}))))))\n\n ;; the value written beside a slider: a click is a click on the box, a double-click types the value\n (closest e \".pval-hit\")\n (let [el (closest e \".pval-hit\") [id b] (el-box el) label (.. el -dataset -param) p (param-of b label)]\n (when b\n (if-let [[_ _ before] (when p (double-click-on [:param id label] (param-value id b p)))]\n (do (.preventDefault e)\n (swap! ui assoc :drag nil)\n (type-param! id b label before))\n (pick-box! id b x y))))\n\n (closest e \".stroke-hit\")\n (let [el (closest e \".stroke-hit\") [id b] (el-box el) tid (keyword (.. el -dataset -stroke))\n d (canvas-data b) tr (get-in d [:strokes tid])]\n (when tr\n (.preventDefault e)\n (swap! ui assoc :sel nil :nsel [id tid]\n :ldrag {:kind :move :box id :tid tid :g (canvas-geom d id b) :d d :x0 x :y0 y :alt (.-altKey e)\n :pts0 (:pts tr) :pts (:pts tr) :dt 0 :dc 0 :moved false})))\n\n (closest e \".score-slot\")\n (let [[id b] (el-box (closest e \".score-slot\"))]\n (when b (score-click! e id b x y)))\n\n (closest e \".mus-body\")\n (let [[id b] (el-box (closest e \".mus-body\"))]\n (when b\n (case (display-of b)\n :canvas (let [d (canvas-data b) g (canvas-geom d id b)\n lx (- x (:x b)) ly (- y (:y b))\n t0 (snap-t d (cv/x->t g lx)) f0 (snap-f d (cv/y->f g ly))\n mode (cond (.-altKey e) :free (.-shiftKey e) :line :else :note)]\n (.preventDefault e)\n (swap! ui assoc :sel nil :nsel nil\n :ldrag {:kind :draw :mode mode :box id :g g :d d :x0 x :y0 y :bx (:x b) :by (:y b)\n :t0 t0 :f0 f0 :click-t (cv/x->t g lx) :raw [[lx ly]] :pts nil :moved false}))\n :score (score-click! e id b x y)\n nil)))\n\n (closest e \".box\")\n (let [el (closest e \".box\") id (keyword (.. el -dataset -box)) b (some-> (get-in (current) [:boxes id]) view-box)]\n (when b\n ;; the first click redraws the box, so a double click on a patch box is detected here\n (let [now (js/Date.now) [lid lt] (:last-box-click @ui) again? (and (= lid id) (< (- now lt) 450))]\n (cond\n ;; a patch @name: its line, in its tab (#117)\n (and again? (line-ref? b) (not (.-altKey e)))\n (do (.preventDefault e)\n (swap! ui assoc :last-box-click nil :drag nil)\n (js/setTimeout (fn [] (gesture! (str \"(open-ref \" id \")\"))) 0))\n (and again? (embedded? b) (not (.-altKey e)))\n (do (.preventDefault e)\n (swap! ui assoc :last-box-click nil :drag nil)\n (js/setTimeout (fn [] (gesture! (str \"(enter \" id \")\"))) 0))\n ;; a double-click on the right of the header of a box with data opens it as text\n (and again? (data-header? id b x y))\n (do (.preventDefault e)\n (swap! ui assoc :last-box-click nil :drag nil)\n (js/setTimeout (fn [] (open-code-editor! id)) 0))\n :else (pick-box! id b x y {:last-box-click [id now]})))))\n\n (closest e \".wire-hit\")\n (let [idx (js/parseInt (.. (closest e \".wire-hit\") -dataset -line) 10)]\n (swap! ui assoc :sel [:line (nth (:lines (current)) idx)] :nsel nil))\n\n ;; an empty place of the paper: a frame starts (a plain click there deselects); in presentation, nothing\n (locked?) (swap! ui assoc :sel nil :nsel nil :tsel nil :insp nil)\n :else (let [add? (.-shiftKey e)]\n (swap! ui assoc :nsel nil :tsel nil :insp nil\n :sel (when add? (:sel @ui))\n :marquee {:x0 x :y0 y :x x :y y :moved false :add add? :base (if add? (sel-ids) #{})}))))))\n\n(defn move-ldrag [ld x y]\n (let [{:keys [g d x0 y0 pts0]} ld\n [t0 f0] (first pts0)\n dt (cv/round-to (- (snap-t d (cv/x->t g (+ (cv/t->x g t0) (- x x0)))) t0) 4)\n ft (snap-f d (cv/y->f g (+ (cv/f->y g f0) (- y y0))))\n dc (cv/round-to (cv/delta-y d ft f0) 3)]\n (assoc ld :moved true :dt dt :dc dc :pts (mapv (fn [[t f]] [(+ t dt) (cv/shift-y d f dc)]) pts0))))\n\n(defn draw-ldrag [ld x y]\n (let [{:keys [g d mode t0 f0 bx by raw]} ld\n lx (- x bx) ly (- y by)]\n (case mode\n :note (assoc ld :pts [[t0 f0] [(snap-t d (cv/x->t g lx)) f0]])\n :line (assoc ld :pts [[t0 f0] [(snap-t d (cv/x->t g lx)) (snap-f d (cv/y->f g ly))]])\n :free (let [[px py] (peek raw)\n far? (if (cv/generic? d) (> (js/Math.hypot (- lx px) (- ly py)) 2) (> lx (+ px 1)))\n raw (if far? (conj raw [lx ly]) raw)]\n (assoc ld :raw raw :pts (mapv (fn [[px py]] [(cv/x->t g px) (cv/y->f g py)]) raw))))))\n\n(defn hover-hit!\n \"The part of a component's view (a shape with :hit) the pointer is over or near, highlighted.\"\n [e x y]\n (let [el (closest e \".box.act\")\n [id b] (when el (el-box el))\n h (when (and b (fn? (:gesture (box-def b))) (not (closest e \".grip\")))\n (let [f (fid id)\n k (try (shp/hit-near (ctl-shapes* (ctl-m* f b) b) [(- x (:x b) grip) (- y (:y b))]) (catch :default _ nil))]\n (when (some? k) [id k])))]\n (when (not= h (:hover-hit @ui))\n (swap! ui assoc :hover-hit h)\n (render-overlay!))))\n\n(defn hover-out!\n \"The outlet within reach of the pointer lights up, and the pointer becomes a cross: press there to wire.\"\n [x y]\n (let [h (when-not (or (locked?) (:annot @ui)) (port-near (current) :out x y))]\n (when (not= h (:hover-out @ui))\n (let [el-of (fn [[id o]] (.querySelector svg (str \".port.out[data-box=\\\"\" (name id) \"\\\"][data-out=\\\"\" o \"\\\"]\")))]\n (some-> (:hover-out @ui) el-of .-classList (.remove \"hot\"))\n (some-> h el-of .-classList (.add \"hot\"))\n (.toggle (.-classList svg) \"near-out\" (some? h))\n (swap! ui assoc :hover-out h)))))\n\n(.addEventListener svg \"pointermove\"\n (fn [e]\n (let [[x y] (pt e) {:keys [drag wire ldrag numdrag paramdrag ctldrag marquee resize adraw]} @ui]\n (cond\n adraw (annot-move! x y)\n resize (let [[w0 h0] size-min [w1 h1] size-max\n w (js/Math.round (max w0 (min w1 (+ (:w0 resize) (- x (:x0 resize))))))\n h (js/Math.round (max h0 (min h1 (+ (:h0 resize) (- y (:y0 resize))))))]\n (when (or (not= w (:w resize)) (not= h (:h resize)))\n (swap! ui assoc :resize (assoc resize :w w :h h :moved true))\n (render-scene (current))))\n marquee (let [far (> (+ (js/Math.abs (- x (:x0 marquee))) (js/Math.abs (- y (:y0 marquee)))) 3)\n m (assoc marquee :x x :y y :moved (or (:moved marquee) far))]\n (swap! ui assoc :marquee m)\n (when (:moved m) (draw-marquee! m)))\n (and drag (:ids drag))\n (let [[gx gy] (group-offset drag x y)]\n (when (or (:moved drag) (> (+ (js/Math.abs gx) (js/Math.abs gy)) 2))\n ;; what is being moved comes to the front, here (issue #166)\n (when-not (:moved drag) (to-front! (keys (:ids drag))))\n (swap! ui assoc :drag (assoc drag :gx gx :gy gy :moved true))))\n ctldrag (ctl-gesture! x y (.-shiftKey e))\n paramdrag (when-not (:button paramdrag)\n (let [b (get-in (current) [:boxes (:id paramdrag)]) v (value-at-x b (:p paramdrag) x)]\n (when (not= v (:v paramdrag))\n (swap! ui assoc :paramdrag (assoc paramdrag :v v))\n (send-quiet! (:id paramdrag) [(param-k (:label paramdrag)) v]))))\n numdrag (let [inc-size (if (.-shiftKey e) 0.01 0.1)\n v (cv/round-to (+ (:v0 numdrag) (* inc-size (js/Math.round (- (:y0 numdrag) y)))) 4)]\n (when (not= v (or (:v numdrag) (:v0 numdrag)))\n (swap! ui assoc :numdrag (assoc numdrag :v v))\n (let [was-on (eng/running?)]\n (inject-local! (fid (:id numdrag)) 0 v)\n (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!)))))\n (render-overlay!)))\n ldrag (let [far (> (+ (js/Math.abs (- x (:x0 ldrag))) (js/Math.abs (- y (:y0 ldrag)))) 3)]\n (when (or (:moved ldrag) far)\n (swap! ui assoc :ldrag\n (if (= :move (:kind ldrag))\n (move-ldrag ldrag x y)\n (assoc (draw-ldrag ldrag x y) :moved true)))))\n drag (let [nx (max 0 (- x (:dx drag))) ny (max 0 (- y (:dy drag)))]\n (when (or (:moved drag) (> (+ (js/Math.abs (- nx (:x drag))) (js/Math.abs (- ny (:y drag)))) 2))\n (when-not (:moved drag) (to-front! [(:id drag)]))\n (swap! ui assoc :drag (assoc drag :x nx :y ny :moved true))))\n wire (swap! ui assoc :wire (assoc wire :x x :y y) :hover-in (drop-target e wire))\n :else (do (hover-out! x y) (hover-hit! e x y))))))\n\n(defn finish-drawing! [{:keys [box mode d g pts raw moved click-t]}]\n (if-not moved\n (pos-click! box click-t)\n (let [generic? (cv/generic? d)\n min-dur (if (:gx d) (cv/step-x (:gx d)) 0.05)\n pts (case mode\n :free (let [px (cv/simplify raw 1.5)]\n (mapv (fn [[px py]] [(cv/round-to (cv/x->t g px) 4) (cv/round-to (cv/y->f g py) 4)]) px))\n (if generic? pts (sort-by first pts)))\n ps (cv/sane-pts-for d pts)]\n (when (and ps (or generic? (>= (- (first (peek ps)) (ffirst ps)) (* 0.99 min-dur))))\n ;; drawn freehand (⌥): in a measured tree, the note goes to its free voice\n (gesture! (if (= mode :free)\n (str \"(stroke \" box \" \" (cv/next-id d) \" \" (pts-code ps) \" true)\")\n (str \"(stroke \" box \" \" (pts-code ps) \")\")))))))\n\n(defn end-gesture! [e]\n (let [{:keys [drag wire ldrag numdrag paramdrag ctldrag marquee resize adraw]} @ui]\n (cond\n adraw (annot-up!)\n resize (do (swap! ui assoc :resize nil)\n (if (:moved resize)\n (gesture! (str \"(resize \" (:id resize) \" \" (:w resize) \" \" (:h resize) \")\"))\n (render-scene (current))))\n marquee (end-marquee! marquee)\n (and drag (:ids drag) (:moved drag))\n (let [{:keys [ids gx gy]} drag ks (sort-by box-num (keys ids)) r (fn [v] (js/Math.round v))]\n (swap! ui assoc :drag nil)\n (if (= 1 (count ks))\n (let [[x0 y0] (get ids (first ks))]\n (gesture! (str (if @pres-mode \"(present \" \"(move \") (first ks) \" \" (r (+ x0 gx)) \" \" (r (+ y0 gy)) \")\")))\n (gesture! (str (if @pres-mode \"(present-by [\" \"(move-by [\") (str/join \" \" ks) \"] \" (r gx) \" \" (r gy) \")\"))))\n (and drag (:clicked drag))\n (swap! ui assoc :drag nil :sel [:box (:clicked drag)])\n ctldrag\n (let [v (ctl-release-value ctldrag)]\n (swap! ui assoc :ctldrag nil)\n ;; the change stays in the work (a knob is rewritten with its new arguments), or is sent as a gesture\n (ctl-commit! ctldrag v cv/fmt))\n paramdrag\n (do (swap! ui assoc :paramdrag nil)\n (if (:button paramdrag)\n (do (send-quiet! (:id paramdrag) [(param-k (:label paramdrag)) 0])\n (repl-print! \"in from-patch\" (str \"<span class=\\\"p\\\">⟵</span>\" (esc (str \"(send! \" (:id paramdrag) \" [\" (pr-str (param-k (:label paramdrag))) \" 1]) … [\" (pr-str (param-k (:label paramdrag))) \" 0]\")))))\n (gesture! (str \"(send! \" (:id paramdrag) \" [\" (pr-str (param-k (:label paramdrag))) \" \" (cv/fmt (:v paramdrag)) \"])\"))))\n numdrag\n (do (swap! ui assoc :numdrag nil)\n ;; let go after a drag: its value stays in its text, as a knob's (this tab already sent it); a click sends it again\n (if (:v numdrag)\n (ctl-commit! {:f (fid (:id numdrag)) :id (:id numdrag) :echo (str \"(send! \" (:id numdrag) \" \")} (:v numdrag) cv/fmt)\n (gesture! (str \"(send! \" (:id numdrag) \" :bang)\"))))\n ldrag\n (do (swap! ui assoc :ldrag nil)\n (if (= :move (:kind ldrag))\n (when (and (:moved ldrag) (or (not (zero? (:dt ldrag))) (not (zero? (:dc ldrag)))))\n (gesture! (str \"(move-stroke \" (:box ldrag) \" \" (:tid ldrag) \" \" (cv/fmt (:dt ldrag)) \" \" (cv/fmt (:dc ldrag))\n ;; ⌥: a note of a measured tree leaves its measures\n (when (:alt ldrag) \" :free\") \")\")))\n (finish-drawing! ldrag)))\n (and drag (:moved drag))\n (do (swap! ui assoc :drag nil)\n (gesture! (str (if @pres-mode \"(present \" \"(move \") (:id drag) \" \" (js/Math.round (:x drag)) \" \" (js/Math.round (:y drag)) \")\")))\n drag (swap! ui assoc :drag nil)\n wire\n (let [[to in] (when e (drop-target e wire))]\n (.remove (.-classList svg) \"wiring\")\n (swap! ui assoc :wire nil :hover-in nil)\n (when to\n (gesture! (str \"(connect \" (:from wire) \" \" (:out wire) \" \" to \" \" in \")\"))\n ;; a tree into a freqt shown as a score: the edits made on the score come back to the tree (a dashed line)\n (let [p (current) from (:from wire)]\n (when (and (= \"tree\" (klass (get-in p [:boxes from :text]))) (= \"freqt\" (klass (get-in p [:boxes to :text])))\n (= :score (display-of (get-in p [:boxes to])))\n (zero? in)\n (not (some (fn [[a o b]] (and (= a to) (= o 2) (= b from))) (:lines p))))\n (gesture! (str \"(connect \" to \" 2 \" from \" 0)\"))\n (repl-print! \"out\" (esc (str \"; and back: the edits made on \" to \" go to \" from \" (the dashed line)\"))))))))))\n\n(.addEventListener svg \"pointerup\" end-gesture!)\n(.addEventListener svg \"pointerleave\" (fn [_] (when (:hover-out @ui) (hover-out! -1e6 -1e6)) (when (:hover-hit @ui) (swap! ui assoc :hover-hit nil) (render-overlay!)) (when (or (:adraw @ui) (:drag @ui) (:wire @ui) (:ldrag @ui) (:numdrag @ui) (:paramdrag @ui) (:ctldrag @ui) (:marquee @ui) (:resize @ui)) (end-gesture! nil))))\n\n(.addEventListener svg \"dblclick\"\n (fn [e]\n (let [[x y] (pt e)]\n (cond\n ;; in presentation no box is written or created\n (locked?) nil\n (closest e \".resize-corner\") nil\n (closest e \".code-area\") nil\n (or (closest e \".param\") (closest e \".pval-hit\") (closest e \".pres-area\")\n (closest e \".stroke-hit\") (closest e \".score-slot\") (closest e \".mus-body\")) nil\n (and (closest e \".box.act\") (not (closest e \".grip\"))) nil\n (closest e \".hchip\") nil\n (closest e \".box\")\n (let [el (closest e \".box\") id (keyword (.. el -dataset -box)) b (get-in (current) [:boxes id])]\n (when b\n (if (or (and (or (embedded? b) (line-ref? b)) (not (.-altKey e))) (data-header? id (view-box b) x y))\n nil\n (open-editor! {:id id :x (:x b) :y (:y b) :text (:text b)}))))\n :else (open-editor! {:x x :y y})))))\n\n(defn stroke-key!\n \"Arrows, + − and Delete on the chosen stroke, respecting the grids of the canvas.\"\n [e k [id tid]]\n (let [b (get-in (current) [:boxes id]) d (:data b) tr (get-in d [:strokes tid]) sh (.-shiftKey e)]\n (if (nil? tr)\n (swap! ui assoc :nsel nil)\n (let [pts (:pts tr) [t0 f0] (first pts) dur (- (first (peek pts)) t0)\n gy (:gy d) stp (cv/step-x (:gx d)) cyc (cv/cycle (:gx d))\n g (canvas-geom d id b)\n dc (fn [dir] (cond\n (cv/generic? d) (* dir (if sh 5 1) (or (:step gy) (cv/nice-step (- (:yb g) (:ya g)) 20)))\n (:cents gy)\n (cv/round-to (cv/hz->cents (cv/degree->hz gy (+ (cv/hz->degree gy f0) (* dir (if sh (count (cv/degrees gy)) 1)))) f0) 3)\n :else (* dir (if sh 1200 100))))\n move-by (fn [dt c] (gesture! (str \"(move-stroke \" id \" \" tid \" \" (cv/fmt dt) \" \" (cv/fmt c) \")\")))\n stretch-to (fn [nd] (gesture! (str \"(stretch \" id \" \" tid \" \" (cv/fmt (/ nd dur)) \")\")))]\n (case k\n \"ArrowUp\" (move-by 0 (dc 1))\n \"ArrowDown\" (move-by 0 (dc -1))\n \"ArrowLeft\" (when (or (cv/generic? d) (pos? t0)) (move-by (- (if (cv/generic? d) (if sh cyc stp) (min t0 (if sh cyc stp)))) 0))\n \"ArrowRight\" (move-by (if sh cyc stp) 0)\n (\"+\" \"=\") (stretch-to (+ dur stp))\n \"-\" (when (> dur stp) (stretch-to (- dur stp)))\n (\"Delete\" \"Backspace\") (do (swap! ui assoc :nsel nil) (gesture! (str \"(erase-stroke \" id \" \" tid \")\")))\n \"Escape\" (swap! ui assoc :nsel nil)\n nil)))))\n\n(.addEventListener js/document \"keydown\"\n (fn [e]\n (let [tag (.. js/document -activeElement -tagName) k (.-key e) mod? (or (.-ctrlKey e) (.-metaKey e))]\n (when (and (= k \"Escape\") (:merge-pick @ui))\n (swap! ui assoc :merge-pick false)\n (.remove (.-classList ($ \"hist-wrap\")) \"picking\"))\n (when-not (#{\"INPUT\" \"TEXTAREA\"} tag)\n (cond\n (and (or (= k \"?\") (= k \"F1\")) (not mod?))\n (let [[kind v] (:sel @ui) b (when (= kind :box) (get-in (current) [:boxes v]))]\n (.preventDefault e)\n (show-help! (when b (klass (:text b)))))\n (and (:tsel @ui) (not mod?)\n (or (#{\"ArrowUp\" \"ArrowDown\" \"ArrowLeft\" \"ArrowRight\" \"+\" \"=\" \"-\" \"#\" \"Delete\" \"Backspace\" \"Escape\" \"Enter\"} k)\n (letter-pcs (str/lower-case k))))\n (do (.preventDefault e)\n (try (tree-key! k (.-shiftKey e))\n (catch :default ex (repl-print! \"err\" (esc (or (.-message ex) (str ex)))))))\n (and (:nsel @ui) (not mod?)\n (#{\"ArrowUp\" \"ArrowDown\" \"ArrowLeft\" \"ArrowRight\" \"+\" \"=\" \"-\" \"Delete\" \"Backspace\" \"Escape\"} k))\n (do (.preventDefault e) (stroke-key! e k (:nsel @ui)))\n (and (= k \" \") (not= tag \"BUTTON\") (.-hidden ($ \"manager\")))\n (do (.preventDefault e) (gesture! (if (eng/running?) \"(stop)\" \"(play)\")))\n (and (#{\"Delete\" \"Backspace\"} k) (:sel @ui) (not (locked?)))\n (let [[kind v] (:sel @ui)]\n (.preventDefault e)\n (swap! ui assoc :sel nil :insp nil)\n (case kind\n :box (gesture! (str \"(delete \" v \")\"))\n :boxes (gesture! (str \"(delete \" (str/join \" \" (sort-by box-num v)) \")\"))\n (gesture! (str \"(disconnect \" (str/join \" \" v) \")\"))))\n (and (= k \"Escape\") (or (:sel @ui) (:insp @ui)))\n (swap! ui assoc :sel nil :insp nil)\n ;; ⌘/Ctrl+A: every box on screen\n ;; (in presentation it selects nothing, and the browser does not select the page either)\n (and mod? (= (str/lower-case k) \"a\") (.-hidden ($ \"manager\")))\n (do (.preventDefault e)\n (when-not (locked?) (swap! ui assoc :sel (sel-of (keys (scene-boxes))) :insp nil :nsel nil :tsel nil)))\n (and mod? (= (str/lower-case k) \"z\") (.-shiftKey e))\n (do (.preventDefault e) (gesture! \"(forward)\"))\n (and mod? (= (str/lower-case k) \"z\"))\n (do (.preventDefault e) (gesture! \"(rewind)\"))\n (and mod? (= (str/lower-case k) \"y\"))\n (do (.preventDefault e) (gesture! \"(forward)\")))))))\n","page/06-connection.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 7 of 12: connection\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── connection to the shared history ─────────────────────────\n\n(defn js->node [d]\n (let [m (js->clj (.data d))\n at (get m \"at\") parent (get m \"parent\") evs (get m \"events\") t (get m \"t\")\n sess (get m \"session\") mg (get m \"merge\") ln (get m \"line\")]\n {:id (.-id d)\n :line (when (and (string? ln) (seq ln) (not= ln main-line)) ln)\n :parent (when (string? parent) parent)\n :at (if (number? at) at 0)\n :author (str (get m \"author\"))\n :session (when (string? sess) sess)\n :merge (when (valid-pos? mg) mg)\n :t (if (number? t) t 0)\n :events (if (sequential? evs)\n (vec (keep (fn [x] (let [v (dec* x)] (when (and (vector? v) (keyword? (first v))) v))) evs))\n [])}))\n\n(defn merge-incoming\n \"The segments of one line as they arrive, with yours not saved yet (or longer here than there) kept.\"\n [local incoming]\n (let [mine? (fn [n] (= (:author n) (my-author)))\n pending (into {} (filter (fn [[k n]] (and (not (contains? incoming k)) (mine? n))) local))]\n (into pending\n (for [[k r] incoming :let [l (get local k)]]\n [k (if (and l (mine? l) (> (count (:events l)) (count (:events r)))) l r)]))))\n\n(defn on-history [snap]\n (let [incoming (group-by (fn [n] (or (:line n) main-line))\n (for [d (array-seq (.-docs snap)) :when (.-exists d)] (js->node d)))\n by-id (fn [ns] (into {} (map (fn [n] [(:id n) n]) ns)))]\n (swap! hist\n (fn [h]\n (let [active (active-line)\n lines (disj (into (set (keys incoming)) (keys (:other h))) active)]\n (assoc h\n :nodes (merge-incoming (:nodes h) (by-id (get incoming active)))\n :other (into {} (for [l lines] [l (merge-incoming (get-in h [:other l]) (by-id (get incoming l)))]))\n :loaded true))))\n (when (nil? (:pos @world))\n (when-let [t (newest-tip)] (swap! world assoc :pos t)))))\n\n(defn start-local!\n \"A local work begins empty: the first gesture is its root (the example work is a button away, in the history pane).\"\n []\n (swap! hist assoc :mode :local :loaded true))\n\n(defn setup-room!\n \"Presence inside the open room (one named room per shared work).\"\n [room]\n (.onPeers room\n (fn [ch]\n (reset! peers\n (vec (for [p (array-seq (.-peers ch)) :when (not= \"agent\" (.-kind p))]\n {:peer (.-peer p) :by (.-by p) :me (.-isMe p) :same (.-sameTab p) :kind (.-kind p)\n :session (let [s (.. p -presence -session)] (when (string? s) s))\n :pos (let [pp (js->clj (.. p -presence -pos))] (when (valid-pos? pp) pp))\n ;; the line they are on (#117): their position is a point of that line\n :line (let [l (.. p -presence -line)] (if (and (string? l) (seq l)) l main-line))\n ;; performing in a jam (issue #5): its id and the point of the history it starts from\n :jam (let [j (.. p -presence -jam)] (when (string? j) j))\n :jam-at (let [pp (js->clj (.. p -presence -jamAt))] (when (valid-pos? pp) pp))}))))\n (fn [_] nil))\n (publish-presence!))\n\n;; Where the page gets its database, rooms, user and Claude: inside claude.ai from the viewer\n;; (window.claude); anywhere else from a backend with the same shape (window.kairoticBackend: GUN for\n;; data and rooms, Claude with your own API key — see kairotic/backends/gun-backend.js). Study 17.\n(defn backend [] (.-kairoticBackend js/window))\n(defn pages? \"True outside claude.ai, when the page runs on its own backend (Kairotic Pages).\"\n [] (boolean (and (not (.-claude js/window)) (backend))))\n;; ───── relays (Pages): which ones this page syncs through, chosen in the session manager ─────\n;; The choice is ?peer= in the address (boot.js reads it and remembers it in this browser): a list of\n;; wss://…/gun, off (no relay at all) or none (back to the site's, site/config.js). Choosing reloads the\n;; page with it. While the relays are not the site's, the address and the room links carry ?peer=, so\n;; whoever opens them syncs through the same relays and sees the same rooms.\n\n(defn site-relays [] (vec (js->clj (or (.-KAIROTIC_PEERS js/window) #js []))))\n(defn current-relays [] (vec (js->clj (or (.-kairoticPeers js/window) #js []))))\n\n(defn relay-param\n \"What ?peer= must say for someone else to sync through the relays of this page: nil when they are the site's.\"\n []\n (let [c (current-relays)]\n (cond (= c (site-relays)) nil\n (empty? c) \"off\"\n :else (str/join \",\" c))))\n\n(defn with-relay\n \"url with the ?peer= of this page's relays (or without one, when they are the site's).\"\n [url]\n (let [u (js/URL. url (.-href js/location)) p (relay-param)]\n (if p (.set (.-searchParams u) \"peer\" p) (.delete (.-searchParams u) \"peer\"))\n (str/replace (.toString u) #\"peer=([^&#]*)\" (fn [[_ v]] (str \"peer=\" (js/decodeURIComponent v))))))\n\n(defn normalize-relay\n \"What someone writes as a relay, as GUN wants it: https://host → wss://host/gun, host:port → ws(s)://host:port/gun.\n nil if it cannot be a relay.\"\n [s]\n (let [s (str/trim (str s))\n s (cond (str/starts-with? s \"https://\") (str \"wss://\" (subs s 8))\n (str/starts-with? s \"http://\") (str \"ws://\" (subs s 7))\n (re-find #\"^wss?://\" s) s\n (re-find #\"^(localhost|127\\.0\\.0\\.1)(:|/|$)\" s) (str \"ws://\" s)\n (seq s) (str \"wss://\" s)\n :else s)]\n (when-let [[_ scheme host path] (re-matches #\"(wss?)://([^/\\s,]+)(/[^\\s,]*)?\" s)]\n (str scheme \"://\" host (if (or (nil? path) (= \"/\" path)) \"/gun\" path)))))\n\n(defn relay-problem\n \"Why a page could not use relay url, or nil.\"\n [url]\n (cond (nil? url) \"That is not a relay address: it looks like wss://host/gun.\"\n (and (= \"https:\" (.-protocol js/location)) (str/starts-with? url \"ws://\")\n (not (re-find #\"^ws://(localhost|127\\.0\\.0\\.1)[:/]\" url)))\n \"This page is served over https, so it can only reach a relay at wss:// (a host with TLS).\"\n :else nil))\n\n(defn choose-relays!\n \"Reloads the page syncing through v: a list of relays, \\\"off\\\" (no relay) or \\\"none\\\" (the site's).\"\n [v]\n (let [u (js/URL. (.-href js/location))]\n (.set (.-searchParams u) \"peer\" v)\n (.assign js/location (str/replace (.toString u) #\"peer=([^&#]*)\" (fn [[_ x]] (str \"peer=\" (js/decodeURIComponent x)))))))\n\n(defn address-carries-relay!\n \"Keeps ?peer= in the address while the relays are not the site's (so a copied address takes them along),\n and takes it away when they are.\"\n []\n (when (and (pages?) (not embed-mode))\n (let [now (.-href js/location) want (with-relay now)]\n (when (not= now want)\n (try (.replaceState js/history nil \"\" want) (catch :default _ nil))))))\n\n(defonce relay-status (atom [])) ; [{:url :state}] while the session manager is open\n(defonce relay-test (atom nil)) ; {:url :state :testing|:ok|:fail :msg}\n\n(defn refresh-relay-status! []\n (when-let [f (and (pages?) (.-relays (backend)))]\n (let [st (vec (for [r (array-seq (f))] {:url (.-url r) :state (keyword (.-state r))}))]\n (when (not= st @relay-status) (reset! relay-status st)))))\n\n(defn test-relay!\n \"Tries to open a connection to a relay (a free one may take up to a minute to wake up).\"\n [url]\n (reset! relay-test {:url url :state :testing})\n (try\n (let [ws (js/WebSocket. url)\n done (fn [state msg]\n (when (= (:url @relay-test) url)\n (when (= :testing (:state @relay-test)) (reset! relay-test {:url url :state state :msg msg})))\n (try (.close ws) (catch :default _ nil)))]\n (set! (.-onopen ws) (fn [_] (done :ok \"It answers.\")))\n (set! (.-onerror ws) (fn [_] (done :fail \"It does not answer: check the address, or that the relay is running.\")))\n (js/setTimeout (fn [] (done :fail \"No answer after 20 seconds (a free relay may take up to a minute to wake up: try again).\")) 20000))\n (catch :default e (reset! relay-test {:url url :state :fail :msg (str (.-message e))}))))\n\n(def relay-states {:open [\"ok\" \"connected\"] :connecting [\"wait\" \"connecting…\"] :waiting [\"wait\" \"waiting for it (a free relay may take a minute to wake up)\"]})\n\n(defn relay-section\n \"On Pages, the relays of this page in the session manager: their state, choosing others, running your own.\"\n [open?]\n (when (pages?)\n (let [cur (current-relays) site (site-relays) default? (= cur site)\n st (into {} (map (juxt :url :state) @relay-status))\n {t-url :url t-state :state t-msg :msg} @relay-test\n dot (fn [u] (let [[cls word] (get relay-states (get st u :waiting))]\n (str \"<span class=\\\"rdot \" cls \"\\\"></span><span class=\\\"rstate\\\">\" word \"</span>\")))\n summary (cond (empty? cur) \"No relay: works stay in this browser, rooms reach nobody else\"\n default? (str \"The site's relay\" (when (> (count cur) 1) \"s\"))\n :else (str \"Your relay\" (when (> (count cur) 1) \"s\")))\n all-open (and (seq cur) (every? (fn [u] (= :open (get st u))) cur))]\n (str \"<details class=\\\"relays\\\" id=\\\"relays\\\"\" (when open? \" open\") \">\"\n \"<summary><span class=\\\"rlabel\\\">Relay</span> \" (esc summary)\n (when (seq cur) (str \" <span class=\\\"rdot \" (if all-open \"ok\" \"wait\") \"\\\"></span>\")) \"</summary>\"\n \"<p class=\\\"mgr-hint\\\">A relay is a small server that passes works and rooms between browsers and keeps a copy. \"\n \"Everyone in a community uses the same one: the rooms of one relay are not seen through another.</p>\"\n (when (seq cur)\n (str \"<ul class=\\\"rlist\\\">\"\n (apply str (for [u cur]\n (str \"<li><code>\" (esc u) \"</code> \" (dot u)\n (when (> (count cur) 1)\n (str \" <button class=\\\"act small\\\" data-act=\\\"relay-drop\\\" data-url=\\\"\" (esc u) \"\\\">Remove</button>\"))\n \"</li>\")))\n \"</ul>\"))\n \"<form class=\\\"new\\\" data-kind=\\\"relay\\\"><input id=\\\"relay-url\\\" placeholder=\\\"wss://your-relay.example/gun\\\" spellcheck=\\\"false\\\" autocomplete=\\\"off\\\">\"\n \"<button type=\\\"button\\\" class=\\\"act\\\" data-act=\\\"relay-test\\\">Test</button>\"\n \"<button class=\\\"act primary\\\">Use</button></form>\"\n (when t-url\n (str \"<p class=\\\"rtest \" (name t-state) \"\\\"><code>\" (esc t-url) \"</code>: \"\n (case t-state :testing \"trying…\" (esc t-msg)) \"</p>\"))\n \"<p class=\\\"rchoices\\\">\"\n (when-not default? (str \"<button class=\\\"act\\\" data-act=\\\"relay-site\\\">Use the site's relay\" (when (> (count site) 1) \"s\") \"</button> \"))\n (when (seq cur) \"<button class=\\\"act\\\" data-act=\\\"relay-off\\\">Work without a relay</button>\")\n \"</p>\"\n \"<p class=\\\"mgr-hint\\\">Changing it reloads the page. While it is not the site's, the address and the room links carry it \"\n \"(<code>?peer=…</code>), so whoever opens them syncs through it too.</p>\"\n \"<details class=\\\"rown\\\"><summary>Run your own relay</summary>\"\n \"<p>On any computer or server with Node.js 18 or later:</p>\"\n \"<pre>npx @kairotic/relay --port 8765 --data ./radata</pre>\"\n \"<p>It answers at <code>ws://localhost:8765/gun</code>. For others to reach it, put it on a host with TLS — a small VPS, \"\n \"<a href=\\\"https://render.com/deploy?repo=https://github.com/bonuoq/kairotic\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\">Render</a>, \"\n \"Fly.io, Railway, or your machine behind a tunnel — and use <code>wss://<that host>/gun</code> here. \"\n \"It keeps what it is sent in its data folder: rooms in clear, solo works encrypted. Back that folder up. \"\n \"<a href=\\\"https://github.com/bonuoq/kairotic/tree/main/relay#readme\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\">More</a></p>\"\n \"</details>\"\n \"</details>\"))))\n\n(defn cuse [nm]\n (cond\n (.-claude js/window) (.catch (.use (.-claude js/window) nm) (fn [_] nil))\n (backend) (js/Promise.resolve (aget (backend) nm))\n :else (js/Promise.resolve nil)))\n","page/07-claude.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 8 of 12: claude\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── components written with Claude (Study 15) ─────────────────────────\n;; The page asks Claude through claude.ai's `sample` capability: on the viewer's own Claude account,\n;; with their consent. Claude gets the contract, the API, real components and the request, and can call\n;; the page's tools (kairotic.assistant) to check what it writes before it answers. The answer's source\n;; becomes a component box, written as gestures like any other.\n\n(defonce sample-fn (atom nil))\n(defonce ask-ctl (atom nil))\n(defonce ask-refs (atom nil))\n\n;; ───── the log of requests to Claude, kept in this browser (Study 23) ─────\n\n(def ask-log-key \"kairotic.claude-log\")\n(defonce asking (atom nil)) ; the request on its way: {:id :t :kind :request :change :tier :lines :status :code :answer}\n\n(defn ask-entries []\n (or (try (some-> (.getItem js/localStorage ask-log-key) js/JSON.parse (js->clj :keywordize-keys true) vec)\n (catch :default _ nil))\n []))\n\n(defn save-ask-entries! [es]\n (let [es (vec (take-last 200 es))]\n (try (.setItem js/localStorage ask-log-key (js/JSON.stringify (clj->js es)))\n (catch :default _\n ;; full: the older half goes\n (try (.setItem js/localStorage ask-log-key (js/JSON.stringify (clj->js (vec (take-last (quot (count es) 2) es)))))\n (catch :default _ nil))))))\n\n(declare render-ask-history!)\n\n(defn begin-ask! [kind request change?]\n (reset! asking {:id (str (js/Date.now)) :t (.toISOString (js/Date.)) :kind (name kind) :request request\n :change (boolean change?) :tier (some-> ($ \"ask-tier\") .-value) :work (:name @work)\n :lines [] :status \"asked\"}))\n\n(defn note-answer! [r src]\n (when @asking (swap! asking assoc :answer (ai/cut (.-text r) 8000) :code src :model (.-modelTierApplied r))))\n\n(defn end-ask! []\n (when-let [a @asking]\n (reset! asking nil)\n (save-ask-entries! (conj (ask-entries) a))\n (render-ask-history!)))\n\n(defn ask-log! [cls text]\n (when @asking\n (swap! asking (fn [a] (cond-> (update a :lines conj (str (when (seq cls) (str cls \": \")) text))\n (= cls \"done\") (assoc :status \"made\")\n (and (= cls \"err\") (not= \"made\" (:status a))) (assoc :status \"failed\" :error text)))))\n ;; the bar of a link (?ask=) shows the last line too\n (when-let [st ($ \"ab-status\")] (set! (.-textContent st) text))\n (when-let [ol ($ \"ask-log\")]\n (let [li (js/document.createElement \"li\")]\n (set! (.-className li) (or cls \"\"))\n (set! (.-textContent li) text)\n (.appendChild ol li))))\n\n(defn fetch-text [path] (-> (js/fetch path) (.then (fn [r] (if (.-ok r) (.text r) (throw (js/Error. (str path \" \" (.-status r)))))))))\n\n(defn load-ask-refs\n \"Promise of what Claude reads besides the request: the contract and shapes documentation, the API\n and the catalog of examples (two of them given whole, the rest read with a tool). Loaded once.\"\n []\n (or @ask-refs\n (let [p (-> (js/Promise.all #js [(fetch-text \"kairotic/components.cljs\") (fetch-text \"kairotic/shapes.cljs\")\n (fetch-text \"kairotic/api.cljs\")\n ((.-kairoticImport js/window) \"kairotic/examples.mjs\")])\n (.then (fn [a]\n (let [examples (:examples (js->clj (aget a 3) :keywordize-keys true))\n by-name (fn [n] (first (filter #(= n (:name %)) examples)))]\n {:contract (str (ai/header-of (aget a 0)) \"\\n\\nViews — \" (ai/header-of (aget a 1)))\n :api (aget a 2)\n :examples (vec examples)\n :always (vec (keep by-name [\"knob\" \"filter-panel\"]))})))\n (.catch (fn [e] (reset! ask-refs nil) (throw e))))]\n (reset! ask-refs p)\n p)))\n\n(defn ask-tools\n \"The page functions Claude may call while it writes (small plain-data results).\"\n [refs]\n (let [src-schema {:type \"string\" :description \"the complete source (a component, an abstraction or a package)\"}\n cls-schema {:type \"string\" :description \"which class, when the source is a package (else omit)\"}\n logged (fn [label f]\n (fn [input _]\n (-> (js/Promise.resolve nil)\n (.then (fn [_] (f input)))\n (.catch (fn [e] {:ok false :error (or (.-message e) (str e))}))\n (.then (fn [r]\n (ask-log! (if (:ok r) \"ok\" \"err\")\n (str label (when-let [c (or (:class r) (:box-text r) (:name r)\n (some->> (:definitions r) (map :class) seq (str/join \", \")))]\n (str \" · \" c))\n (when-let [e (or (:error r) (first (:errors r)))] (str \" · \" (ai/cut e 160)))))\n (clj->js r))))))]\n #js [#js {:name \"read_example\"\n :description \"The whole source of an example of the catalog, by name. Read the ones close to the request before writing.\"\n :inputSchema (clj->js {:type \"object\" :properties {:name {:type \"string\"}} :required [\"name\"]})\n :execute (logged \"read example\"\n (fn [i] (if-let [e (first (filter #(= (str (.-name i)) (:name %)) (:examples refs)))]\n {:ok true :name (:name e) :kind (:kind e) :source (:source e)}\n {:ok false :error (str \"no example \" (.-name i))})))}\n #js {:name \"check_faust\"\n :description \"Compiles Faust code with the page's compiler. Returns {ok, ins, outs, params} or {ok:false, error} with the compiler's message. Use it for every Faust source before putting it in a faust~ box.\"\n :inputSchema (clj->js {:type \"object\" :properties {:code {:type \"string\" :description \"the Faust source\"}} :required [\"code\"]})\n :execute (logged \"check Faust\" (fn [i] (ai/compile-faust (str (.-code i)))))}\n #js {:name \"check_component\"\n :description \"Evaluates the whole source and validates it: every definition, the patch of abstractions (classes that exist, valid ports in every line) and the Faust inside them, compiled. Returns {ok, definitions, errors}. Call it before answering, and again after every fix.\"\n :inputSchema (clj->js {:type \"object\" :properties {:source src-schema} :required [\"source\"]})\n :execute (logged \"check\" (fn [i] (ai/check-full (str (.-source i)))))}\n #js {:name \"try_messages\"\n :description \"Sends messages to a component's :receive one after another (its state carried over, as in the engine) and returns what each returned (out, show, effects, later, state) or the error. Not for abstractions (they are patches). args_text is what follows the class in the box text, e.g. \\\"0 1 log\\\".\"\n :inputSchema (clj->js {:type \"object\"\n :properties {:source src-schema :class cls-schema\n :args_text {:type \"string\" :description \"words after the class in the box text (may be empty)\"}\n :messages {:type \"string\" :description \"EDN vector of [inlet value], e.g. [[0 440] [0 :bang] [1 [1 2]]]\"}}\n :required [\"source\" \"messages\"]})\n :execute (logged \"try messages\" (fn [i] (ai/try-receive (str (.-source i)) (str (or (.-class i) \"\")) (str (or (.-args_text i) \"\")) (str (.-messages i)))))}\n #js {:name \"try_view\"\n :description \"Draws a component's own view (:view with :derive, or :draw) for a shown value and box text, and reports shapes without a valid kind, holes without a value and non-finite numbers; with a :gesture it also tries one drag and what :persist would write.\"\n :inputSchema (clj->js {:type \"object\"\n :properties {:source src-schema :class cls-schema\n :args_text {:type \"string\"}\n :shown {:type \"string\" :description \"EDN of the last shown value, e.g. 0.5 or [0.2 0.8], or empty\"}}\n :required [\"source\"]})\n :execute (logged \"try view\" (fn [i] (ai/try-view (str (.-source i)) (str (or (.-class i) \"\")) (str (or (.-args_text i) \"\")) (str (or (.-shown i) \"\")))))}\n #js {:name \"list_classes\"\n :description \"The box classes the work knows now (core, packages, the work's own), one line each: name, [inlets outlets], first sentence of its doc.\"\n :execute (logged \"list classes\" (fn [_] {:ok true :classes (ai/classes)}))}]))\n\n(declare open-definition)\n\n(defn selected-component\n \"The component box chosen in the Components tab (or open in the code window), if it is in the patch on\n screen: [id source].\"\n []\n (let [[path id] (or @chosen-def (open-definition))\n b (when (= (vec path) (cmd-path)) (get-in (current) [:boxes id]))]\n (when (definition? b) [id (str (get-in b [:data :source]))])))\n\n(defn ask-busy! [busy?]\n (set! (.-disabled ($ \"ask-go\")) busy?)\n (set! (.-disabled ($ \"ask-stop\")) (not busy?)))\n\n(defn ask-error-copy [code]\n (case code\n \"not_granted\" (if (some-> @sample-fn .-byok) \"There is no API key, or it was refused: paste yours above.\" \"Claude is not allowed for this page (you can allow it next time you open it).\")\n \"sampling_disabled\" \"Claude is not available for this account.\"\n \"rate_limited\" \"Too many requests, or your Claude usage limit: try again later.\"\n \"session_expired\" \"Sign in to Claude again.\"\n \"refused\" \"Claude declined this request: try asking it differently.\"\n \"prompt_too_large\" \"The request is too large.\"\n \"no_credit\" \"Your Anthropic account has no credit left (console.anthropic.com → Billing).\"\n \"overloaded\" \"Claude is overloaded right now: try again in a moment.\"\n \"no_model\" \"The API does not know the model asked for.\"\n \"tools_unavailable\" \"This view cannot let Claude try the component.\"\n (str \"Claude could not answer (\" code \").\")))\n\n(defn ask-component!\n \"Asks Claude for a component (or a change to the selected component box) described by `request`.\"\n ([] (ask-component! (.-value ($ \"ask-text\"))))\n ([request]\n (let [s @sample-fn request (str/trim (str request))\n change (when (.-checked ($ \"ask-change\")) (selected-component))\n out ($ \"ask-out\")]\n (cond\n (nil? s) (repl-print! \"err\" \"Claude is not available in this view (it needs claude.ai).\")\n (empty? request) (ask-log! \"err\" \"Describe the component first.\")\n :else\n (let [ctl (js/AbortController.)]\n (reset! ask-ctl ctl)\n (set! (.-innerHTML ($ \"ask-log\")) \"\")\n (set! (.-textContent out) \"\")\n (ask-busy! true)\n (begin-ask! :component request change)\n (ask-log! \"\" (if change (str \"changing \" (name (first change)) \" · thinking…\") \"thinking…\"))\n ;; everything inside the promise chain: whatever fails, the panel is released in .finally\n (-> (js/Promise.resolve nil)\n (.then (fn [_] (js/Promise.all #js [(load-ask-refs)\n (-> (js/Promise.resolve (when (fn? (.-limits s)) (.limits s)))\n (.catch (fn [_] nil)))])))\n (.then (fn [a]\n (let [refs (aget a 0) lim (aget a 1)\n input (ai/prompt (assoc refs :request request :change (second change)))\n opts (cond-> {:modelTier (.-value ($ \"ask-tier\")) :signal (.-signal ctl)\n :onText (fn [u] (set! (.-textContent out) (.-text u)))}\n (and lim (.-tools lim)) (assoc :tools (ask-tools refs)))]\n (s input (clj->js opts)))))\n (.then (fn [r]\n (let [src (ai/source-of (.-text r)) _ (note-answer! r src)]\n (if (nil? src)\n (ask-log! \"err\" \"The answer has no source block: try again or ask differently.\")\n (-> (ai/check-full src)\n (.then (fn [chk]\n (if-not (:ok chk)\n (ask-log! \"err\" (str \"The source does not work: \" (or (:error chk) (str/join \"; \" (:errors chk))) \" (it is in the answer above).\"))\n (let [names (mapv :class (:definitions chk))\n what (or (:package chk) (first names))\n hdr (str \";; \" what \" · written with Claude\\n\"\n \";; asked: \" (str/replace (ai/cut request 300) #\"\\s+\" \" \") \"\\n\")\n id (if change\n (let [id (first change)] (gesture! (str \"(code \" id \" \" (pr-str (str hdr src)) \")\")) id)\n (new-definition! (str hdr src)))]\n ;; the official classes its abstractions use come into the work too\n (doseq [k (ai/used-classes src)] (ensure-class! (str k)))\n (ask-log! \"done\" (str (str/join \", \" (map #(str \"«\" % \"»\") names)) \" in the work (\" (name id) \"): write \"\n (str \"«\" (last names) \"»\") \" in a box to use it.\"))\n (when (.-truncated r) (ask-log! \"err\" \"The answer was cut short.\")))))))))))\n (.catch (fn [e]\n (let [code (or (.-code e) \"error\")]\n (when-not (= code \"cancelled\")\n (ask-log! \"err\" (if (= code \"error\") (str \"Error: \" (or (.-message e) e)) (str (ask-error-copy code) (when-let [m (.-message e)] (str \" — \" (ai/cut m 400))))))))))\n (.finally (fn [] (ask-busy! false) (reset! ask-ctl nil) (end-ask!)))))))\n :asking))\n\n(defn ask-what [] (if (.-checked (.querySelector js/document \"input[name=ask-what][value=component]\")) :component :patch))\n\n(defn render-ask-mode! []\n (let [patch? (= :patch (ask-what)) byok (some-> @sample-fn .-byok)]\n (set! (.-textContent ($ \"ask-change-t\")) (if patch? \"change the open patch\" \"change the selected component\"))\n (set! (.-title ($ \"ask-change-l\")) (if patch? \"Claude gets the open patch and changes it; unchecked, it makes a new one\" \"Choose a component in the Components tab first (a click on its row)\"))\n (set! (.-checked ($ \"ask-change\")) patch?)\n (set! (.-textContent ($ \"ask-go\")) (if patch? \"Make it\" \"Write it\"))\n (set! (.-placeholder ($ \"ask-text\"))\n (if patch?\n \"A hello world: a sine at 440 Hz with a volume knob… · add a knob that does FM synthesis… · a canon in two voices played by synth~…\"\n \"A stereo chorus in Faust with rate and depth knobs on its panel… · a resonant filter whose cutoff follows an envelope… · a Markov chain of pitch classes…\"))\n (set! (.-innerHTML ($ \"ask-note\"))\n (str (if patch?\n \"Describe a patch and Claude makes it — or changes the open one — checks it (classes, ports, Faust) and loads it as one event of the history.\"\n \"Describe a component and Claude writes it, tries it and puts it in the work as a component box, like one you wrote.\")\n (if byok\n \" Here, outside claude.ai, it uses <b>your own Anthropic API key</b> (console.anthropic.com): it stays in this browser and is only sent to api.anthropic.com, so you pay your own use.\"\n \" It uses <b>your own</b> Claude account: the first time, Claude asks you to allow this page.\")))))\n\n(.addEventListener (.querySelector js/document \".ask-what\") \"change\" (fn [_] (render-ask-mode!)))\n\n;; ───── patches made by Claude (Study 23) ─────\n\n(declare link-code)\n\n(defn ensure-classes!\n \"After a whole patch is loaded: the official classes its boxes use come into the work (a definition\n that was there before the load may have gone with it).\"\n []\n (doseq [b (vals (:boxes (eng/flat (root-patch))))] (ensure-class! (str (:text b)))))\n\n(defn check-patch-code\n \"Promise of {:ok :errors :boxes}: whether patch code (as a link carries it) makes a patch that works —\n only patch calls, classes that exist, lines between ports that exist, Faust that compiles and\n components that evaluate. Nothing goes into the work.\"\n [src]\n (-> (js/Promise.resolve nil)\n (.then (fn [_]\n (let [p (build (link-code src))\n bs (:boxes p)\n k-of (fn [b] (klass (:text b)))\n known? (fn [k] (or (comp/lookup k) (lib/package-of k)))\n unknown (vec (for [[id b] bs :let [k (k-of b)] :when (not (known? k))] (str (name id) \": no class «\" k \"»\")))\n fausts (vec (for [[id b] bs :when (= \"faust~\" (k-of b))] [id (str (get-in b [:data :source]))]))\n comps (vec (for [[id b] bs :when (#{\"component\"} (k-of b))] [id (str (get-in b [:data :source]))]))]\n (-> (js/Promise.all (into-array (concat (for [[_ src] fausts] (ai/compile-faust src))\n (for [[_ src] comps] (ai/check-full src)))))\n (.then (fn [rs]\n (let [rs (vec (array-seq rs))\n code-errs (vec (keep (fn [[[id _] r]] (when-not (:ok r) (str (name id) \": \" (or (:error r) (first (:errors r))))))\n (map vector (concat fausts comps) rs)))\n ;; ports, now that the Faust boxes know theirs (package classes not loaded yet are left out)\n io-of (fn [id] (let [b (get bs id)] (when (and b (comp/lookup (k-of b))) (io b))))\n line-errs (vec (for [[a o b i :as l] (:lines p)\n :let [[_ outs] (io-of a) [ins _] (io-of b)]\n e [(when-not (get bs a) (str (pr-str l) \": no box \" a))\n (when-not (get bs b) (str (pr-str l) \": no box \" b))\n (when (and outs (>= o outs)) (str (pr-str l) \": \" (name a) \" has \" outs \" outlet(s)\"))\n (when (and ins (>= i ins)) (str (pr-str l) \": \" (name b) \" has \" ins \" inlet(s)\"))]\n :when e] e))\n errs (vec (concat unknown code-errs line-errs))]\n {:ok (empty? errs) :errors errs\n :boxes (vec (for [[id b] bs] (str (name id) \" \" (:text b) (when-let [x (io-of id)] (str \" \" (pr-str x))))))})))))))\n (.catch (fn [e] {:ok false :errors [(str (or (.-message e) e))]}))))\n\n(defn patch-tools\n \"The page functions Claude may call while it makes a patch.\"\n [refs]\n (let [comp-tools (ask-tools refs)\n pick (fn [n] (first (filter #(= n (.-name %)) (array-seq comp-tools))))\n logged (fn [label f]\n (fn [input _]\n (-> (js/Promise.resolve nil)\n (.then (fn [_] (f input)))\n (.catch (fn [e] {:ok false :errors [(or (.-message e) (str e))]}))\n (.then (fn [r]\n (ask-log! (if (:ok r) \"ok\" \"err\") (str label (when-let [e (first (:errors r))] (str \" · \" (ai/cut e 160)))))\n (clj->js r))))))]\n #js [(pick \"list_classes\") (pick \"check_faust\") (pick \"read_example\") (pick \"check_component\")\n #js {:name \"class_help\"\n :description \"What one class does: its doc, usage, inlets and outlets (what each takes and sends), and an example.\"\n :inputSchema (clj->js {:type \"object\" :properties {:class {:type \"string\"}} :required [\"class\"]})\n :execute (logged \"help\"\n (fn [i] (let [k (str (.-class i)) d (comp/lookup k) h (hlp/of k)]\n (if (or d (seq h) (lib/package-of k))\n {:ok true :class k :doc (or (:doc d) (:doc h)) :usage (:usage d)\n :io (let [x (:io d)] (if (vector? x) x \"depends on its arguments\"))\n :inlets (:inlets h) :outlets (:outlets h) :example (:example h)\n :note (when-not d \"an official class: it comes into the work when a box uses it\")}\n {:ok false :errors [(str \"no class \" k)]}))))}\n #js {:name \"check_patch\"\n :description \"Checks the WHOLE patch code: only patch calls with literal arguments, classes that exist, every line between ports that exist, every Faust source compiled and every component evaluated. Returns {ok, errors, boxes}. Call it before answering, and again after every fix.\"\n :inputSchema (clj->js {:type \"object\" :properties {:code {:type \"string\" :description \"the whole patch code\"}} :required [\"code\"]})\n :execute (logged \"check patch\" (fn [i] (check-patch-code (str (.-code i)))))}]))\n\n(defn apply-patch-code!\n \"Loads patch code made by Claude into the open work (one event). Its scripts and components run: you\n asked for them.\"\n [src]\n (let [code (link-code src) p (build code)\n srcs (for [b (vals (:boxes p)) :when (#{\"script\" \"component\"} (klass (:text b)))] (str (get-in b [:data :source])))]\n (swap! cbox/trusted into srcs)\n (cbox/forget-language! \"component\")\n (cbox/forget-language! \"clojurescript\")\n (dispatch! [:load p])\n (ensure-classes!)\n (render-all!)\n code))\n\n(defn ask-patch!\n \"Asks Claude for a patch described by `request` (or a change to the open one, when change? is true).\n Promise of the code loaded, or nil.\"\n [request change?]\n (let [s @sample-fn request (str/trim (str request)) out ($ \"ask-out\")]\n (cond\n (nil? s) (do (ask-log! \"err\" \"Claude is not available here.\") (js/Promise.resolve nil))\n (empty? request) (do (ask-log! \"err\" \"Describe the patch first.\") (js/Promise.resolve nil))\n (nil? (:kind @work)) (do (ask-log! \"err\" \"Open or create a work first.\") (js/Promise.resolve nil))\n :else\n (let [ctl (js/AbortController.)\n current (when change? (let [p (work-patch)] (when (seq (:boxes p)) (patch->code p))))]\n (reset! ask-ctl ctl)\n (set! (.-innerHTML ($ \"ask-log\")) \"\")\n (set! (.-textContent out) \"\")\n (ask-busy! true)\n (begin-ask! :patch request current)\n (ask-log! \"\" (if current \"changing the patch · thinking…\" \"making the patch · thinking…\"))\n (-> (js/Promise.resolve nil)\n (.then (fn [_] (js/Promise.all #js [(load-ask-refs)\n (-> (js/Promise.resolve (when (fn? (.-limits s)) (.limits s))) (.catch (fn [_] nil)))])))\n (.then (fn [a]\n (let [refs (aget a 0) lim (aget a 1)\n input (ai/patch-prompt {:request request :current current :classes (ai/classes)})\n opts (cond-> {:modelTier (.-value ($ \"ask-tier\")) :signal (.-signal ctl)\n :onText (fn [u] (set! (.-textContent out) (.-text u)))}\n (and lim (.-tools lim)) (assoc :tools (patch-tools refs)))]\n (s input (clj->js opts)))))\n (.then (fn [r]\n (let [src (ai/source-of (.-text r)) _ (note-answer! r src)]\n (if (nil? src)\n (do (ask-log! \"err\" \"The answer has no patch code: try again or ask differently.\") nil)\n (.then (check-patch-code src)\n (fn [chk]\n (if-not (:ok chk)\n (do (ask-log! \"err\" (str \"The patch does not work yet: \" (str/join \"; \" (take 3 (:errors chk))) \" (it is in the answer, in the Claude tab).\")) nil)\n (let [code (apply-patch-code! src)]\n (ask-log! \"done\" (str \"Patch loaded (\" (count (:boxes (work-patch))) \" boxes): ▶ to hear it.\"\n (when (.-truncated r) \" The answer was cut short.\")))\n code))))))))\n (.catch (fn [e]\n (let [code (or (.-code e) \"error\")]\n (when-not (= code \"cancelled\")\n (ask-log! \"err\" (if (= code \"error\") (str \"Error: \" (or (.-message e) e)) (str (ask-error-copy code) (when-let [m (.-message e)] (str \" — \" (ai/cut m 400))))))))\n nil))\n (.finally (fn [] (ask-busy! false) (reset! ask-ctl nil) (end-ask!))))))))\n\n(defn ask!\n \"The Claude tab's button: a patch or a component, as chosen.\"\n ([] (ask! (.-value ($ \"ask-text\"))))\n ([request]\n (if (= :patch (ask-what))\n (do (ask-patch! request (.-checked ($ \"ask-change\"))) :asking)\n (ask-component! request))))\n\n(defn ask-patch\n \"Asks Claude to make a patch, or change the open one: (ask-patch \\\"add a knob that does FM\\\"). Uses your\n own Claude account (or your own API key outside claude.ai).\"\n ([request] (ask-patch request true))\n ([request change?]\n (set! (.-value ($ \"ask-text\")) (str request))\n (.click ($ \"tab-claude\"))\n (ask-patch! request change?)\n :asking))\n\n(defn ask-component\n \"Asks Claude to write a component: (ask-component \\\"a slow LFO with its waveform drawn\\\"). The result\n is a component box in the work. Uses your own Claude account.\"\n [request]\n (set! (.-value ($ \"ask-text\")) (str request))\n (.click ($ \"tab-claude\"))\n (ask-component! request))\n\n(.addEventListener ($ \"ask-go\") \"click\" (fn [_] (ask!)))\n(.addEventListener ($ \"ask-stop\") \"click\" (fn [_] (when-let [c @ask-ctl] (.abort c))))\n(.addEventListener ($ \"ask-text\") \"keydown\"\n (fn [e] (when (and (= \"Enter\" (.-key e)) (or (.-ctrlKey e) (.-metaKey e))) (.preventDefault e) (ask!))))\n\n;; outside claude.ai Claude runs with your own Anthropic API key, kept only in this browser\n(defn render-key! []\n (when-let [s @sample-fn]\n (when (.-byok s)\n (set! (.-hidden ($ \"ask-key\")) false)\n (set! (.-textContent ($ \"ask-key-state\")) (if (.hasKey s) \"a key is saved in this browser\" \"no key yet\")))))\n\n(.addEventListener ($ \"ask-key-save\") \"click\"\n (fn [_] (when-let [s @sample-fn]\n (let [v (str/trim (.-value ($ \"ask-key-in\")))]\n (when (seq v) (.setKey s v) (set! (.-value ($ \"ask-key-in\")) \"\") (render-key!))))))\n(.addEventListener ($ \"ask-key-forget\") \"click\"\n (fn [_] (when-let [s @sample-fn] (.setKey s nil) (render-key!))))\n\n(-> (cuse \"sample\")\n (.then (fn [s]\n (reset! sample-fn s)\n (set! (.-hidden ($ \"tab-claude\")) (nil? s))\n (render-key!)\n (render-ask-mode!)\n (render-askbar!))))\n","page/08-sessions.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 9 of 12: sessions\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── session manager ─────────────────────────\n\n(defonce rooms (atom {}))\n(defonce solo-works (atom {}))\n(defonce lobby-peers (atom []))\n(defonce snapshot-subs (atom [])) ; not `subs`: the page shares one namespace with components, and clojure.core/subs must stay a function there\n(defonce mgr (atom {:open true :confirm nil :busy nil :invite nil :relays false}))\n\n(defn room-name [id] (str \"room-\" (str/lower-case id)))\n\n(defn meta-of [d]\n (let [m (js->clj (.data d))]\n {:id (.-id d)\n :name (let [n (get m \"name\")] (if (and (string? n) (seq n)) n \"Untitled\"))\n :created (let [t (get m \"created\")] (if (number? t) t 0))\n :origin (let [o (get m \"origin\")] (when (string? o) o))}))\n\n(defn lobby-presence! []\n (when-let [r @roomref]\n (.catch (.presence r (clj->js {:room (when (= :room (:kind @work)) (:id @work))})) (fn [_] nil))))\n\n(defn people-in [id] (count (filter (fn [p] (= (:room p) id)) @lobby-peers)))\n\n(defn unsub-all! []\n (doseq [u @snapshot-subs] (u))\n (reset! snapshot-subs []))\n\n(defn leave-room! []\n (when-let [r @named-room]\n (.catch (.leave r) (fn [_] nil))\n (reset! named-room nil))\n (reset! peers []))\n\n(defn set-hash! [h]\n (try (if (seq h)\n (set! (.-hash js/location) h)\n (.replaceState js/history nil \"\" (str (.-pathname js/location) (.-search js/location))))\n (catch :default _ nil)))\n\n(defn show-manager! [] (swap! mgr assoc :open true :confirm nil))\n(defn hide-manager!\n \"Closes the session manager: back to the open work, or — when none is open yet — into a local one.\"\n []\n (if (:kind @work)\n (swap! mgr assoc :open false :confirm nil)\n (open-work! :local \"local\" \"Local\")))\n\n(defn on-meta [d]\n (when (.-exists d)\n (let [m (js->clj (.data d)) v (get m \"simultaneity_ms\") n (get m \"name\")]\n (when (string? n) (swap! work assoc :name n))\n (when (and (number? v) (<= 0 v 10000) (not= v (:simul-ms @settings)))\n (swap! settings assoc :simul-ms v)))))\n\n(defn reset-patch-state!\n \"What the boxes of the patch on screen showed and held is forgotten (a new box with the same id starts\n empty): when another work opens, or another line of this one (#117).\"\n []\n (swap! eng/rt assoc :shows {} :states {} :loops #{})\n (reset! score-cache {})\n (reset! live-trees {})\n (reset! dismissed-trees {})\n (reset! sent-trees {})\n (reset! sent-data {})\n (reset! sent-shape nil)\n (reset! msg-edits {}))\n\n(defn reset-work-state! [mode]\n (reset-patch-state!)\n (unsub-all!)\n (leave-room!)\n (reset! queues {})\n (reset! cache {})\n (reset! settings {:simul-ms 1500})\n (swap! ui assoc :follow nil :merge-pick false :sel nil :drag nil :wire nil)\n (.remove (.-classList ($ \"hist-wrap\")) \"picking\")\n (reset! world {:pos nil :auto true :prev-pos nil :jumped-at 0})\n (reset! line-state {:active main-line :index {} :pos {}})\n (swap! hist assoc :nodes {} :other {} :loaded false :mode mode))\n\n(defonce lesson (atom nil)) ; the open lesson (a tutorial or a help patch), Study 18\n\n(defn open-work!\n \"Opens a work: :room (shared), :solo (private) or :local (not saved).\"\n [kind id nm]\n (eng/stop!)\n (reset! lesson nil)\n (reset! cbox/trust (not= kind :room))\n (cbox/forget-language! \"clojurescript\")\n (reset! work {:kind kind :id id :name nm})\n (reset-work-state! (case kind\n :room (if (:writable @hist) :shared :readonly)\n :solo :solo\n :local))\n (swap! mgr assoc :open false :confirm nil :invite nil)\n (set-hash! (if (= kind :room) (str \"room-\" id) \"\"))\n (lobby-presence!)\n (if (= kind :local)\n (start-local!)\n (let [db @dbref]\n (swap! snapshot-subs conj (.onSnapshot (.collection db (hist-path)) on-history db-failed!))\n (swap! snapshot-subs conj (.onSnapshot (.doc db (work-base)) on-meta (fn [_] nil)))\n ;; the names of its lines (#117)\n (swap! snapshot-subs conj (.onSnapshot (.collection db (str (work-base) \"/lines\")) on-lines (fn [_] nil)))\n (when (and (= kind :room) @roomref)\n (-> (.join @roomref (room-name id))\n (.then (fn [r]\n (if (and (= :room (:kind @work)) (= id (:id @work)))\n (do (reset! named-room r) (setup-room! r))\n (.catch (.leave r) (fn [_] nil)))))\n (.catch (fn [_] nil))))))\n (repl-print! \"out\" (esc (str \"; \" (case kind :room \"Shared room\" :solo \"Solo work\" \"Local work\") \": «\" nm \"»\"))))\n\n(defn close-work! []\n (reset! lesson nil)\n (reset! work {:kind nil :id nil :name nil})\n (reset-work-state! :none)\n (set-hash! \"\")\n (lobby-presence!)\n (show-manager!))\n\n(defn coll-for [kind] (case kind :room \"rooms\" :solo (str \"data/users/\" (uid))))\n\n(defn busy! [msg] (swap! mgr assoc :busy msg))\n\n(defn mgr-fail! [e]\n (busy! nil)\n (db-failed! e))\n\n(defn create-work! [kind nm example?]\n (let [db @dbref\n ref (.doc (.collection db (coll-for kind)))\n id (.-id ref)]\n (busy! \"Creating…\")\n (-> (.set ref (clj->js {:name nm :created (js/Date.now) :author (uid) :simultaneity_ms 1500}))\n (.then (fn [_]\n (busy! nil)\n (open-work! kind id nm)\n (when example? (gesture! \"(load-example)\"))))\n (.catch mgr-fail!))))\n\n(defn plain [o] (js/JSON.parse (js/JSON.stringify o)))\n\n(defn copy-work!\n \"Copies a work with all its history into a new work (from room to solo or the other way round).\"\n [from-kind from-id to-kind nm]\n (let [db @dbref\n src (str (base-of from-kind from-id) \"/history\")\n ref (.doc (.collection db (coll-for to-kind)))\n id (.-id ref)\n dst (str (coll-for to-kind) \"/\" id \"/history\")]\n (busy! \"Copying the history…\")\n (-> (.set ref (clj->js {:name nm :created (js/Date.now) :author (uid) :simultaneity_ms 1500\n :origin (str (name from-kind) \":\" from-id)}))\n (.then (fn [_] (.get (.collection db src))))\n (.then (fn [snap]\n (reduce (fn [p d] (.then p (fn [_] (.set (.doc db (str dst \"/\" (.-id d))) (plain (.data d))))))\n (js/Promise.resolve nil)\n (array-seq (.-docs snap)))))\n ;; and the names of its lines (their segments came with the history)\n (.then (fn [_] (.get (.collection db (str (base-of from-kind from-id) \"/lines\")))))\n (.then (fn [snap]\n (reduce (fn [p d] (.then p (fn [_] (.set (.doc db (str (coll-for to-kind) \"/\" id \"/lines/\" (.-id d))) (plain (.data d))))))\n (js/Promise.resolve nil)\n (filter (fn [d] (.-exists d)) (array-seq (.-docs snap))))))\n (.then (fn [_] (busy! nil) (open-work! to-kind id nm)))\n (.catch mgr-fail!))))\n\n(defn delete-work!\n \"Deletes a work and all its history.\"\n [kind id]\n (let [db @dbref base (base-of kind id)]\n (when (and (= kind (:kind @work)) (= id (:id @work))) (close-work!))\n (busy! \"Deleting…\")\n (-> (.get (.collection db (str base \"/history\")))\n (.then (fn [snap]\n (reduce (fn [p d] (.then p (fn [_] (.delete (.doc db (str base \"/history/\" (.-id d)))))))\n (js/Promise.resolve nil)\n (array-seq (.-docs snap)))))\n ;; the names of its lines (their segments went with the history)\n (.then (fn [_] (.get (.collection db (str base \"/lines\")))))\n (.then (fn [snap]\n (reduce (fn [p d] (.then p (fn [_] (.delete (.doc db (str base \"/lines/\" (.-id d)))))))\n (js/Promise.resolve nil)\n (array-seq (.-docs snap)))))\n (.then (fn [_] (.delete (.doc db base))))\n (.then (fn [_] (busy! nil) (swap! mgr assoc :confirm nil)))\n (.catch mgr-fail!))))\n\n(defn fmt-date [t]\n (if (pos? t)\n (let [d (js/Date. t)]\n (str (.toLocaleDateString d \"en-GB\" #js {:day \"numeric\" :month \"short\"}) \" · \"\n (.toLocaleTimeString d \"en-GB\" #js {:hour \"2-digit\" :minute \"2-digit\"})))\n \"\"))\n\n(defn room-link\n \"A link to room id on this site, with this page's relays when they are not the site's.\"\n [id]\n (with-relay (str (.-origin js/location) (.-pathname js/location) \"#room-\" id)))\n\n(defn item-html [kind {:keys [id created origin] nm :name}]\n (let [k (name kind)\n current? (and (= kind (:kind @work)) (= id (:id @work)))\n confirm? (= (:confirm @mgr) [k id])\n n (when (= kind :room) (people-in id))\n can-write (:writable @hist)]\n (str \"<li class=\\\"item\" (when current? \" current\") (when (= id (:invite @mgr)) \" invited\") \"\\\">\"\n \"<div class=\\\"item-main\\\"><span class=\\\"item-name\\\">\" (esc nm) \"</span>\"\n \"<span class=\\\"item-meta\\\">\" (fmt-date created)\n (when origin (str \" · copy\"))\n (when (and n (pos? n)) (str \" · <b>\" n (if (= 1 n) \" person inside\" \" people inside\") \"</b>\"))\n (when current? \" · open now\")\n \"</span></div>\"\n \"<div class=\\\"item-acts\\\">\"\n \"<button class=\\\"act primary\\\" data-act=\\\"open\\\" data-kind=\\\"\" k \"\\\" data-id=\\\"\" (esc id) \"\\\">\" (if current? \"Back\" \"Open\") \"</button>\"\n (when (and (= kind :room) (pages?))\n (str \"<button class=\\\"act\\\" data-act=\\\"link\\\" data-kind=\\\"room\\\" data-id=\\\"\" (esc id) \"\\\" title=\\\"Copies a link to this room\"\n (when (relay-param) \", with the relay it is on\") \"\\\">Copy link</button>\"))\n (when can-write\n (str (if (= kind :solo)\n (str \"<button class=\\\"act\\\" data-act=\\\"copy\\\" data-kind=\\\"\" k \"\\\" data-to=\\\"room\\\" data-id=\\\"\" (esc id) \"\\\" title=\\\"Creates a shared room with a copy of this work and its history\\\">Share a copy</button>\")\n (str \"<button class=\\\"act\\\" data-act=\\\"copy\\\" data-kind=\\\"\" k \"\\\" data-to=\\\"solo\\\" data-id=\\\"\" (esc id) \"\\\" title=\\\"Creates a solo work with a copy of this room and its history\\\">Copy for me</button>\"))\n \"<button class=\\\"act danger\" (when confirm? \" armed\") \"\\\" data-act=\\\"delete\\\" data-kind=\\\"\" k \"\\\" data-id=\\\"\" (esc id) \"\\\">\"\n (if confirm? \"Sure? Delete\" \"Delete\") \"</button>\"))\n \"</div></li>\")))\n\n(defn welcome\n \"What the session manager says before any work is open: what Kairotic is, how to start, and that it is an alpha.\"\n []\n (if (es?)\n (str \"<div class=\\\"mgr-welcome\\\">\"\n \"<p class=\\\"wt\\\">Te damos la bienvenida a <b>Kairotic</b> <span class=\\\"alpha\\\">0.2.0-alpha</span></p>\"\n \"<p>Un espacio para componer, improvisar e interpretar música donde <b>el patch y su código son la misma obra</b>: cajas unidas por líneas, como en Max o Pure Data, cada gesto guardado en una historia que puedes recorrer, ramificar y compartir.</p>\"\n \"<ul>\"\n \"<li><b>Empieza</b> abajo: una obra <b>solo</b> (se guarda para ti), una <b>sala compartida</b> (con otras personas en la misma historia) o <b>en local</b>, sin guardar.</li>\"\n \"<li><b>Doble clic</b> en un sitio vacío crea una caja (<code>osc~ 440</code>); arrastra de una salida a una entrada para conectar; <b>▶</b> pone en marcha el sonido.</li>\"\n \"<li>La pestaña <b>Help</b> tiene la guía, los conceptos, los tutoriales y una página para cada caja; <b>Claude</b> hace patches a partir de lo que describes.</li>\"\n \"</ul>\"\n \"<p class=\\\"alpha-note\\\">Es una <b>versión alfa</b>: puede fallar, y cambiará. Lo que nos cuentes decide lo que viene después; la pestaña <b>Feedback</b> lo convierte en un aviso en GitHub. ¡Gracias por probarla!</p>\"\n \"<p class=\\\"wb\\\"><button class=\\\"act primary\\\" data-act=\\\"guide\\\">Leer la guía</button> <button class=\\\"act\\\" data-act=\\\"local\\\">Empezar en local</button> <button class=\\\"act\\\" data-act=\\\"feedback\\\">Feedback</button></p>\"\n \"</div>\")\n (str \"<div class=\\\"mgr-welcome\\\">\"\n \"<p class=\\\"wt\\\">Welcome to <b>Kairotic</b> <span class=\\\"alpha\\\">0.2.0-alpha</span></p>\"\n \"<p>A space to compose, improvise and perform music where <b>the patch and its code are the same work</b>: boxes joined by lines, as in Max or Pure Data, every gesture kept in a history you can travel, branch and share.</p>\"\n \"<ul>\"\n \"<li><b>Start</b> below: a <b>solo</b> work (saved for you), a <b>shared room</b> (with others, in the same history) or <b>locally</b>, without saving.</li>\"\n \"<li><b>Double-click</b> an empty place to create a box (<code>osc~ 440</code>); drag from an outlet to an inlet to connect; <b>▶</b> starts the sound.</li>\"\n \"<li>The <b>Help</b> tab has the guide, the concepts, the tutorials and a page for every box; <b>Claude</b> makes patches from what you describe.</li>\"\n \"</ul>\"\n \"<p class=\\\"alpha-note\\\">This is an <b>alpha</b>: it may fail, and it will change. What you tell us decides what comes next; the <b>Feedback</b> tab turns it into a GitHub issue. Thank you for trying it!</p>\"\n \"<p class=\\\"wb\\\"><button class=\\\"act primary\\\" data-act=\\\"guide\\\">Read the guide</button> <button class=\\\"act\\\" data-act=\\\"local\\\">Start locally</button> <button class=\\\"act\\\" data-act=\\\"feedback\\\">Feedback</button></p>\"\n \"</div>\")))\n\n(defn render-manager! []\n (let [{:keys [open busy invite]} @mgr\n el ($ \"manager\")\n db? (some? @dbref)\n can-write (:writable @hist)\n connecting? (= :connecting (:mode @hist))\n solo-list (sort-by :created > (vals @solo-works))\n room-list (sort-by (fn [s] [(if (= (:id s) invite) 0 1) (- (people-in (:id s))) (- (:created s))]) (vals @rooms))\n inv (when invite (get @rooms invite))]\n (set! (.-hidden el) (not open))\n (set! (.-innerHTML ($ \"work-name\"))\n (if (:kind @work)\n (str (case (:kind @work) :room \"Room\" :solo \"Solo\" \"Local\") \" · <b>\" (esc (or (:name @work) \"\")) \"</b>\")\n \"No work open\"))\n (when open\n ;; the lists update live: whatever you are typing in the forms is kept\n (let [keep (into {} (for [k [\"new-solo\" \"new-room\" \"relay-url\"] :let [i ($ k)] :when i] [k (.-value i)]))\n keep-ex (into {} (for [k [\"new-solo-ex\" \"new-room-ex\"] :let [i ($ k)] :when i] [k (.-checked i)]))\n focus (.. js/document -activeElement -id)]\n (js/setTimeout\n (fn []\n (doseq [[k v] keep] (when-let [i ($ k)] (set! (.-value i) v)))\n (doseq [[k v] keep-ex] (when-let [i ($ k)] (set! (.-checked i) v)))\n (when (and (seq focus) ($ focus) (contains? keep focus)) (.focus ($ focus))))\n 0))\n (set! (.-innerHTML ($ \"mgr-body\"))\n (str\n (when (nil? (:kind @work)) (welcome))\n (when busy (str \"<p class=\\\"mgr-busy\\\">\" (esc busy) \"</p>\"))\n (cond\n connecting? \"<p class=\\\"mgr-note\\\">Connecting…</p>\"\n (not db?)\n (str \"<p class=\\\"mgr-note\\\">This view has no database (outside claude.ai or not signed in): you can only work locally, without saving.</p>\"\n \"<button class=\\\"act primary\\\" data-act=\\\"local\\\">Start locally</button> \"\n \"<button class=\\\"act\\\" data-act=\\\"open-file\\\" title=\\\"A work saved as a .kairotic file: it opens as a local work\\\">Open a file…</button>\")\n :else\n (str\n (when inv\n (str \"<div class=\\\"invite\\\">You have been invited to the room <b>\" (esc (:name inv)) \"</b>.\"\n \" <button class=\\\"act primary\\\" data-act=\\\"open\\\" data-kind=\\\"room\\\" data-id=\\\"\" (esc (:id inv)) \"\\\">Enter</button></div>\"))\n (when-not can-write\n \"<p class=\\\"mgr-note\\\">You can enter the rooms and walk through their history, but not create or change works: your access to this artifact is read only.</p>\")\n (relay-section (:relays @mgr))\n \"<div class=\\\"mgr-cols\\\">\"\n (if (pages?)\n \"<section class=\\\"mgr-col\\\"><h3>Solo</h3><p class=\\\"mgr-hint\\\">Only you see these works: they are encrypted with a key that stays in this browser.</p>\"\n \"<section class=\\\"mgr-col\\\"><h3>Solo</h3><p class=\\\"mgr-hint\\\">Only you see these works, not even whoever shares the artifact.</p>\")\n (if (seq solo-list)\n (str \"<ul class=\\\"items\\\">\" (apply str (map (fn [o] (item-html :solo o)) solo-list)) \"</ul>\")\n \"<p class=\\\"mgr-empty\\\">You have no solo works yet.</p>\")\n (when (and can-write (uid))\n \"<form class=\\\"new\\\" data-kind=\\\"solo\\\"><input id=\\\"new-solo\\\" placeholder=\\\"Name of the work\\\" maxlength=\\\"60\\\" required><label class=\\\"opt\\\"><input type=\\\"checkbox\\\" id=\\\"new-solo-ex\\\"> with the example work</label><button class=\\\"act primary\\\">Create</button></form>\")\n \"</section>\"\n (if (pages?)\n \"<section class=\\\"mgr-col\\\"><h3>Shared rooms</h3><p class=\\\"mgr-hint\\\">Anyone using this site with the same relay sees them and can enter.</p>\"\n \"<section class=\\\"mgr-col\\\"><h3>Shared rooms</h3><p class=\\\"mgr-hint\\\">Anyone with access to this artifact sees them and can enter.</p>\")\n (if (seq room-list)\n (str \"<ul class=\\\"items\\\">\" (apply str (map (fn [s] (item-html :room s)) room-list)) \"</ul>\")\n \"<p class=\\\"mgr-empty\\\">No rooms yet.</p>\")\n (when can-write\n \"<form class=\\\"new\\\" data-kind=\\\"room\\\"><input id=\\\"new-room\\\" placeholder=\\\"Name of the room\\\" maxlength=\\\"60\\\" required><label class=\\\"opt\\\"><input type=\\\"checkbox\\\" id=\\\"new-room-ex\\\"> with the example work</label><button class=\\\"act primary\\\">Create</button></form>\")\n \"</section></div>\"\n \"<p class=\\\"mgr-foot\\\"><button class=\\\"act\\\" data-act=\\\"local\\\">Try locally, without saving</button> <button class=\\\"act\\\" data-act=\\\"learn\\\" title=\\\"Tutorials and the help of every component\\\">Learn: tutorials and help</button>\"\n ;; a work as a file (#149): open one as a new solo work, or keep the one open\n \" <button class=\\\"act\\\" data-act=\\\"open-file\\\" title=\\\"A work saved as a .kairotic file: it opens as a new solo work, with its whole history\\\">Open a file…</button>\"\n (when (:kind @work) \" <button class=\\\"act\\\" data-act=\\\"export-file\\\" title=\\\"The open work as a .kairotic file: every line, its whole history and the sounds recorded\\\">Download this work</button>\")\n \"</p>\")))))))\n\n(add-watch mgr ::render (fn [_ _ _ _] (render-manager!)))\n(add-watch rooms ::render (fn [_ _ _ _] (render-manager!)))\n(add-watch solo-works ::render (fn [_ _ _ _] (render-manager!)))\n(add-watch lobby-peers ::render (fn [_ _ _ _] (when (:open @mgr) (render-manager!))))\n(add-watch work ::render (fn [_ _ _ _] (render-manager!)))\n\n(.addEventListener ($ \"mgr-body\") \"click\"\n (fn [e]\n (when-let [b (.closest (.-target e) \"[data-act]\")]\n (let [act (.. b -dataset -act)\n kind (keyword (.. b -dataset -kind))\n id (.. b -dataset -id)\n item (get (if (= kind :room) @rooms @solo-works) id)]\n (case act\n \"open\" (if (and (= kind (:kind @work)) (= id (:id @work)))\n (hide-manager!)\n (open-work! kind id (:name item)))\n \"copy\" (let [to (keyword (.. b -dataset -to))]\n (copy-work! kind id to (str (:name item) (if (= to :room) \" (shared)\" \" (my copy)\"))))\n \"delete\" (if (= (:confirm @mgr) [(name kind) id])\n (delete-work! kind id)\n (do (swap! mgr assoc :confirm [(name kind) id])\n (js/setTimeout (fn [] (when (= (:confirm @mgr) [(name kind) id]) (swap! mgr assoc :confirm nil))) 4000)))\n \"local\" (open-work! :local \"local\" \"Local\")\n \"link\" (let [u (room-link id)]\n (-> (js/Promise.resolve)\n (.then (fn [_] (.writeText (.-clipboard js/navigator) u)))\n (.then (fn [_] (set! (.-textContent b) \"Copied\")))\n (.catch (fn [_] (repl-print! \"out\" (esc (str \"; \" u)))\n (set! (.-textContent b) \"In the REPL\")))\n (.then (fn [_] (js/setTimeout (fn [] (render-manager!)) 1500)))))\n \"relay-test\" (let [u (normalize-relay (.-value ($ \"relay-url\")))]\n (if-let [why (relay-problem u)]\n (reset! relay-test {:url (str/trim (.-value ($ \"relay-url\"))) :state :fail :msg why})\n (test-relay! u)))\n \"relay-site\" (choose-relays! \"none\")\n \"relay-off\" (choose-relays! \"off\")\n \"relay-drop\" (let [u (.. b -dataset -url)]\n (choose-relays! (let [left (remove #{u} (current-relays))] (if (seq left) (str/join \",\" left) \"off\"))))\n \"learn\" (do (open-work! :local \"local\" \"Local\") (show-help! nil))\n \"guide\" (do (open-work! :local \"local\" \"Local\") (docs \"guide\"))\n \"feedback\" (do (when-not (:kind @work) (open-work! :local \"local\" \"Local\")) (swap! mgr assoc :open false) (.click ($ \"tab-feedback\")))\n \"open-file\" (open-work-file!)\n \"export-file\" (gesture! \"(export-work)\")\n nil)))))\n\n(.addEventListener ($ \"mgr-body\") \"submit\"\n (fn [e]\n (.preventDefault e)\n (let [f (.-target e)\n kind (keyword (.. f -dataset -kind))]\n (if (= kind :relay)\n ;; use this relay (only it): the page reloads syncing through it\n (let [typed (str/trim (.-value ($ \"relay-url\"))) u (normalize-relay typed)]\n (if-let [why (relay-problem u)]\n (reset! relay-test {:url typed :state :fail :msg why})\n (choose-relays! u)))\n (let [nm (str/trim (.-value ($ (str \"new-\" (name kind)))))\n ex (.-checked ($ (str \"new-\" (name kind) \"-ex\")))]\n (when (seq nm) (create-work! kind nm ex)))))))\n\n;; the relay section: open or closed stays as it was when the manager is drawn again, and while it is\n;; open its relays' state is looked at every two seconds\n(.addEventListener ($ \"mgr-body\") \"toggle\"\n (fn [e] (let [t (.-target e)]\n (when (and (= \"relays\" (.-id t)) (not= (boolean (.-open t)) (:relays @mgr)))\n (swap! mgr assoc :relays (boolean (.-open t))))))\n true)\n(add-watch relay-status ::render (fn [_ _ _ _] (when (:open @mgr) (render-manager!))))\n(add-watch relay-test ::render (fn [_ _ _ _] (when (:open @mgr) (render-manager!))))\n(defonce relay-timer\n (js/setInterval (fn [] (when (and (:open @mgr) (pages?)) (refresh-relay-status!))) 2000))\n\n(.addEventListener ($ \"open-manager\") \"click\" (fn [_] (show-manager!)))\n(.addEventListener ($ \"mgr-close\") \"click\" (fn [_] (hide-manager!)))\n(.addEventListener js/document \"keydown\"\n (fn [e] (when (and (= (.-key e) \"Escape\") (:open @mgr) (not (:merge-pick @ui))) (hide-manager!))))\n\n;; when a compilation finishes, the status, ports and parameters of code boxes change\n(swap! cbox/listeners assoc :page (fn [] (render-all!)))\n\n;; ───────────────────────── transport ─────────────────────────\n\n(.addEventListener ($ \"play\") \"click\" (fn [_] (gesture! \"(play)\")))\n(.addEventListener ($ \"stop\") \"click\" (fn [_] (gesture! \"(stop)\")))\n\n(-> (.-kairoticVerovio js/window)\n (.then (fn [tk]\n (reset! vrv tk)\n (reset! vrv-status :ok)\n (reset! score-cache {})\n (render-scene (current))))\n (.catch (fn [_]\n (reset! vrv-status :error)\n (render-scene (current)))))\n","page/09-learn.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 10 of 12: learn\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── learning: help and lessons ─────────────────────────\n;; The Help tab shows what each class does, port by port (its :help, or kairotic.help), with a help\n;; patch. A lesson (a tutorial, or a help patch) opens as a local work built step by step: each step\n;; leaves a point in the history, the lesson bar shows the note of the step you are at, ◀ ▶ travel\n;; between them, and changing something at any step simply starts a branch of your own.\n\n(defonce lang (atom (let [saved (try (.getItem js/localStorage \"kairotic.lang\") (catch :default _ nil))]\n (cond (#{\"es\" \"en\"} saved) (keyword saved)\n (str/starts-with? (str (.-language js/navigator)) \"es\") :es\n :else :en))))\n\n(defn tr \"A text in the chosen language (or the other one).\" [m]\n (cond (string? m) m\n (map? m) (or (not-empty (get m @lang)) (not-empty (get m :en)) (not-empty (get m :es)) \"\")\n :else \"\"))\n\n(defn es? [] (= @lang :es))\n\n(defn rich\n \"Note text to HTML: paragraphs (blank lines), **bold**, `code` (a click puts it in the REPL).\"\n [t]\n (->> (str/split (str t) #\"\\n\\s*\\n\")\n (remove str/blank?)\n (map (fn [para]\n (str \"<p>\"\n (-> (esc (str/trim para))\n (str/replace #\"\\*\\*([^*]+)\\*\\*\" \"<b>$1</b>\")\n (str/replace #\"`([^`]+)`\"\n (fn [[_ c]] (str \"<code class=\\\"run\\\" data-code=\\\"\" c \"\\\" title=\\\"Click: into the REPL\\\">\" c \"</code>\"))))\n \"</p>\")))\n (apply str)))\n\n(defn select-tab! [tab] (when-let [t ($ (str \"tab-\" tab))] (.click t)))\n\n(defn to-repl! [code]\n (set-repl-text! code) (focus-repl!))\n\n;; ───── tutorials (kairotic/tutorials.mjs, built from docs/tutorials) ─────\n\n(def tracks [[\"patch-code\" {:en \"Patch ⇄ code\" :es \"Patch ⇄ código\"}]\n [\"theory\" {:en \"Notation and theory\" :es \"Notación y teoría\"}]\n [\"composition\" {:en \"Composition and CAC\" :es \"Composición y CAC\"}]\n [\"dsp\" {:en \"Electroacoustics and DSP\" :es \"Electroacústica y DSP\"}]\n [\"faust\" {:en \"Faust\" :es \"Faust\"}]])\n\n(defonce tutorials (atom nil)) ; nil · :loading · [{:id :track :order :title :steps} …]\n\n(defn load-tutorials! []\n (when (nil? @tutorials)\n (reset! tutorials :loading)\n (-> ((.-kairoticImport js/window) (str \"kairotic/tutorials.mjs?v=\" (js/Date.now)))\n (.then (fn [m] (reset! tutorials (vec (js->clj (.-tutorials m) :keywordize-keys true)))))\n (.catch (fn [e] (reset! tutorials [])\n (repl-print! \"err\" (esc (str \"Could not read the tutorials: \" (or (.-message e) e)))))))))\n\n;; ───── the Help tab ─────\n\n(defonce help-cls (atom nil)) ; nil = the index\n\n(defn help-ports [label n names]\n (when (pos? n)\n (str \"<h4>\" label \"</h4>\"\n (if (= n (count names))\n (str \"<ol start=\\\"0\\\">\" (apply str (for [x names] (str \"<li>\" (esc x) \"</li>\"))) \"</ol>\")\n (str \"<p>\" n (if (= label \"Inlets\") \" (numbered from 0, left to right)\" \" (numbered from 0)\")\n (when (seq names) (str \": \" (esc (str/join \" · \" names)))) \"</p>\")))))\n\n(defn help-word [w]\n (if (str/starts-with? (str w) \"(\")\n (str \"<code class=\\\"run\\\" data-code=\\\"\" (esc w) \"\\\">\" (esc w) \"</code>\")\n (str \"<code>\" (esc w) \"</code>\")))\n\n(defn help-refs\n \"Links to the outer documentation of a class ([[label url] …]: clojuredocs.org and clojure.org for the\n boxes of clojure.core), opened in a new tab; empty when it has none.\"\n [refs]\n (when (seq refs)\n (str \"<p class=\\\"refs\\\"><small>\" (if (es?) \"Referencia: \" \"Reference: \")\n (str/join \" · \" (for [[label url] refs]\n (str \"<a href=\\\"\" (esc url) \"\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\">\" (esc label) \"</a>\")))\n \"</small></p>\")))\n\n(defn help-page [cls]\n (let [d (comp/lookup cls) h (hlp/of cls)\n doc (or (:doc d) (:doc h)) usage (or (:usage d) (:usage h))\n [ins outs] (if d (try (io cls) (catch :default _ [0 0])) [(count (:inlets h)) (count (:outlets h))])\n spec (when d (spec-of d))]\n (str \"<p class=\\\"back\\\"><a href=\\\"#\\\" data-help-index=\\\"1\\\">◀ Help</a></p>\"\n \"<h3>\" (esc cls)\n (when-let [p (:package h)] (str \"<span class=\\\"pkg\\\" title=\\\"Writing it in a box brings this package into the work\\\">\" (esc p) \"</span>\"))\n (when (= :work (:origin d)) \"<span class=\\\"pkg\\\">defined in this work</span>\")\n \"</h3>\"\n (when usage (str \"<div class=\\\"usage\\\">\" (esc usage) \"</div>\"))\n ;; an introduction in short paragraphs (:about), with everything it does folded below it; or the doc\n (if-let [about (:about h)]\n (str \"<div class=\\\"about\\\">\" (rich about) \"</div>\"\n (when doc (str \"<details class=\\\"all-doc\\\"><summary>Everything it does</summary><p>\" (esc doc) \"</p></details>\")))\n (when doc (str \"<p>\" (esc doc) \"</p>\")))\n (help-refs (or (:ref d) (:ref h)))\n (when (and (nil? d) (empty? h)) \"<p>There is no class with this name.</p>\")\n (when (or spec (seq (:args h)))\n ;; what each argument is, and (from the help's :args, [[:k \"what it does\"] …]) what it does; without the\n ;; component loaded, its arguments as the help lists them\n (str \"<h4>Arguments</h4><table>\"\n (apply str (for [[a v] (or spec (map (fn [[a]] [a nil]) (:args h))) :let [what (get (into {} (:args h)) a)]]\n (str \"<tr><td>\" (esc (name a)) \"</td><td>\"\n (esc (cond (nil? v) \"\"\n (boolean? v) \"a flag: on when its name is written\"\n (keyword? v) (str \"a number (by default, the value of \" (name v) \")\")\n (number? v) (str \"a number, \" (cv/fmt v) \" by default\")\n :else \"a word\"))\n \"</td>\" (when (seq (:args h)) (str \"<td>\" (when what (esc what)) \"</td>\")) \"</tr>\")))\n \"</table>\"))\n (help-ports \"Inlets\" ins (:inlets h))\n (help-ports \"Outlets\" outs (:outlets h))\n (when (seq (:messages h))\n (str \"<h4>Messages and gestures</h4><table>\"\n (apply str (for [[w x] (:messages h)] (str \"<tr><td>\" (help-word w) \"</td><td>\" (esc x) \"</td></tr>\")))\n \"</table>\"))\n (when-let [steps (seq (hlp/patch-steps cls))]\n (str \"<h4>Help patch</h4><p><button class=\\\"act primary\\\" data-help-open=\\\"\" (esc cls) \"\\\">Open the help patch</button> \"\n \"<small>a local work you can play and change; Close (in the lesson bar) brings back what you had open</small></p>\"\n (when (seq (:try h)) (str \"<div class=\\\"try\\\">\" (esc (:try h)) \"</div>\"))\n (when (> (count steps) 1)\n (str \"<p><small>\" (count steps) \" steps, each one a use of \" (esc cls) \" (◀ ▶ in the lesson bar):</small></p>\"\n \"<ol class=\\\"help-steps\\\">\"\n (apply str (map-indexed (fn [i st] (str \"<li><a href=\\\"#\\\" data-help-open=\\\"\" (esc cls) \"\\\" data-help-step=\\\"\" i \"\\\">\"\n (esc (tr (:title st))) \"</a></li>\"))\n steps))\n \"</ol>\"))))\n (when (and d (empty? h) (#{:work :user} (:origin d)))\n \"<p><small>No help written yet: a component can carry its own, as <code>:help {:inlets […] :outlets […] :example \\\"…\\\"}</code> in its definition.</small></p>\")\n (when (seq (:see h))\n (str \"<h4>See also</h4><div class=\\\"chips\\\">\"\n (apply str (for [c (:see h)] (str \"<span class=\\\"chip\\\" data-help=\\\"\" (esc c) \"\\\">\" (esc c) \"</span>\")))\n \"</div>\")))))\n\n(declare docs-index)\n\n(defn help-index []\n (let [ts @tutorials]\n (str \"<input class=\\\"help-find\\\" id=\\\"help-find\\\" list=\\\"help-classes\\\" placeholder=\\\"\"\n (if (es?) \"Una clase: osc~, ramp, reader~…\" \"A class: osc~, ramp, reader~…\") \"\\\" spellcheck=\\\"false\\\">\"\n \"<datalist id=\\\"help-classes\\\">\" (apply str (for [c (hlp/known)] (str \"<option value=\\\"\" (esc c) \"\\\">\"))) \"</datalist>\"\n \"<p><small>\" (if (es?) \"Selecciona una caja y pulsa <b>?</b> para ver aquí su ayuda.\" \"Select a box and press <b>?</b> to see its help here.\") \"</small></p>\"\n (docs-index)\n \"<h4>\" (if (es?) \"Tutoriales\" \"Tutorials\") \"</h4>\"\n (cond\n (= :loading ts) \"<p>…</p>\"\n (empty? ts) \"<p><small>None.</small></p>\"\n :else\n (apply str\n (for [[tk tname] tracks\n :let [ls (sort-by :order (filter (fn [t] (= tk (:track t))) ts))]\n :when (seq ls)]\n (str \"<p><b>\" (esc (tr tname)) \"</b></p><ul class=\\\"tuts\\\">\"\n (apply str (for [t ls]\n (str \"<li class=\\\"tut\\\" data-tut=\\\"\" (esc (:id t)) \"\\\"><span>\" (esc (tr (:title t))) \"</span>\"\n \"<small>\" (count (:steps t)) (if (es?) \" pasos\" \" steps\") \"</small></li>\")))\n \"</ul>\"))))\n \"<h4>\" (if (es?) \"Componentes\" \"Components\") \"</h4><div class=\\\"chips\\\">\"\n (apply str (for [c (hlp/known)] (str \"<span class=\\\"chip\\\" data-help=\\\"\" (esc c) \"\\\">\" (esc c) \"</span>\")))\n \"</div>\")))\n\n;; ───── the documentation in the Help tab (kairotic/docs.mjs, built from docs/) ─────\n\n(declare link-code open-link-work! render-help! show-help!)\n\n(defonce doc-pages (atom nil)) ; nil · :loading · {\"id\" {\"en\" text \"es\" text}}\n(defonce help-doc (atom nil)) ; the page of the documentation on screen, or nil\n\n(def doc-groups\n [[{:en \"Start here\" :es \"Para empezar\"} [\"guide\" \"concepts\"]]\n [{:en \"Topics\" :es \"Temas\"} [\"mt\" \"flow\" \"ask\" \"embed\" \"pages\"]]\n [{:en \"Extending\" :es \"Ampliarlo\"} [\"writing-a-component\"]]\n [{:en \"Reference\" :es \"Referencia\"} [\"reference\"]]])\n\n(defn load-docs! []\n (when (nil? @doc-pages)\n (reset! doc-pages :loading)\n (-> ((.-kairoticImport js/window) (str \"kairotic/docs.mjs?v=\" (js/Date.now)))\n (.then (fn [m] (reset! doc-pages (get (js->clj m) \"pages\"))))\n (.catch (fn [e] (reset! doc-pages {})\n (repl-print! \"err\" (esc (str \"Could not read the documentation: \" (or (.-message e) e)))))))))\n\n(defn doc-text [id]\n (let [p (when (map? @doc-pages) (get @doc-pages id))]\n (or (when (es?) (get p \"es\")) (get p \"en\"))))\n\n(defn doc-title [id]\n (or (some->> (doc-text id) (re-find #\"(?m)^# (.+)$\") second) id))\n\n(def docs-base \"https://github.com/bonuoq/kairotic/blob/main/docs/\")\n\n(defn md-link\n \"A link of the documentation: to another page (shown here, in its language), to the web (a new tab),\n or to a file of the repository (on GitHub).\"\n [label href]\n (let [[_ id es] (re-matches #\"(?:\\./)?(?:tutorials/)?([A-Za-z-]+?)(\\.es)?\\.md(?:#.*)?\" href)]\n (cond\n (and id (contains? (set (mapcat second doc-groups)) id))\n (str \"<a href=\\\"#\\\" data-doc=\\\"\" id \"\\\" data-lang=\\\"\" (if es \"es\" \"en\") \"\\\">\" label \"</a>\")\n (and id (= id \"README\")) (str \"<a href=\\\"#\\\" data-help-index=\\\"1\\\">\" label \"</a>\")\n (str/starts-with? href \"#\") label\n :else (let [u (if (re-find #\"^https?:\" href) href (.-href (js/URL. href docs-base)))]\n (str \"<a href=\\\"\" u \"\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\">\" label \"</a>\")))))\n\n(defn md-inline\n \"Inline Markdown: `code`, [links](…), **bold**, *italic*.\"\n [s]\n (let [parts (str/split (str s) #\"`\" -1)]\n (apply str\n (map-indexed\n (fn [i p]\n (if (odd? i)\n (str \"<code>\" (esc p) \"</code>\")\n (-> (esc p)\n (str/replace #\"\\[([^\\]]+)\\]\\(([^)\\s]+)\\)\" (fn [[_ l h]] (md-link l (str/replace h \"&\" \"&\"))))\n (str/replace #\"\\*\\*([^*]+)\\*\\*\" \"<b>$1</b>\")\n (str/replace #\"(^|[\\s(])\\*([^*\\s][^*]*)\\*\" \"$1<i>$2</i>\"))))\n parts))))\n\n(defn md-code [lang code]\n (let [patch? (and (#{\"clojure\" \"clj\" \"\"} lang) (str/includes? code \"(box \")\n (try (link-code code) true (catch :default _ false)))]\n (str \"<pre>\" (esc code) \"</pre>\"\n (when patch?\n (str \"<p class=\\\"doc-try\\\"><button class=\\\"act\\\" data-doc-patch=\\\"\" (esc code) \"\\\">\"\n (if (es?) \"Abrir como patch local\" \"Open as a local patch\") \"</button></p>\")))))\n\n(defn md-block-start? [l]\n (or (str/starts-with? l \"```\") (re-matches #\"#{1,6} .*\" l) (str/starts-with? l \"|\") (str/starts-with? l \"> \")\n (re-matches #\"([-*]|\\d+\\.) .*\" l)))\n\n(defn md->html\n \"The Markdown of docs/ as HTML: headings, paragraphs, lists, tables, quotes, code blocks.\"\n [text]\n (let [ls (vec (str/split-lines (str text))) n (count ls)\n take-while-from (fn [i pred] (loop [j i] (if (and (< j n) (pred (nth ls j))) (recur (inc j)) j)))]\n (loop [i 0 out []]\n (if (>= i n)\n (apply str out)\n (let [l (nth ls i)]\n (cond\n (str/starts-with? l \"```\")\n (let [j (take-while-from (inc i) #(not (str/starts-with? % \"```\")))]\n (recur (inc j) (conj out (md-code (str/trim (clojure.core/subs l 3)) (str/join \"\\n\" (subvec ls (inc i) (min j n)))))))\n (str/blank? l) (recur (inc i) out)\n (re-matches #\"#{1,6} .*\" l)\n (let [k (count (re-find #\"^#+\" l))]\n (recur (inc i) (conj out (str \"<h\" (min 6 (inc k)) \" class=\\\"dh\\\">\" (md-inline (str/trim (clojure.core/subs l k))) \"</h\" (min 6 (inc k)) \">\"))))\n (str/starts-with? l \"|\")\n (let [j (take-while-from i #(str/starts-with? % \"|\"))\n rows (remove #(re-matches #\"\\|[\\s:|-]+\\|?\" %) (subvec ls i j))\n cells (fn [r] (map str/trim (butlast (rest (str/split r #\"\\|\" -1)))))]\n (recur j (conj out (str \"<table class=\\\"dt\\\">\"\n (apply str (map-indexed (fn [k r] (str \"<tr>\" (apply str (for [c (cells r)] (str (if (zero? k) \"<th>\" \"<td>\") (md-inline c) (if (zero? k) \"</th>\" \"</td>\")))) \"</tr>\")) rows))\n \"</table>\"))))\n (str/starts-with? l \"> \")\n (let [j (take-while-from i #(str/starts-with? % \">\"))]\n (recur j (conj out (str \"<blockquote>\" (md-inline (str/join \" \" (map #(str/trim (clojure.core/subs % 1)) (subvec ls i j)))) \"</blockquote>\"))))\n (re-matches #\"([-*]|\\d+\\.) .*\" l)\n (let [ordered (re-matches #\"\\d+\\. .*\" l)\n j (take-while-from i #(or (re-matches #\"\\s*([-*]|\\d+\\.) .*\" %) (re-matches #\"\\s+\\S.*\" %)))\n items (reduce (fn [acc x]\n (if-let [[_ t] (re-matches #\"\\s*(?:[-*]|\\d+\\.) (.*)\" x)]\n (conj acc t)\n (conj (pop acc) (str (peek acc) \" \" (str/trim x)))))\n [] (subvec ls i j))]\n (recur j (conj out (str (if ordered \"<ol>\" \"<ul>\") (apply str (for [t items] (str \"<li>\" (md-inline t) \"</li>\"))) (if ordered \"</ol>\" \"</ul>\")))))\n :else\n (let [j (take-while-from (inc i) #(not (or (str/blank? %) (md-block-start? %))))]\n (recur j (conj out (str \"<p>\" (md-inline (str/join \" \" (subvec ls i j))) \"</p>\"))))))))))\n\n(defn doc-page [id]\n (str \"<p class=\\\"back\\\"><a href=\\\"#\\\" data-help-index=\\\"1\\\">◀ Help</a></p>\"\n (cond\n (= :loading @doc-pages) \"<p>…</p>\"\n (doc-text id) (str \"<div class=\\\"doc\\\">\" (md->html (doc-text id)) \"</div>\")\n :else (str \"<p>\" (esc (str \"No page \" id)) \"</p>\"))))\n\n(defn docs-index []\n (str \"<h4>\" (if (es?) \"Documentación\" \"Documentation\") \"</h4>\"\n (if (map? @doc-pages)\n (apply str (for [[g ids] doc-groups]\n (str \"<p><b>\" (esc (tr g)) \"</b></p><ul class=\\\"tuts\\\">\"\n (apply str (for [id ids :when (doc-text id)]\n (str \"<li class=\\\"tut\\\" data-doc=\\\"\" id \"\\\"><span>\" (esc (doc-title id)) \"</span></li>\")))\n \"</ul>\")))\n \"<p>…</p>\")))\n\n(defn show-doc!\n \"Opens a page of the documentation in the Help tab.\"\n [id]\n (load-docs!)\n (reset! help-cls nil)\n (reset! help-doc id)\n (render-help!)\n (select-tab! \"help\")\n (set! (.-scrollTop ($ \"help-view\")) 0))\n\n(defn docs\n \"The documentation in the Help tab: (docs) its index, (docs \\\"guide\\\") a page — guide, concepts, mt,\n flow, ask, embed, pages, writing-a-component, reference.\"\n ([] (show-help! nil) (mapv first (mapcat (fn [[_ ids]] (map vector ids)) doc-groups)))\n ([id] (show-doc! (str id)) (str id)))\n\n(add-watch doc-pages ::help (fn [_ _ _ _] (render-help!)))\n\n(defn reference-md\n \"The reference of every class with a help page, as Markdown (docs/reference.md is made with it):\n (reference-md).\"\n []\n (let [md-ports (fn [label n names]\n (when (pos? n)\n (str \"**\" label \"** \" (if (= n (count names))\n (str \"\\n\" (apply str (map-indexed (fn [i x] (str \"\\n\" i \". \" x)) names)) \"\\n\")\n (str n (when (seq names) (str \": \" (str/join \" · \" names))) \"\\n\"))\n \"\\n\")))\n page (fn [cls]\n (let [d (comp/lookup cls) h (hlp/of cls)\n doc (or (:doc d) (:doc h)) usage (or (:usage d) (:usage h))\n [ins outs] (if d (try (io cls) (catch :default _ [0 0])) [(count (:inlets h)) (count (:outlets h))])]\n (when (and doc (not (str/starts-with? (str doc) \"Kairotic class with no semantics\")))\n (str \"### \" cls (when-let [p (:package h)] (str \" · `\" p \"`\")) \"\\n\\n\"\n (when usage (str \"`\" usage \"`\\n\\n\"))\n (when-let [a (:about h)] (str a \"\\n\\n\"))\n doc \"\\n\\n\"\n (when (seq (:args h))\n (str \"**Arguments**\\n\\n\"\n (apply str (for [[a v] (if d (spec-of d) (map (fn [[a]] [a nil]) (:args h))) :let [what (get (into {} (:args h)) a)]]\n (str \"- `\" (name a) \"`\"\n (cond (boolean? v) \" (a flag)\" (number? v) (str \" (\" (cv/fmt v) \")\") :else \"\")\n (when what (str \": \" what)) \"\\n\")))\n \"\\n\"))\n (md-ports \"Inlets\" ins (:inlets h))\n (md-ports \"Outlets\" outs (:outlets h))\n (when (seq (:messages h))\n (str \"**Messages and gestures**\\n\\n\" (apply str (for [[w x] (:messages h)] (str \"- `\" (if (string? w) w (pr-str w)) \"`: \" x \"\\n\"))) \"\\n\"))\n (when-let [t (:try h)] (str \"**Try:** \" t \"\\n\\n\"))\n (when-let [e (:example h)] (str \"```clojure\\n\" (str/trim e) \"\\n```\\n\\n\"))\n (apply str (for [st (:steps h)]\n (str \"**\" (tr (:title st)) \"**\" (when (seq (tr (:note st))) (str \" — \" (tr (:note st)))) \"\\n\\n\"\n (when (seq (tr (:try st))) (str \"*Try:* \" (tr (:try st)) \"\\n\\n\"))\n \"```clojure\\n\" (str/trim (:example st)) \"\\n```\\n\\n\")))\n (when (seq (:see h)) (str \"See also: \" (str/join \", \" (map #(str \"`\" % \"`\") (:see h))) \"\\n\\n\"))\n (when-let [refs (seq (or (:ref d) (:ref h)))]\n (str \"Reference: \" (str/join \" · \" (for [[label url] refs] (str \"[\" label \"](\" url \")\"))) \"\\n\\n\"))))))]\n (str \"# Class reference\\n\\n\"\n \"*Made from the help of Kairotic \" version \" (the Help tab shows the same, and the help of classes a work defines). \"\n \"Generated: do not edit by hand — `(reference-md)` in the REPL writes it.*\\n\\n\"\n (str/join \"\" (keep page (hlp/known))))))\n\n(defn render-help! []\n (when-let [el ($ \"help-view\")]\n (set! (.-innerHTML el) (cond @help-doc (doc-page @help-doc)\n @help-cls (help-page @help-cls)\n :else (help-index)))))\n\n(defn show-help!\n \"Opens the Help tab: the page of a class, or the index (nil).\"\n [cls]\n (load-tutorials!)\n (load-docs!)\n (reset! help-doc nil)\n (reset! help-cls (when (seq cls) cls))\n (render-help!)\n (select-tab! \"help\")\n (set! (.-scrollTop ($ \"help-view\")) 0))\n\n(defn refresh-help!\n \"Draws the Help tab as it is (the index, or the page it was on), loading the tutorials if needed.\"\n [] (load-tutorials!) (load-docs!) (render-help!))\n\n(add-watch tutorials ::help (fn [_ _ _ _] (render-help!)))\n\n;; ───── lessons ─────\n\n(defonce lesson-back (atom nil)) ; what was open before the first lesson\n\n(defn render-lesson! []\n (let [el ($ \"lesson\") l @lesson]\n (set! (.-hidden el) (nil? l))\n (when l\n (let [steps (:steps l) n (count steps) i (min (:at l) (dec n)) st (nth steps i nil)\n here (norm (:pos @world))\n last-pos (some :pos (reverse steps))\n away? (and here last-pos (not (some (fn [s] (= here (:pos s))) steps)) (not (reaches? here last-pos)))]\n (set! (.-textContent ($ \"lesson-title\")) (tr (:title l)))\n (set! (.-textContent ($ \"lesson-n\")) (str (inc i) \" / \" n))\n (set! (.-disabled ($ \"lesson-prev\")) (zero? i))\n (set! (.-disabled ($ \"lesson-next\")) (>= i (dec n)))\n (set! (.-textContent ($ \"lesson-back\")) (if (es?) \"Cerrar\" \"Close\"))\n (doseq [b (array-seq (.querySelectorAll el \"[data-lang]\"))]\n (.setAttribute b \"aria-pressed\" (str (= (name @lang) (.. b -dataset -lang)))))\n (set! (.-innerHTML ($ \"lesson-note\"))\n (str (let [t (tr (:title st))] (when (seq t) (str \"<p class=\\\"step-t\\\">\" (esc t) \"</p>\")))\n (rich (tr (:note st)))\n (let [t (tr (:try st))]\n (when (seq t) (str \"<div class=\\\"try\\\">\" (rich (str (if (es?) \"**Prueba:** \" \"**Try:** \") t)) \"</div>\")))\n (when away?\n (str \"<p class=\\\"away\\\">\"\n (if (es?) \"Estás en una rama tuya: la lección sigue en la historia. ◀ ▶ te devuelven a ella.\"\n \"You are on a branch of your own: the lesson is still in the history. ◀ ▶ take you back to it.\")\n \"</p>\"))))))))\n\n(defn lesson-sync!\n \"After moving in the history by other means, the step you are at.\"\n []\n (when-let [l @lesson]\n (let [here (norm (:pos @world)) steps (:steps l)]\n (when-not (= (:pos (nth steps (:at l) nil)) here)\n (let [i (last (keep-indexed (fn [i s] (when (and (:pos s) here (reaches? (:pos s) here)) i)) steps))]\n (swap! lesson assoc :at (or i 0)))))\n (render-lesson!)))\n\n(add-watch world ::lesson (fn [_ _ o n] (when (and @lesson (not= (:pos o) (:pos n))) (lesson-sync!))))\n\n(defn lesson-go! [i]\n (when-let [l @lesson]\n (let [i (max 0 (min (dec (count (:steps l))) i)) p (:pos (nth (:steps l) i))]\n (swap! lesson assoc :at i)\n (if p\n (goto (first p) (second p))\n (swap! world assoc :pos nil :auto false :prev-pos nil))\n (swap! lesson assoc :at i)\n (render-lesson!))))\n\n(def box-class-re #\"\\(box\\s+(?::\\S+\\s+)?\\\"([^\\\"\\s]+)\")\n\n(defn lesson-definitions\n \"Promise of [[name classes source] …]: the official packages a lesson's boxes\n need and the work does not define yet, fetched before the lesson is built (so that their\n definitions are part of its history, in order, and not late arrivals on a branch of their own).\"\n [l]\n (let [ks (distinct (for [st (:steps l) c (:code st) [_ k] (re-seq box-class-re c)] k))\n ;; a lesson starts from an empty history: every class of a package is needed, even if the\n ;; work open before it had defined it\n pkgs (distinct (keep (fn [k] (first (lib/package-of k))) ks))]\n (if (empty? pkgs)\n (js/Promise.resolve [])\n (-> (js/Promise.all\n (into-array\n (for [p pkgs] (.then (lib/import-package p) (fn [[m origin]] [p (set (map :class (:components m))) (lib/package-source m origin)])))))\n (.then (fn [arr] (vec arr)))))))\n\n(declare build-lesson!)\n\n(defn compiled-components\n \"Promise: the sources of these component boxes compiled (or failed), so that the classes they define\n can be registered at once while a lesson is built, and its next gestures (the code of a pbind) find them.\"\n [srcs]\n (js/Promise.\n (fn [res _]\n (let [t0 (js/Date.now)]\n (letfn [(check []\n (if (or (every? #(not= :compiling (:status (cbox/compiled \"component\" %))) srcs)\n (> (- (js/Date.now) t0) 15000))\n (res nil)\n (js/setTimeout check 30)))]\n (check))))))\n\n(defn open-lesson!\n \"Opens a lesson: first the packages its boxes need, then the lesson itself (build-lesson!).\"\n [l]\n (repl-print! \"out\" (esc (str \"; \" (if (es?) \"Preparando la lección\" \"Preparing the lesson\") \"…\")))\n (-> (lesson-definitions l)\n ;; a lesson is a local work, run as trusted (build-lesson!): its packages compile first\n (.then (fn [defs]\n (reset! cbox/trust true)\n (.then (compiled-components (map #(nth % 2) defs)) (fn [_] (build-lesson! (assoc l :defs defs))))))\n (.catch (fn [e]\n (repl-print! \"err\" (esc (str \"; \" (or (.-message e) e) \" · \" (if (es?) \"la lección se abre sin ese paquete\" \"the lesson opens without that package\"))))\n (build-lesson! l)))))\n\n(defn build-lesson!\n \"Builds a lesson as a local work, step by step: the gestures of each step are made in order\n (they appear in the REPL) and each step remembers its point in the history.\"\n [l]\n (when-not @lesson (reset! lesson-back {:work @work :hist @hist :world @world :settings @settings :lines @line-state}))\n (reset! lesson nil)\n (eng/stop!)\n (reset! cbox/trust true)\n (cbox/forget-language! \"clojurescript\")\n (reset! work {:kind :local :id \"lesson\" :name (tr (:title l))})\n (reset-work-state! :local)\n (swap! mgr assoc :open false :confirm nil :invite nil)\n (set-hash! \"\")\n (lobby-presence!)\n (swap! hist assoc :mode :local :loaded true)\n (repl-print! \"out\" (esc (str \"; \" (if (es?) \"Lección\" \"Lesson\") \": «\" (tr (:title l)) \"»\")))\n (let [defs (atom (:defs l)) ; [[name classes source] …] of packages not yet in the work\n ;; definition boxes get ids beyond any the lesson writes (lessons name their boxes)\n free-id (atom (inc (reduce max 0 (for [st (:steps l) c (:code st) [_ n] (re-seq #\":b(\\d+)\" c)] (js/parseInt n 10)))))\n steps (reduce (fn [acc st]\n (doseq [c (:code st)]\n ;; a class from a package: its definition goes in just before the box that uses it\n (let [used (set (map second (re-seq box-class-re c)))]\n (doseq [[nm cls src :as d] @defs :when (some used cls)]\n (let [id (keyword (str \"b\" @free-id)) [x y] (component-slot)]\n (swap! free-id inc)\n (gesture! (str \"(box \" id \" \\\"component\\\" \" x \" \" y \")\"))\n (gesture! (str \"(code \" id \" \" (pr-str src) \")\"))\n ;; its classes now, not at the next render: the gestures after it use them\n (lib/sync! (eng/flat (root-patch))))\n (swap! defs (fn [ds] (vec (remove #{d} ds))))))\n (gesture! c))\n (conj acc (assoc st :pos (norm (:pos @world)))))\n [] (:steps l))]\n (reset! lesson (assoc l :steps steps :at 0))\n (lesson-go! (or (:start l) 0))\n (render-all!)\n (render-lesson!)))\n\n(defn close-lesson!\n \"Closes the lesson and brings back what was open before it.\"\n []\n (let [b @lesson-back w (:work b)]\n (reset! lesson nil)\n (reset! lesson-back nil)\n (eng/stop!)\n (cond\n (#{:room :solo} (:kind w)) (open-work! (:kind w) (:id w) (:name w))\n (= :local (:kind w)) (do (reset! work w)\n (reset-work-state! :local)\n (reset! hist (:hist b))\n (reset! settings (:settings b))\n (reset! world (:world b))\n (when (:lines b) (reset! line-state (:lines b)))\n (render-all!))\n :else (close-work!))\n (render-lesson!)))\n\n(defn open-help-patch!\n \"Opens the help patch of a class as a lesson (one step per use, when it has several), at step i.\"\n ([cls] (open-help-patch! cls 0))\n ([cls i]\n (let [steps (hlp/patch-steps cls)]\n (when (seq steps)\n (open-lesson! {:help cls\n :title {:en (str \"Help · \" cls) :es (str \"Ayuda · \" cls)}\n :start i\n :steps steps})))))\n\n(defn open-tutorial! [id]\n (when-let [t (first (filter (fn [t] (= id (:id t))) (when (sequential? @tutorials) @tutorials)))]\n (open-lesson! t)))\n\n(defn tutorial\n \"Opens a tutorial by id: (tutorial \\\"patch-to-code\\\"). Without an id, the list.\"\n ([] (show-help! nil) (if (sequential? @tutorials) (mapv :id @tutorials) :loading))\n ([id] (if (sequential? @tutorials) (do (open-tutorial! id) id) (do (load-tutorials!) :loading))))\n\n(defn set-lang! [l]\n (reset! lang l)\n (try (.setItem js/localStorage \"kairotic.lang\" (name l)) (catch :default _ nil))\n (render-lesson!)\n (render-help!))\n\n(.addEventListener ($ \"help-view\") \"click\"\n (fn [e]\n (let [t (.-target e)]\n (cond\n (.closest t \"[data-help-index]\") (do (.preventDefault e) (show-help! nil))\n (.closest t \"[data-doc]\")\n (let [el (.closest t \"[data-doc]\") l (.getAttribute el \"data-lang\")]\n (.preventDefault e)\n (when (and l (not= l (name @lang))) (reset! lang (keyword l)) (render-lesson!))\n (show-doc! (.getAttribute el \"data-doc\")))\n (.closest t \"[data-doc-patch]\")\n (try (open-link-work! (if (es?) \"Documentación\" \"Documentation\")\n (link-code (.getAttribute (.closest t \"[data-doc-patch]\") \"data-doc-patch\")))\n (catch :default x (repl-print! \"err\" (esc (str \"; \" (or (.-message x) x))))))\n (.closest t \"[data-help-open]\")\n (let [el (.closest t \"[data-help-open]\")]\n (.preventDefault e)\n (open-help-patch! (.getAttribute el \"data-help-open\") (js/parseInt (or (.getAttribute el \"data-help-step\") \"0\") 10)))\n (.closest t \"[data-help]\") (show-help! (.getAttribute (.closest t \"[data-help]\") \"data-help\"))\n (.closest t \"[data-tut]\") (open-tutorial! (.getAttribute (.closest t \"[data-tut]\") \"data-tut\"))\n (.closest t \"code.run\") (to-repl! (.getAttribute (.closest t \"code.run\") \"data-code\"))))))\n\n(.addEventListener ($ \"help-view\") \"change\"\n (fn [e]\n (when (= \"help-find\" (.. e -target -id))\n (let [v (str/trim (.. e -target -value))]\n (when (or (comp/lookup v) (seq (hlp/of v))) (show-help! v))))))\n\n(.addEventListener ($ \"lesson\") \"click\"\n (fn [e]\n (let [t (.-target e)]\n (cond\n (.closest t \"#lesson-prev\") (lesson-go! (dec (:at @lesson)))\n (.closest t \"#lesson-next\") (lesson-go! (inc (:at @lesson)))\n (.closest t \"#lesson-back\") (close-lesson!)\n (.closest t \"[data-lang]\") (set-lang! (keyword (.. (.closest t \"[data-lang]\") -dataset -lang)))\n (.closest t \"code.run\") (to-repl! (.getAttribute (.closest t \"code.run\") \"data-code\"))))))\n","page/10-embed.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 11 of 12: embed\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── embedding (Study 22) ─────────────────────────\n;; A link carries what it shows: a patch (its code, compressed), a tutorial step or a help patch. It\n;; opens as a local work (nothing is saved, and in ?embed / ?present nothing connects to a relay).\n;; The code of a link is read as data and only a few calls are let through, with literal arguments:\n;; a link cannot run code in this page. Its script and component boxes wait, as in a shared room,\n;; until whoever opened it runs them.\n;; Release/Perform (issue #50): the link carries a release of the patch (its presets boxes keeping their\n;; presets, as `(release)` makes it) and opens in Perform, so what whoever plays it changes is a take,\n;; never the work. Old ?present links open the same way.\n\n(declare with-stored-presets perform)\n\n(def link-calls links/calls)\n(defn link-code\n \"The code of a link, read as data and written again with only the calls a patch is made of\n (kairotic.links).\"\n [src] (links/read-code src))\n\n(defn script-boxes\n \"The script, component and pattern boxes of the work that would run code nobody has allowed yet.\"\n []\n (count (filter (fn [b] (and (#{\"script\" \"component\" \"pattern\"} (klass (:text b)))\n (not (cbox/allowed? (str (get-in b [:data :source]))))))\n (vals (:boxes (eng/flat (root-patch)))))))\n\n(defn trust-official!\n \"The component boxes of a link that are exactly an official package (as this page\n brings it) run without asking.\"\n []\n (let [srcs (keep (fn [b] (when (= \"component\" (klass (:text b))) (str (get-in b [:data :source]))))\n (vals (:boxes (eng/flat (root-patch)))))\n pkgs (distinct (for [s srcs [_ p] (re-seq #\":package \\\"([^\\\"]+)\\\"\" s) :when (get lib/packages p)] p))\n wanted (set srcs)]\n (-> (js/Promise.all\n (into-array\n (for [p pkgs] (-> (lib/import-package p) (.then (fn [[m origin]] (lib/package-source m origin))) (.catch (fn [_] nil))))))\n (.then (fn [arr]\n (let [ok (filter wanted (array-seq arr))]\n (when (seq ok)\n (swap! cbox/trusted into ok)\n (cbox/forget-language! \"component\")\n (render-all!))))))))\n\n(defn update-trust-bar! []\n (when-let [el ($ \"trust-bar\")]\n (let [n (if (and (= \"link\" (:id @work)) (not @cbox/trust)) (script-boxes) 0)]\n (set! (.-hidden el) (zero? n))\n (when (pos? n)\n (set! (.-textContent ($ \"trust-text\"))\n (if (es?)\n (str \"Este patch trae \" n (if (= n 1) \" script\" \" scripts\") \" (ClojureScript de quien hizo el enlace): no se ejecutan hasta que lo permitas.\")\n (str \"This patch brings \" n (if (= n 1) \" script\" \" scripts\") \" (ClojureScript by whoever made the link): they do not run until you allow it.\")))\n (set! (.-textContent ($ \"trust-run\")) (if (es?) \"Ejecutarlos\" \"Run them\"))))))\n\n(.addEventListener ($ \"trust-run\") \"click\" (fn [_] (trust-scripts true)))\n\n(defn open-link-work!\n \"Opens a local work whose history starts with the patch of a link.\"\n [nm code]\n (let [p (build code)]\n (eng/stop!)\n (reset! lesson nil)\n (reset! cbox/trust false)\n (cbox/forget-language! \"clojurescript\")\n (reset! work {:kind :local :id \"link\" :name nm})\n (reset-work-state! :local)\n (swap! mgr assoc :open false :confirm nil :invite nil)\n (swap! hist assoc :mode :local :loaded true)\n (let [id (new-node! nil 0 [[:load p]] nil)]\n (swap! world assoc :pos [id 1]))\n (ensure-classes!)\n (trust-official!)\n (repl-print! \"out\" (esc (str \"; \" (if (es?) \"Desde un enlace\" \"From a link\") \": «\" nm \"» (\" (if (es?) \"local: no se guarda\" \"local: not saved\") \")\")))\n (render-all!)))\n\n(defn site-url\n \"Where links point: this page on Kairotic Pages (inside claude.ai, the public site).\"\n []\n (if (pages?)\n (str (.-origin js/location) (.-pathname js/location))\n \"https://bonuoq.github.io/kairotic/\"))\n\n(defn release-code\n \"The code of the patch as a release carries it: its presets boxes keeping their presets (issue #50).\"\n []\n (let [p (inline-lines (work-patch))]\n (patch->code (try (with-stored-presets p) (catch :default _ p)))))\n\n(defn link-mode\n \"The mode of a link: :present (Release/Perform; also asked as :release or :perform) or :embed.\"\n [mode]\n (if (#{:present :release :perform \"present\" \"release\" \"perform\"} mode) :present :embed))\n\n(defn packed-code\n \"Promise of the patch as a link carries it: in Release/Perform, its release.\"\n [mode]\n (-> (js/Promise.resolve nil)\n (.then (fn [_] ((.-kairoticPack js/window) (if (= mode :present) (release-code) (patch->code (inline-lines (work-patch)))))))))\n\n(defn link-params\n \"Promise of the parameters that bring back what is shown now: the tutorial step, the help patch, or\n the patch itself — or, if asked in the Share/Export panel, a description for Claude (Study 23). In\n Release/Perform (:present), always the release of the patch (issue #50).\"\n ([] (link-params :embed))\n ([mode]\n (let [l @lesson\n ask (when (some-> ($ \"ep-ask\") .-checked) (str/trim (str (.-value ($ \"ep-ask-text\")))))]\n (cond\n (seq ask) (js/Promise.resolve [[\"ask\" ask]])\n (= mode :present) (.then (packed-code :present) (fn [z] [[\"code\" z]]))\n (and l (:id l)) (js/Promise.resolve [[\"tutorial\" (:id l)] [\"step\" (str (inc (:at l)))] [\"lang\" (name @lang)]])\n (and l (:help l)) (js/Promise.resolve [[\"help\" (:help l)] [\"lang\" (name @lang)]])\n :else (.then (packed-code :embed) (fn [z] [[\"code\" z]]))))))\n\n(defn url-with\n \"A link to the site with these parameters, after # (issue #55: a long patch is not refused by the server).\"\n [ps mode]\n (let [q (js/URLSearchParams.)]\n (doseq [[k v] ps] (.set q k v))\n (case mode :embed (.set q \"embed\" \"\") :present (.set q \"present\" \"\") nil)\n (str (site-url) \"#\" (str/replace (.toString q) #\"=(&|$)\" \"$1\"))))\n\n(defn iframe-of [url mode]\n (str \"<iframe src=\\\"\" (esc url) \"\\\" width=\\\"100%\\\" height=\\\"\" (if (= mode :present) 560 480)\n \"\\\" style=\\\"border:0\\\" allow=\\\"fullscreen; autoplay\\\" allowfullscreen loading=\\\"lazy\\\"></iframe>\"))\n\n(defn copy-text! [text]\n (-> (js/Promise.resolve)\n (.then (fn [_] (.writeText (.-clipboard js/navigator) text)))\n (.then (fn [_] true))\n (.catch (fn [_] false))))\n\n(defn embed-link\n \"A link (and an iframe) that shows what is open now in another page: the patch, or with :release\n (also :perform or :present) a release of it, in Perform, only its presentation, fullscreen. The link is\n copied. In Notion: /embed and paste it.\"\n ([] (embed-link :embed))\n ([mode]\n (let [mode (link-mode mode)]\n (-> (link-params mode)\n (.then (fn [ps]\n (let [u (url-with ps mode)]\n (repl-print! \"out\" (esc (str \"; \" u)))\n (repl-print! \"out\" (esc (str \"; \" (iframe-of u mode))))\n (.then (copy-text! u) (fn [ok] (repl-print! \"out\" (if ok \"; (link copied)\" \"; (copy it from here)\")))))))\n (.catch (fn [e] (repl-print! \"err\" (esc (str (or (.-message e) e)))))))\n :making-link)))\n\n;; ───── the Share/Export panel (it was Embed) ─────\n\n(defn ep-mode [] (if (.-checked (.querySelector js/document \"input[name=ep-mode][value=present]\")) :present :embed))\n\n(defn render-embed-pop! []\n (set! (.-hidden ($ \"ep-ask-row\")) (not (.-checked ($ \"ep-ask\"))))\n (when (and (.-checked ($ \"ep-ask\")) (str/blank? (.-value ($ \"ep-ask-text\"))))\n (set! (.-value ($ \"ep-ask-text\")) (str/trim (str (.-value ($ \"ask-text\"))))))\n (let [mode (ep-mode) l @lesson]\n (set! (.-textContent ($ \"ep-what\"))\n (cond (= mode :present) \"A release of this patch (its presets boxes keep their presets), opened in Perform: whatever is played or changed there is a take, never the work. Only the presented boxes, filling the frame, with a fullscreen button (without presented boxes, the whole patch).\"\n (and l (:id l)) (str \"This tutorial, at step \" (inc (:at l)) \", with its lesson bar.\")\n (and l (:help l)) (str \"The help patch of \" (:help l) \".\")\n :else \"This patch, scaled to the frame, with ▶ ■ and a link to open it in Kairotic.\"))\n (-> (link-params mode)\n (.then (fn [ps]\n (let [u (url-with ps mode)]\n (set! (.-value ($ \"ep-url\")) u)\n (set! (.-value ($ \"ep-iframe\")) (iframe-of u mode)))))\n (.catch (fn [e] (set! (.-value ($ \"ep-url\")) (str \"Error: \" (or (.-message e) e))))))))\n\n(.addEventListener ($ \"embed-btn\") \"click\"\n (fn [_]\n (let [el ($ \"embed-pop\")]\n (set! (.-hidden el) (not (.-hidden el)))\n (when-not (.-hidden el) (render-embed-pop!)))))\n\n(.addEventListener ($ \"embed-pop\") \"change\" (fn [_] (render-embed-pop!)))\n\n(.addEventListener ($ \"embed-pop\") \"click\"\n (fn [e]\n (let [t (.-target e)]\n (cond\n (.closest t \"#ep-close\") (set! (.-hidden ($ \"embed-pop\")) true)\n (.closest t \"[data-copy]\")\n (let [b (.closest t \"[data-copy]\") src ($ (.getAttribute b \"data-copy\"))]\n (.select src)\n (.then (copy-text! (.-value src))\n (fn [ok] (set! (.-textContent b) (if ok \"Copied\" \"Select + copy\"))\n (js/setTimeout (fn [] (set! (.-textContent b) \"Copy\")) 1500))))))))\n\n;; ───── inside the frame ─────\n\n(defn mode-url\n \"This same address in another mode: nil (the whole editor), :embed or :present.\"\n [mode]\n (let [q (js/URLSearchParams. (.toString url-params))]\n (.delete q \"embed\")\n (.delete q \"present\")\n (case mode :embed (.set q \"embed\" \"\") :present (.set q \"present\" \"\") nil)\n (let [s (str/replace (.toString q) #\"=(&|$)\" \"$1\")]\n (str (.-origin js/location) (.-pathname js/location) (when (seq s) (str \"#\" s))))))\n\n(defn fullscreen!\n \"Fills the screen with the presentation (or leaves it). Where the frame does not allow it, the\n presentation opens in a tab of its own.\"\n []\n (let [d js/document el (.-documentElement d)]\n (cond\n (.-fullscreenElement d) (.exitFullscreen d)\n (and (.-fullscreenEnabled d) (.-requestFullscreen el)) (.catch (.requestFullscreen el) (fn [_] (js/window.open (mode-url :present) \"_blank\" \"noopener\")))\n (and (.-webkitFullscreenEnabled d) (.-webkitRequestFullscreen el)) (.webkitRequestFullscreen el)\n :else (js/window.open (mode-url :present) \"_blank\" \"noopener\"))))\n\n(.addEventListener ($ \"fs-btn\") \"click\" (fn [_] (fullscreen!)))\n\n(defonce resize-timer (atom nil))\n(defonce first-touch (atom false))\n(when embed-mode\n (.add (.-classList js/document.body) \"embed\")\n (when (= embed-mode :present) (.add (.-classList js/document.body) \"present\"))\n (set! (.-href ($ \"open-full\")) (mode-url nil))\n (doseq [ev [\"resize\" \"fullscreenchange\" \"webkitfullscreenchange\"]]\n (.addEventListener (if (= ev \"resize\") js/window js/document) ev\n (fn [_]\n (js/clearTimeout @resize-timer)\n (reset! resize-timer (js/setTimeout (fn [] (render-scene (current))) 80))))))\n\n(defn perform-release!\n \"In ?present (Release/Perform, issue #50): the work opens in Perform, so what is played or changed there is\n a take and the release stays as it came. Not in a lesson, which has steps of its own.\"\n ([] (perform-release! 0))\n ([tries]\n (when (and (= embed-mode :present) (not @perf) (not @lesson))\n (if (#{:connecting :none} (:mode @hist))\n ;; the work is still opening: a moment later\n (when (< tries 40) (js/setTimeout (fn [] (perform-release! (inc tries))) 150))\n (try (perform)\n (catch :default e (js/console.warn \"Release/Perform: not in Perform\" e)))))))\n\n(defn present-what!\n \"In ?present (Release/Perform): in Perform, the presentation if the patch has presented boxes (otherwise\n the whole patch); the first touch starts the sound.\"\n []\n (when (= embed-mode :present)\n (perform-release!)\n (presentation (boolean (some :present (vals (:boxes (work-patch))))))\n (when-not @first-touch\n (reset! first-touch true)\n (.addEventListener ($ \"canvas-wrap\") \"pointerdown\"\n (fn [_] (when-not (eng/running?) (play)))\n #js {:once true :capture true}))))\n\n;; ───── a link that carries a description: ?ask=… (Study 23) ─────\n;; The link carries what to make, never a key: whoever opens it makes the patch with Claude on their own\n;; key (outside claude.ai, kept in their browser) or account. The result stays in their browser, so it is\n;; not made again on every visit, and \"Copy the link of this result\" gives a link that carries it.\n\n(defonce link-ask (atom nil)) ; {:text :base :key :done :busy :hidden}\n(defonce link-base (atom nil)) ; the code of the patch a ?code / ?src link brought, if any\n\n(defn ask-store-key [text base] (str \"kairotic.ask:\" (hash [text base])))\n\n(defn render-askbar! []\n (let [a @link-ask el ($ \"askbar\")]\n (set! (.-hidden el) (or (nil? a) (boolean (:hidden a))))\n (when a\n (let [s @sample-fn byok (some-> s .-byok) need-key (boolean (and s byok (not (.hasKey s))))]\n (set! (.-textContent ($ \"ab-text\")) (str \"«\" (:text a) \"»\"))\n (set! (.-hidden ($ \"ab-keyrow\")) (not need-key))\n (set! (.-disabled ($ \"ab-go\")) (boolean (or (nil? s) need-key (:busy a))))\n (set! (.-textContent ($ \"ab-go\")) (if (:done a) \"Make it again\" \"Make it with Claude\"))\n (set! (.-hidden ($ \"ab-fix\")) (not (:done a)))\n (set! (.-innerHTML ($ \"ab-note\"))\n (cond\n (nil? s) \"Claude is not available here: open it in Kairotic ↗.\"\n byok (str \"Claude makes this patch from the description with <b>your own Anthropic API key</b>\"\n (when embed-mode \" (saved only in this browser, for this frame)\")\n \", sent only to api.anthropic.com. The link carries the description, never a key.\")\n :else \"Claude makes this patch from the description with your own Claude account.\"))))))\n\n(defn ask-link! []\n (when-let [a @link-ask]\n (when-not (:busy a)\n (swap! link-ask assoc :busy true)\n (render-askbar!)\n ;; from the patch the link brought (or an empty one), not from an earlier result\n (dispatch! [:load (build (or (:base a) \"\"))])\n (-> (ask-patch! (:text a) (boolean (:base a)))\n (.then (fn [code]\n (when code\n (try (.setItem js/localStorage (:key a) code) (catch :default _ nil))\n (swap! link-ask assoc :done true)\n (present-what!))))\n (.finally (fn [] (swap! link-ask assoc :busy false) (render-askbar!)))))))\n\n(defn setup-ask!\n \"A link with ?ask: the bar with the description; what this browser made from it before, if anything.\"\n [text base]\n (let [k (ask-store-key text base)\n made (try (.getItem js/localStorage k) (catch :default _ nil))]\n (reset! link-ask {:text text :base base :key k})\n (when (seq made)\n (try (apply-patch-code! made)\n (swap! link-ask assoc :done true)\n (ask-log! \"done\" \"made earlier in this browser\")\n (catch :default _ nil)))\n (render-askbar!)))\n\n(.addEventListener ($ \"ab-go\") \"click\" (fn [_] (ask-link!)))\n(.addEventListener ($ \"ab-hide\") \"click\" (fn [_] (swap! link-ask assoc :hidden true) (render-askbar!)))\n(.addEventListener ($ \"ab-key-save\") \"click\"\n (fn [_] (when-let [s @sample-fn]\n (let [v (str/trim (.-value ($ \"ab-key\")))]\n (when (seq v) (.setKey s v) (set! (.-value ($ \"ab-key\")) \"\") (render-askbar!) (render-key!))))))\n(.addEventListener ($ \"ab-fix\") \"click\"\n (fn [_]\n (-> (packed-code (or embed-mode :embed))\n (.then (fn [z]\n (let [u (url-with [[\"code\" z]] (or embed-mode :embed))]\n (.then (copy-text! u)\n (fn [ok] (set! (.-textContent ($ \"ab-status\"))\n (if ok \"Link copied: put it in place of this one, and everyone sees this patch.\"\n (str \"Copy this link: \" u)))))))))))\n\n(defn ask-link\n \"A link that carries a description for Claude: (ask-link \\\"a sine at 440 Hz with an FM knob\\\"),\n (ask-link \\\"…\\\" :present). Whoever opens it makes the patch with their own key or account.\"\n ([text] (ask-link text :embed))\n ([text mode]\n (let [u (url-with [[\"ask\" (str text)]] (link-mode mode))]\n (repl-print! \"out\" (esc (str \"; \" u)))\n (.then (copy-text! u) (fn [ok] (repl-print! \"out\" (if ok \"; (link copied)\" \"; (copy it from here)\"))))\n :making-link)))\n\n\n;; ───── the log of requests to Claude: shown, loaded again, exported, shared ─────\n\n(defn ask-play-url\n \"Promise of a link that plays what an entry made: its patch, or a patch with its component.\"\n [e]\n (let [code (if (= \"component\" (:kind e))\n (str \"(box :b1 \\\"component\\\" 20 20)\\n(code :b1 \" (pr-str (str (:code e))) \")\")\n (str (:code e)))]\n (.then ((.-kairoticPack js/window) code) (fn [z] (url-with [[\"code\" z]] nil)))))\n\n(defn ask-markdown\n \"An entry as Markdown, to read or to share.\"\n [e url max-code]\n (let [code (str (:code e))]\n (str \"**Asked Claude** (\" (:kind e) (when (:change e) \", changing the open one\") \" · \" (:tier e) \") in Kairotic\\n\\n\"\n \"> \" (str/replace (str (:request e)) #\"\\n\" \"\\n> \") \"\\n\\n\"\n (when url (str \"▶ [Open it in Kairotic](\" url \")\\n\\n\"))\n (when (seq code)\n (if (> (count code) max-code)\n (str \"_The code (\" (count code) \" characters) is in the link._\\n\\n\")\n (str \"```clojure\\n\" code \"\\n```\\n\\n\")))\n \"<details><summary>How it went: \" (:status e) \"</summary>\\n\\n\"\n (str/join \"\\n\" (map #(str \"- \" %) (take 30 (:lines e))))\n \"\\n</details>\\n\")))\n\n(defn render-ask-history! []\n (when-let [ol ($ \"ask-hist-list\")]\n (let [es (reverse (ask-entries))]\n (set! (.-textContent ($ \"ask-hist-n\")) (str \"(\" (count es) \")\"))\n (set! (.-innerHTML ol)\n (apply str\n (for [e es]\n (str \"<li data-ask=\\\"\" (esc (:id e)) \"\\\">\"\n \"<div class=\\\"ah-top\\\">\" (esc (:kind e)) \" · \" (esc (clojure.core/subs (str (:t e)) 0 16)) \" · <span class=\\\"\" (esc (:status e)) \"\\\">\" (esc (:status e)) \"</span>\"\n (when (:work e) (str \" · \" (esc (:work e)))) \"</div>\"\n \"<div class=\\\"ah-q\\\">\" (esc (ai/cut (:request e) 300)) \"</div>\"\n \"<div class=\\\"ah-acts\\\">\"\n (when (seq (:code e)) \"<button class=\\\"act\\\" data-act=\\\"load\\\" title=\\\"Into the open work, as one event\\\">Load</button>\")\n \"<button class=\\\"act\\\" data-act=\\\"copy\\\" title=\\\"As Markdown\\\">Copy</button>\"\n (when (seq (:code e)) \"<button class=\\\"act\\\" data-act=\\\"share\\\" title=\\\"Opens a discussion already written in the Gallery of the Kairotic repository: you read it and publish it, under your own account\\\">Share on GitHub…</button>\")\n \"<button class=\\\"act\\\" data-act=\\\"del\\\" title=\\\"Delete this entry\\\">✕</button>\"\n \"</div></li>\")))))))\n\n(def share-repo \"https://github.com/bonuoq/kairotic\")\n\n(.addEventListener ($ \"ask-hist-list\") \"click\"\n (fn [ev]\n (when-let [btn (.closest (.-target ev) \"[data-act]\")]\n (let [id (.getAttribute (.closest btn \"[data-ask]\") \"data-ask\")\n e (first (filter #(= id (:id %)) (ask-entries)))\n act (.getAttribute btn \"data-act\")]\n (when e\n (case act\n \"load\" (try\n (if (= \"component\" (:kind e))\n (let [src (str \";; written with Claude\\n;; asked: \" (str/replace (ai/cut (:request e) 300) #\"\\s+\" \" \") \"\\n\" (:code e))]\n (swap! cbox/trusted conj src)\n (new-definition! src))\n (apply-patch-code! (:code e)))\n (catch :default x (repl-print! \"err\" (esc (str \"; \" (or (.-message x) x))))))\n \"copy\" (-> (ask-play-url e)\n (.then (fn [u] (copy-text! (ask-markdown e u 20000))))\n (.then (fn [ok] (set! (.-textContent btn) (if ok \"Copied\" \"Not copied\")))))\n \"share\" (let [w (js/window.open \"about:blank\" \"_blank\")]\n ;; the window is opened at the click (a popup blocker allows it), then filled\n (-> (ask-play-url e)\n (.then (fn [u]\n (let [q (js/URLSearchParams.)]\n (.set q \"category\" \"gallery\")\n (.set q \"labels\" \"gallery\")\n (.set q \"title\" (ai/cut (str/replace (str (:request e)) #\"\\s+\" \" \") 90))\n (.set q \"body\" (ask-markdown e u 3500))\n (let [href (str share-repo \"/discussions/new?\" (.toString q))]\n (if w (set! (.. w -location -href) href) (js/window.open href \"_blank\"))))))))\n \"del\" (do (save-ask-entries! (vec (remove #(= id (:id %)) (ask-entries))))\n (render-ask-history!))\n nil))))))\n\n(.addEventListener ($ \"ask-hist-export\") \"click\"\n (fn [_]\n (let [text (str/join \"\\n\" (map #(js/JSON.stringify (clj->js %)) (ask-entries)))\n a (js/document.createElement \"a\")]\n (set! (.-href a) (js/URL.createObjectURL (js/Blob. #js [text] #js {:type \"application/x-ndjson\"})))\n (set! (.-download a) \"kairotic-claude-log.jsonl\")\n (.click a))))\n\n(.addEventListener ($ \"ask-hist-clear\") \"click\"\n (fn [_]\n (let [b ($ \"ask-hist-clear\")]\n (if (= \"Sure?\" (.-textContent b))\n (do (save-ask-entries! []) (set! (.-textContent b) \"Clear\") (render-ask-history!))\n (do (set! (.-textContent b) \"Sure?\") (js/setTimeout (fn [] (set! (.-textContent b) \"Clear\")) 3000))))))\n\n(render-ask-history!)\n\n(defn tutorials-ready []\n (js/Promise.\n (fn [res]\n (load-tutorials!)\n (if (sequential? @tutorials)\n (res @tutorials)\n (add-watch tutorials ::ready (fn [_ _ _ n] (when (sequential? n) (remove-watch tutorials ::ready) (res n))))))))\n\n(defn start-from-url!\n \"Opens what the address asks for (?code, ?src, ?tutorial & ?step, ?help); in an embed, a local work if nothing.\"\n []\n (when-let [l (url-param \"lang\")] (when (#{\"es\" \"en\"} l) (reset! lang (keyword l)) (render-lesson!) (render-help!)))\n (let [code (url-param \"code\") src (raw-param \"src\") ask (some-> (url-param \"ask\") str/trim not-empty) tut (url-param \"tutorial\") hc (url-param \"help\")\n step (js/parseInt (or (url-param \"step\") \"1\") 10)\n link-name (str (if (es?) \"Enlace\" \"Link\") (when (= embed-mode :present) \" · release\"))\n fallback (fn [e]\n (when e (repl-print! \"err\" (esc (str \"; \" (or (.-message e) e)))))\n (when (and embed-mode (nil? (:kind @work))) (open-work! :local \"local\" \"Local\"))\n (present-what!))]\n (-> (cond\n (seq code) (.then ((.-kairoticUnpack js/window) code)\n (fn [src] (open-link-work! link-name (reset! link-base (link-code src)))))\n ;; the code itself, readable (written by hand, or by Claude in a Notion page)\n (seq src) (.then (js/Promise.resolve nil) (fn [_] (open-link-work! link-name (reset! link-base (link-code src)))))\n (seq ask) (.then (js/Promise.resolve nil) (fn [_] (open-link-work! link-name \"\")))\n (seq tut) (.then (tutorials-ready)\n (fn [_] (or (open-tutorial! tut) (throw (js/Error. (str \"no tutorial \" (pr-str tut)))))))\n (seq hc) (or (open-help-patch! hc) (js/Promise.reject (js/Error. (str \"no help patch for \" (pr-str hc)))))\n :else (js/Promise.resolve nil))\n (.then (fn [_]\n (when (and @lesson (> step 1)) (lesson-go! (dec step)))\n (when (and ask (= \"link\" (:id @work))) (setup-ask! ask @link-base))\n (fallback nil)))\n (.catch fallback))))\n","page/11-startup.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 12 of 12: startup\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── startup ─────────────────────────\n\n(render-all!)\n(render-comp!)\n(render-controls!)\n(render-manager!)\n(repl-print! \"out\" (str \"; Kairotic \" version \" — \" (cond (.-claude js/window) \"inside claude.ai: works, rooms and Claude come from claude.ai.\" (backend) \"on its own: works and rooms in GUN (your solo works are encrypted in this browser), Claude with your own API key (Claude tab).\" :else \"without a database: local works only.\")))\n(repl-print! \"out\" \"; New here? The Help tab has the tutorials and a page for every class (select a box and press ?). The Claude tab makes patches and components from a description. Share/Export gives a link to a patch, or puts it in another page.\")\n\n;; on Pages, the address carries ?peer= while this page's relays are not the site's\n(address-carries-relay!)\n\n(let [h (.-hash js/location) m (re-matches #\"#room-(.+)\" (str h))]\n (when m (swap! mgr assoc :invite (second m))))\n\n(defn start-backend! []\n (-> (js/Promise.all #js [(cuse \"db\") (cuse \"user\") (cuse \"room\")])\n (.then (fn [arr]\n (let [db (aget arr 0) user (aget arr 1) room (aget arr 2)]\n (reset! userref user)\n (reset! roomref room)\n (when room\n (.onPeers room\n (fn [ch]\n (reset! lobby-peers\n (vec (for [p (array-seq (.-peers ch))]\n {:me (.-isMe p) :room (let [s (.. p -presence -room)] (when (string? s) s))}))))\n (fn [_] nil))\n (lobby-presence!))\n (if (nil? db)\n (do (swap! hist assoc :mode :none :writable false) (render-manager!))\n (-> (js/Promise.all #js [(if user (.id user) (js/Promise.resolve nil))\n (if user (.can user \"data.write\") (js/Promise.resolve nil))])\n (.then (fn [r]\n (let [id (aget r 0) can (aget r 1)\n writable (boolean (and id (not (false? can))))]\n (swap! me assoc :id id)\n (reset! dbref db)\n (listen-library! db)\n (swap! hist assoc :mode :none :writable writable)\n (.onSnapshot (.collection db \"rooms\")\n (fn [snap] (reset! rooms (into {} (for [d (array-seq (.-docs snap)) :when (.-exists d)] (let [s (meta-of d)] [(:id s) s])))))\n db-failed!)\n (when id\n (.onSnapshot (.collection db (str \"data/users/\" id))\n (fn [snap] (reset! solo-works (into {} (for [d (array-seq (.-docs snap)) :when (.-exists d)] (let [s (meta-of d)] [(:id s) s])))))\n (fn [_] nil)))\n (render-manager!)))))))))\n (.catch (fn [_] (swap! hist assoc :mode :none) (render-manager!)))))\n\n;; an embed works on its own (no database, no relay); the whole editor connects first, then opens\n;; what the address asks for\n(if embed-mode\n (start-from-url!)\n (.then (start-backend!) (fn [_] (start-from-url!))))\n","page/12-feedback.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 13 of 13: feedback\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── feedback (0.1.0-alpha) ─────────────────────────\n;; A bug, an idea or a question becomes a GitHub issue (or a Q&A discussion) written for you: the page\n;; only opens GitHub with the text filled in; it is published there, under your own account, or not.\n;; What is added is chosen: the patch on screen (as a link), recent errors, version and browser. The\n;; draft stays in this browser until it is written.\n\n(def fb-repo \"https://github.com/bonuoq/kairotic\")\n(def fb-draft-key \"kairotic.feedback-draft\")\n\n(js/window.addEventListener \"error\"\n (fn [e] (swap! recent-errors (fn [es] (vec (take-last 10 (conj es (str \"page: \" (or (.-message e) e)))))))))\n\n(defn fb-kind []\n (keyword (.-value (.querySelector js/document \"input[name=fb-kind]:checked\"))))\n\n(def fb-templates\n {:bug \"What I did:\\n\\n\\nWhat I expected:\\n\\n\\nWhat happened:\\n\"\n :idea \"What I would like to do:\\n\\n\\nWhy (what it would let me make, play or teach):\\n\"\n :question \"\"})\n\n(defn fb-edition []\n (cond (.-claude js/window) \"claude.ai\"\n embed-mode (str \"embed (\" (name embed-mode) \")\")\n (pages?) \"Kairotic Pages\"\n :else \"local\"))\n\n(defn fb-body\n \"Promise of the text of the issue, with what was chosen.\"\n []\n (let [text (str/trim (.-value ($ \"fb-text\")))\n patch? (and (.-checked ($ \"fb-patch\")) (seq (:boxes (work-patch))))\n errs (when (.-checked ($ \"fb-errors\")) (seq @recent-errors))\n env? (.-checked ($ \"fb-env\"))]\n (-> (if patch?\n (.then ((.-kairoticPack js/window) (patch->code (work-patch))) (fn [z] (url-with [[\"code\" z]] nil)))\n (js/Promise.resolve nil))\n (.then (fn [link]\n (let [link (when (and link (< (count link) 5000)) link)]\n (str text \"\\n\"\n (when link (str \"\\n**The patch:** [open it in Kairotic](\" link \")\\n\"))\n (when (and patch? (nil? link)) \"\\n_The patch is too large for a link: paste its code (Code tab) here._\\n\")\n (when errs (str \"\\n<details><summary>Recent errors</summary>\\n\\n```\\n\" (str/join \"\\n\" (map #(ai/cut % 300) errs)) \"\\n```\\n</details>\\n\"))\n (when env? (str \"\\n---\\nKairotic \" version \" · \" (fb-edition) \" · \" (.-userAgent js/navigator) \"\\n\")))))))))\n\n(defn fb-save-draft! []\n (try (.setItem js/localStorage fb-draft-key\n (js/JSON.stringify #js {:kind (name (fb-kind)) :title (.-value ($ \"fb-title\")) :text (.-value ($ \"fb-text\"))}))\n (catch :default _ nil)))\n\n(defn render-fb-preview! []\n (set! (.-textContent ($ \"fb-errn\")) (str \"(\" (count @recent-errors) \")\"))\n (set! (.-placeholder ($ \"fb-text\"))\n (case (fb-kind)\n :bug \"What you did, what you expected, what happened. The steps to make it happen again help most.\"\n :idea \"What you would like Kairotic to do, and what for.\"\n \"Your question.\"))\n (set! (.-textContent ($ \"fb-go\")) (if (= :question (fb-kind)) \"Ask it on GitHub…\" \"Write it on GitHub…\"))\n (.then (fb-body) (fn [b] (set! (.-textContent ($ \"fb-preview\")) b))))\n\n(defn fb-url [title body]\n (let [q (js/URLSearchParams.) kind (fb-kind)]\n (.set q \"title\" (if (seq title) title (case kind :bug \"Bug: \" :idea \"Idea: \" \"Question: \")))\n (.set q \"body\" body)\n (if (= kind :question)\n (do (.set q \"category\" \"q-a\") (str fb-repo \"/discussions/new?\" (.toString q)))\n (do (.set q \"labels\" (if (= kind :bug) \"bug\" \"enhancement\")) (str fb-repo \"/issues/new?\" (.toString q))))))\n\n(.addEventListener ($ \"fb-go\") \"click\"\n (fn [_]\n (let [w (js/window.open \"about:blank\" \"_blank\") title (str/trim (.-value ($ \"fb-title\")))]\n ;; the window opens at the click (popup blockers allow it), then gets its address\n (.then (fb-body)\n (fn [b] (let [u (fb-url title b)] (if w (set! (.. w -location -href) u) (js/window.open u \"_blank\")))\n ;; written: the draft starts again\n (set! (.-value ($ \"fb-title\")) \"\")\n (set! (.-value ($ \"fb-text\")) (get fb-templates (fb-kind)))\n (fb-save-draft!))))))\n\n(.addEventListener ($ \"fb-copy\") \"click\"\n (fn [_]\n (-> (fb-body)\n (.then (fn [b] (copy-text! (str \"# \" (.-value ($ \"fb-title\")) \"\\n\\n\" b))))\n (.then (fn [ok] (set! (.-textContent ($ \"fb-copy\")) (if ok \"Copied\" \"Not copied\"))\n (js/setTimeout (fn [] (set! (.-textContent ($ \"fb-copy\")) \"Copy\")) 1500))))))\n\n(.addEventListener (.querySelector js/document \".fb-kind\") \"change\"\n (fn [_]\n ;; an untouched template follows the kind\n (when (or (str/blank? (.-value ($ \"fb-text\"))) (some #(= (.-value ($ \"fb-text\")) %) (vals fb-templates)))\n (set! (.-value ($ \"fb-text\")) (get fb-templates (fb-kind))))\n (fb-save-draft!)\n (render-fb-preview!)))\n\n(doseq [id [\"fb-title\" \"fb-text\"]]\n (.addEventListener ($ id) \"input\" (fn [_] (fb-save-draft!))))\n(doseq [id [\"fb-text\" \"fb-patch\" \"fb-errors\" \"fb-env\"]]\n (.addEventListener ($ id) \"change\" (fn [_] (render-fb-preview!))))\n\n;; the open issues, read from GitHub's public API (where the page may reach it)\n(defonce fb-issues (atom nil))\n\n;; ───── an issue, to review and fix with Claude ─────\n;; Each issue has a button that opens a new Claude chat (claude.ai/new) with a prompt about that issue\n;; already written: you read it, change it if you like, and send it. Nothing is sent from here. The prompt\n;; stays short, because it travels in the address.\n\n(def claude-chat-url \"https://claude.ai/new\")\n(def fb-repo-slug \"bonuoq/kairotic\")\n\n(defn claude-prompt\n \"What Claude is asked about an issue: to read it in full on GitHub, review it and fix it in a pull request.\"\n [{:keys [number title url body labels]}]\n (str \"Review issue #\" number \" of the GitHub repository \" fb-repo-slug \" (\" fb-repo \"): \\\"\" title \"\\\"\" (when (seq labels) (str \" (\" (str/join \", \" labels) \")\")) \".\\n\"\n url \"\\n\\n\"\n (when (seq (str/trim (str body)))\n (str \"It says:\\n\" (ai/cut (str/trim (str body)) 900) \"\\n\\n\"))\n \"Read the whole issue and its comments on GitHub first. Then tell me what you understand and how you would \"\n \"solve it; if it is clear, fix it on a new branch, following the conventions of the repository (CHANGELOG, \"\n \"the guide in English and Spanish, tests in tests/), check that the tests pass, and open a pull request that \"\n \"closes the issue.\"))\n\n(defn claude-url [issue]\n (let [q (js/URLSearchParams.)]\n (.set q \"q\" (claude-prompt issue))\n (str claude-chat-url \"?\" (.toString q))))\n\n(defn render-fb-issues! []\n (let [is @fb-issues]\n (set! (.-innerHTML ($ \"fb-list\"))\n (cond\n (nil? is) \"<li class=\\\"soft\\\">…</li>\"\n (= :error is) (str \"<li class=\\\"soft\\\">They could not be read from here: <a href=\\\"\" fb-repo \"/issues\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\">see them on GitHub</a>.</li>\")\n (empty? is) \"<li class=\\\"soft\\\">None yet.</li>\"\n :else (str (apply str (for [i is]\n (str \"<li><a href=\\\"\" (esc (:url i)) \"\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\">\" (esc (:title i)) \"</a>\"\n (when (seq (:labels i)) (str \"<span class=\\\"lb\\\">\" (esc (str/join \" · \" (:labels i))) \"</span>\"))\n \"<a class=\\\"fb-claude\\\" href=\\\"\" (esc (claude-url i)) \"\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\"\"\n \" title=\\\"Open a Claude chat with a prompt to review and fix this issue (you send it)\\\">Claude ↗</a>\"\n \"</li>\")))\n \"<li class=\\\"soft\\\"><a href=\\\"\" fb-repo \"/issues\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\">all of them…</a></li>\")))))\n\n(defn load-fb-issues! []\n (when (or (nil? @fb-issues) (= :error @fb-issues))\n (-> (js/fetch \"https://api.github.com/repos/bonuoq/kairotic/issues?state=open&per_page=20\")\n (.then (fn [r] (if (.-ok r) (.json r) (throw (js/Error. (str (.-status r)))))))\n (.then (fn [a]\n (reset! fb-issues\n (vec (for [i (array-seq a) :when (nil? (.-pull_request i))]\n {:title (.-title i) :url (.-html_url i) :number (.-number i) :body (.-body i)\n :labels (vec (for [l (array-seq (.-labels i))] (.-name l)))})))))\n (.catch (fn [_] (reset! fb-issues :error)))\n (.finally (fn [] (render-fb-issues!))))))\n\n(.addEventListener ($ \"tab-feedback\") \"click\" (fn [_] (render-fb-preview!) (load-fb-issues!)))\n\n;; the draft that was being written\n(let [d (try (some-> (.getItem js/localStorage fb-draft-key) js/JSON.parse) (catch :default _ nil))]\n (when-let [k (some-> d .-kind)]\n (when-let [r (.querySelector js/document (str \"input[name=fb-kind][value=\" k \"]\"))] (set! (.-checked r) true)))\n (set! (.-value ($ \"fb-title\")) (or (some-> d .-title) \"\"))\n (set! (.-value ($ \"fb-text\")) (or (some-> d .-text) (get fb-templates (fb-kind)))))\n\n(defn feedback\n \"Opens the Feedback tab: (feedback), or with a title (feedback \\\"the score does not redraw\\\").\"\n ([] (.click ($ \"tab-feedback\")) :feedback)\n ([title] (set! (.-value ($ \"fb-title\")) (str title)) (fb-save-draft!) (feedback)))\n","page/13-perform.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 14 of 14: perform\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── Compose and Perform (issue #5) ─────────────────────────\n;; Compose is the usual mode: every change to the work is a point of its history.\n;; Perform opens a time of its own to rehearse, try and improvise with the work: the changes make a take\n;; that starts from a point of the history and stays out of it (the patch on screen and in the engine is\n;; the take). ◀ / Ctrl+Z take back your last changes of the take. Going back to Compose keeps the take as\n;; a new point (a branch from where it started, closed by a keyframe) or discards it and goes back to\n;; where you were. In a shared room, those who perform from the same point share one take: a jam, where\n;; only they receive each other's changes; whoever is not performing is invited to join it.\n;; A snapshot, in either mode, writes a keyframe: a point of the history with the work as it is now.\n;; The state of the take is `perf` (00-work.cljs); the take is not kept if the page is reloaded.\n\n(defn layout-ev?\n \"A change of layout only: a box moved, placed in presentation or shown in another view (also inside a sub-patch).\"\n [p [op & args]]\n (case op\n (:move :present :view :size) true\n :batch (let [[evs] args] (boolean (and (sequential? evs) (seq evs) (every? (fn [e] (and (vector? e) (layout-ev? p e))) evs))))\n :in (let [[id inner] args b (get-in p [:boxes id])]\n (boolean (and (embedded? b) (vector? inner) (layout-ev? (or (:data b) empty-patch) inner))))\n false))\n\n(defn take-summary\n \"How many changes a take has, and how many of them change the work (the rest only move boxes).\"\n [st]\n (let [evs (map :ev (perf-events st))\n lay (count (filter (fn [e] (layout-ev? (:base st) e)) evs))]\n {:changes (count evs) :layout lay :work (- (count evs) lay)}))\n\n(defn moment-name [pos] (if-let [p (norm pos)] (str \"moment \" (depth-of p)) \"the start\"))\n\n;; ───── the jam: one document per performer in <work>/jams, with the changes of their take ─────\n\n(defonce jam-unsub (atom nil))\n(defonce jam-seen (atom #{})) ; jams already offered here (or your own)\n\n;; the jams of the line on screen (the main line's are where they always were)\n(defn jam-coll [] (when (and (= :room (:kind @work)) (persist?)) (str (line-base) \"/jams\")))\n\n(defn new-jam-id []\n (str \"j\" (.toString (js/Date.now) 36) (.toString (js/Math.floor (* (js/Math.random) 1679616)) 36)))\n\n(defn jam-push!\n \"Writes your changes of the take where the others in the jam read them.\"\n []\n (when-let [{:keys [jam jam-path at own]} @perf]\n (when (and jam jam-path @dbref)\n (let [body (clj->js {:jam jam :at at :session session-id :author (my-author) :t (js/Date.now)\n :events (mapv (fn [e] (enc [(:t e) (:ev e)])) own)})]\n (enqueue! jam-path (fn [] (.set (.doc @dbref jam-path) body)))))))\n\n;; ───── messages played in the jam (issue #11) ─────\n;; A knob turned, a number dragged, a msg clicked are messages, not changes of the take: they are written,\n;; a few at a time, to a second document of each performer (<jam>-<session>-live, the last ones), and the\n;; others play them in their engines as they arrive. What was there before you joined is not played.\n\n(def live-keep 48)\n(defonce live-buf (atom [])) ; your last messages: [{:t :f :i :v}]\n(defonce live-seen (atom {})) ; session → the newest message of theirs already played here\n(defonce live-timer (atom nil))\n\n(defn live-path [] (when-let [p (:jam-path @perf)] (str p \"-live\")))\n\n(defn live-flush! []\n (reset! live-timer nil)\n (when-let [path (live-path)]\n (when @dbref\n (let [body (clj->js {:jam (:jam @perf) :kind \"live\" :session session-id :t (js/Date.now)\n :msgs (mapv (fn [{:keys [t f i v]}] (enc [t f i v])) @live-buf)})]\n (enqueue! path (fn [] (.set (.doc @dbref path) body)))))))\n\n(defn played!\n \"A message played here: in a jam, it goes to the others too (sent every 60 ms at most).\"\n [f inlet v]\n (when (and (:jam @perf) (:jam-path @perf))\n (swap! live-buf (fn [b] (vec (take-last live-keep (conj b {:t (js/Date.now) :f f :i inlet :v v})))))\n (when-not @live-timer (reset! live-timer (js/setTimeout live-flush! 60)))))\n\n(defn play-live!\n \"Plays here the new messages of another performer of the jam.\"\n [s msgs]\n (let [ms (sort-by first (filter (fn [[t f i]] (and (number? t) (keyword? f) (number? i))) msgs))\n newest (reduce max 0 (map first ms))\n seen (get @live-seen s)]\n (when (seq ms)\n (swap! live-seen assoc s (max newest (or seen 0)))\n ;; the first time: what was played before you came is not played again\n (when seen\n (let [p (work-patch)]\n (doseq [[t f i v] ms :when (> t seen)]\n (when (get-in (eng/flat p) [:boxes f])\n ;; played by someone else: what a task of theirs finds is theirs to keep (eng/*remote*)\n (try (binding [eng/*remote* true] (eng/inject! engine-patch f i v))\n (catch :default e (js/console.error \"jam message\" e))))))\n (render-overlay!)))))\n\n(defn on-jam\n \"The documents of the jams of this work: the changes of the others in yours join the take, and their\n messages are played here.\"\n [snap]\n (when-let [{:keys [jam]} @perf]\n (doseq [d (array-seq (.-docs snap)) :when (.-exists d)\n :let [m (js->clj (.data d)) s (get m \"session\")]\n :when (and (= jam (get m \"jam\")) (= \"live\" (get m \"kind\")) (string? s) (not= s session-id))]\n (play-live! s (map dec* (get m \"msgs\"))))\n (let [others (into {} (for [d (array-seq (.-docs snap)) :when (.-exists d)\n :let [m (js->clj (.data d)) s (get m \"session\")]\n :when (and (= jam (get m \"jam\")) (not= \"live\" (get m \"kind\")) (string? s) (not= s session-id))]\n [s (vec (keep (fn [x]\n (let [[t ev] (dec* x)]\n (when (and (number? t) (vector? ev) (keyword? (first ev))) {:t t :s s :ev ev})))\n (get m \"events\")))]))]\n (when (not= others (:others @perf))\n (swap! perf (fn [st] (when st (perf-recompute (assoc st :others others)))))))))\n\n(defn jam-listen! []\n (when-let [f @jam-unsub] (f))\n (reset! jam-unsub (when-let [c (jam-coll)] (.onSnapshot (.collection @dbref c) on-jam db-failed!))))\n\n(defn jam-at\n \"The jam someone is playing from this point of the history, if any.\"\n [pos]\n (some (fn [p] (when (and (:jam p) (not (:same p)) (same-line? p) (= (norm (:jam-at p)) pos)) (:jam p))) @peers))\n\n(defn jam-mates\n \"Who else is in your jam now.\"\n []\n (when-let [j (:jam @perf)] (filter (fn [p] (and (= j (:jam p)) (not (:same p)))) @peers)))\n\n;; ───── commands ─────\n\n(defn perform\n \"Perform: rehearse, try and improvise outside the history, from where you are. In a shared room, with\n those performing from this same point (a jam). (compose) goes back, keeping the take or not.\"\n ([] (perform nil))\n ([jam-id]\n (when @perf (fail \"You are already in Perform: (compose) to go back.\"))\n (when (#{:connecting :none} (:mode @hist)) (fail \"Open a work before performing.\"))\n (stop-follow!)\n (let [pos (norm (:pos @world))\n base (work-patch)\n coll (jam-coll)\n jam (when coll (or jam-id (jam-at pos) (new-jam-id)))]\n (reset! perf {:from pos :origin pos :at pos :base base :patch base :own [] :others {} :redo [] :cut 0\n :jam jam :jam-path (when jam (str coll \"/\" jam \"-\" session-id))\n ;; the lines it follows stay where they are now while performing (#117, decision 4)\n :pins (followed-fronts)})\n (when jam\n (swap! jam-seen conj jam)\n (jam-listen!)\n (jam-push!))\n (publish-presence!)\n (cond-> {:perform-from (moment-name pos)}\n jam (assoc :jam jam)))))\n\n(defn jam\n \"Joins the jam of someone performing in this room: from the same point of the history, with them.\"\n [id]\n (let [p (first (filter (fn [p] (= (:jam p) id)) @peers))]\n (cond\n (nil? p) (fail \"Nobody is performing in that jam now.\")\n (= id (:jam @perf)) (fail \"You are already in that jam.\")\n @perf (fail \"You are in Perform: (compose) first, then join the jam.\")\n (not (and (:jam-at p) (node (first (:jam-at p))))) (fail \"That point of the history has not arrived here yet: try again in a moment.\"))\n (stop-follow!)\n (swap! world assoc :pos (norm (:jam-at p)) :auto false :prev-pos nil)\n (perform id)))\n\n(declare show-leave-dialog! hide-leave-dialog!)\n\n(defn end-perform!\n \"Leaves Perform (and the jam): returns the take as it was.\"\n []\n (let [st @perf]\n (when-let [f @jam-unsub] (f) (reset! jam-unsub nil))\n (when-let [path (:jam-path st)]\n (when @dbref\n (enqueue! path (fn [] (.delete (.doc @dbref path))))\n (let [lp (str path \"-live\")] (enqueue! lp (fn [] (.delete (.doc @dbref lp)))))))\n (when-let [t @live-timer] (js/clearTimeout t) (reset! live-timer nil))\n (reset! live-buf [])\n (reset! live-seen {})\n (reset! perf nil)\n (hide-leave-dialog!)\n (publish-presence!)\n st))\n\n(defn write-take!\n \"Writes the changes of a take since its last snapshot as a new segment from where it starts, closed by\n `mark`; returns the position after it.\"\n [st mark]\n (let [evs (vec (map :ev (perf-events st))) origin (:origin st)\n id (new-node! (first origin) (if origin (second origin) 0) (conj evs mark) nil)]\n [id (inc (count evs))]))\n\n(defn compose\n \"Back to Compose. (compose) asks what to do with the take, if it has changes; (compose :keep) writes it\n into the history as a new point, a branch from where it started; (compose :discard) drops it and goes\n back to where you were before performing.\"\n ([] (when-not @perf (fail \"You are already in Compose.\"))\n (if (pos? (:changes (take-summary @perf)))\n (do (show-leave-dialog!) :choose)\n (compose :discard)))\n ([how]\n (when-not @perf (fail \"You are already in Compose.\"))\n (case how\n :keep (let [n (:changes (take-summary @perf))\n st (end-perform!)]\n (if (pos? n)\n (let [tip (write-take! st [:mark {:kind :take}])]\n (swap! world assoc :pos tip :auto true :prev-pos nil)\n {:kept n :at (moment-name tip)})\n (do (swap! world assoc :pos (:origin st) :prev-pos nil) {:kept 0})))\n :discard (let [st (end-perform!) from (:from st)]\n (swap! world assoc :pos from :auto (if from (leaf? from) true) :prev-pos nil)\n {:back-to (moment-name from)})\n (fail \"Use (compose), (compose :keep) or (compose :discard).\"))))\n\n(defn snapshot\n \"A keyframe: a point of the history with the work as it is now, in Compose or in Perform (where the take\n so far is written, and goes on from there). (snapshot \\\"intro\\\") names it.\"\n ([] (snapshot nil))\n ([label]\n (let [fronts (followed-fronts)\n ;; where the lines it follows are, so this point plays them as they are now (#117, decision 5)\n mark [:mark (cond-> {:kind :snapshot} (some? label) (assoc :label (str label)) (seq fronts) (assoc :fronts fronts))]]\n (if-let [st @perf]\n (let [evs (perf-events st)\n tip (write-take! st mark)]\n ;; the take goes on from the snapshot: what it had is now in the history\n (swap! perf (fn [s] (assoc s :origin tip :base (:patch s) :redo []\n :cut (reduce max (or (:cut s) 0) (map :t evs)))))\n (swap! world assoc :pos tip :auto false :prev-pos nil)\n {:snapshot (moment-name tip) :changes (count evs)})\n (do (dispatch! mark) (here))))))\n\n;; ───── interface: the mode button, what the take has, leaving it, invitations ─────\n\n(defn floating [id cls]\n (or ($ id)\n (let [el (js/document.createElement \"div\")]\n (set! (.-id el) id)\n (set! (.-className el) cls)\n (set! (.-hidden el) true)\n (.appendChild (.-body js/document) el)\n el)))\n\n(defn hide-leave-dialog! [] (when-let [el ($ \"perform-pop\")] (set! (.-hidden el) true)))\n\n(defn show-leave-dialog! []\n (let [st @perf {:keys [changes layout work]} (take-summary st) el (floating \"perform-pop\" \"perform-pop\")]\n (set! (.-innerHTML el)\n (str \"<p><b>Back to Compose</b> · this take has \" changes (if (= 1 changes) \" change\" \" changes\")\n \" (\" work \" to the work, \" layout \" of layout)\"\n (when (:jam st) \" — the whole jam, everyone's changes\") \".</p>\"\n \"<div class=\\\"pp-actions\\\">\"\n \"<button class=\\\"act primary\\\" data-perf=\\\":keep\\\" title=\\\"A new point of the history, as a branch from \"\n (esc (moment-name (:origin st))) \"\\\">Keep it as a new point</button>\"\n \"<button class=\\\"act\\\" data-perf=\\\":discard\\\">Discard: back to \" (esc (moment-name (:from st))) \"</button>\"\n \"<button class=\\\"act\\\" data-perf=\\\"stay\\\">Keep performing</button>\"\n \"</div>\"))\n (set! (.-hidden el) false)))\n\n(defn render-perform! []\n (let [st @perf on (boolean st) b ($ \"perform-toggle\") info ($ \"perform-info\")]\n (.toggle (.-classList (.-body js/document)) \"performing\" on)\n (when b\n (.toggle (.-classList b) \"on\" on)\n (set! (.-title b) (if on\n \"Back to Compose: keep the take as a new point of the history, or discard it\"\n \"Perform: rehearse, try and improvise outside the history (in a shared room, a jam with whoever performs from the same point)\")))\n (when info\n (set! (.-hidden info) (not on))\n (when on\n (let [{:keys [changes]} (take-summary st) n (count (jam-mates))]\n (set! (.-textContent info)\n (str \"from \" (moment-name (:origin st)) \" · \" changes (if (= 1 changes) \" change\" \" changes\")\n (when (:jam st) (str \" · jam\" (if (pos? n) (str \" with \" n) \", alone for now\"))))))))\n (when-not on (hide-leave-dialog!))))\n\n(defn render-jam-invite! []\n (let [offer (when-not @perf\n (first (filter (fn [p] (and (:jam p) (not (:same p)) (same-line? p) (not (contains? @jam-seen (:jam p))))) @peers)))\n el (floating \"jam-invite\" \"jam-invite\")]\n (if-not offer\n (set! (.-hidden el) true)\n (let [who (if (:me offer) \"You, in another tab,\" (or (not-empty (get-in @profiles [(:by offer) :name])) \"Someone\"))\n at (if (and (:jam-at offer) (node (first (:jam-at offer)))) (moment-name (:jam-at offer)) \"a point of the history\")]\n (set! (.-innerHTML el)\n (str \"<p><b>\" (esc who) \"</b> is performing from \" (esc at) \". Jam together from there?</p>\"\n \"<div class=\\\"pp-actions\\\">\"\n \"<button class=\\\"act primary\\\" data-jam=\\\"\" (esc (:jam offer)) \"\\\">Jam together</button>\"\n \"<button class=\\\"act\\\" data-jam-no=\\\"\" (esc (:jam offer)) \"\\\">Not now</button>\"\n \"</div>\"))\n (set! (.-hidden el) false)))))\n\n(.addEventListener (floating \"perform-pop\" \"perform-pop\") \"click\"\n (fn [e]\n (when-let [a (.. e -target -dataset -perf)]\n (if (= a \"stay\") (hide-leave-dialog!) (gesture! (str \"(compose \" a \")\"))))))\n\n(.addEventListener (floating \"jam-invite\" \"jam-invite\") \"click\"\n (fn [e]\n (let [ds (.. e -target -dataset)]\n (cond\n (.-jam ds) (do (swap! jam-seen conj (.-jam ds)) (gesture! (str \"(jam \" (pr-str (.-jam ds)) \")\")))\n (.-jamNo ds) (do (swap! jam-seen conj (.-jamNo ds)) (render-jam-invite!))))))\n\n(when-let [b ($ \"perform-toggle\")]\n (.addEventListener b \"click\" (fn [_] (gesture! (if @perf \"(compose)\" \"(perform)\")))))\n\n(when-let [b ($ \"snap-btn\")]\n (.addEventListener b \"click\" (fn [_] (gesture! \"(snapshot)\"))))\n\n(add-watch perf ::render (fn [_ _ _ _] (render-all!) (render-perform!) (render-jam-invite!)))\n(add-watch peers ::perform (fn [_ _ _ _] (render-perform!) (render-jam-invite!)))\n;; another work opened: the take of the one before is left behind\n(add-watch work ::perform (fn [_ _ o n] (when (and @perf (not= (select-keys o [:kind :id]) (select-keys n [:kind :id]))) (end-perform!))))\n\n(render-perform!)\n","page/14-editor.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 15 of 15: the code editor\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── the code editor (issue #8) ─────────────────────────\n;; The code of a box (faust~, script, component, tree) is written in a window of its own, over the page:\n;; it can be moved by its bar and resized by its corner, and it stays open while you play. Inside is\n;; CodeMirror 6 (core/vendor/codemirror.mjs, bundled from core/vendor/codemirror/): line numbers, automatic\n;; indentation, matching and closing brackets, structural editing for Clojure, search, and completion of\n;; the names each language knows. Ctrl/⌘+Enter applies the code (one event of the history) and keeps the\n;; window open, to go on; Esc or × closes it, asking first if something is not applied.\n;; If the editor cannot be loaded, a plain text area does the same.\n;; The same window opens the data of a canvas, freqt or score as EDN (discussion #30: { } in its header,\n;; or a double-click on the right of it): applying it writes what changed as one event of the history.\n;; The code of a faust~ also opens as a patch of Faust's own elements, beside it (discussion #115, Study\n;; 31, @kairotic/faust-units): editing the patch rewrites the code in the editor, editing the code redraws\n;; the patch, and applying is still one event. The window opens beside the box, so the parameters the box\n;; shows in the patch stay in sight while you play them.\n\n(defonce code-win (atom nil)) ; {:id :path :lang :data? :ed :original :dirty :confirm :error :fv}\n(defonce cm-module (atom nil)) ; Promise of the bundle\n\n(defn open-definition\n \"[path id] of the component box open in the code window, or nil.\"\n [] (when-let [w @code-win] (when (= \"component\" (:lang w)) [(:path w) (:id w)])))\n\n(defn code-win-box\n \"The box whose code is open in the editor (in the patch on screen), or nil.\"\n [] (when-let [w @code-win] (when (= (:path w) (cmd-path)) (:id w))))\n\n(defn load-cm []\n (or @cm-module\n (reset! cm-module\n (-> ((.-kairoticImport js/window) \"kairotic/vendor/codemirror.mjs\")\n (.catch (fn [e] (js/console.warn \"code editor: a plain text area instead\" e) nil))))))\n\n;; ───── what completion offers, by language ─────\n\n(def faust-words\n [\"process\" \"import(\\\"stdfaust.lib\\\");\" \"declare\" \"with\" \"letrec\" \"environment\" \"hslider\" \"vslider\" \"nentry\"\n \"button\" \"checkbox\" \"hgroup\" \"vgroup\" \"tgroup\" \"hbargraph\" \"vbargraph\" \"attach\" \"mem\" \"min\" \"max\" \"abs\"\n \"os.osc\" \"os.sawtooth\" \"os.square\" \"os.triangle\" \"os.phasor\" \"os.lf_saw\" \"os.pulsetrain\" \"os.oscsin\"\n \"no.noise\" \"no.pink_noise\" \"fi.lowpass\" \"fi.highpass\" \"fi.resonlp\" \"fi.resonhp\" \"fi.resonbp\" \"fi.bandpass\"\n \"fi.dcblocker\" \"fi.zero\" \"fi.pole\" \"ve.moog_vcf\" \"ve.korg35LPF\" \"en.adsr\" \"en.ar\" \"en.asr\" \"en.adsre\"\n \"de.delay\" \"de.fdelay\" \"de.sdelay\" \"re.mono_freeverb\" \"re.stereo_freeverb\" \"re.zita_rev1_stereo\"\n \"ef.echo\" \"ef.cubicnl\" \"co.compressor_mono\" \"co.limiter_1176_R4_mono\" \"si.smoo\" \"si.smooth\" \"si.bus\"\n \"si.block\" \"ba.db2linear\" \"ba.linear2db\" \"ba.midikey2hz\" \"ba.hz2midikey\" \"ba.beat\" \"ba.pulse\" \"ba.if\"\n \"ba.selectn\" \"ma.SR\" \"ma.PI\" \"ma.EPSILON\" \"sp.panner\" \"pm.ks\" \"aa.tanh1\"])\n\n(def tree-words\n [\":voice\" \":measure\" \":section\" \":seq\" \":par\" \":piece\" \":chord\" \":note\" \":rest\" \":tuplet\" \":rtm\" \":shares\"\n \":pitches\" \":meter\" \":groups\" \":dur\"\n \":pitch\" \":tempo\" \":key\" \":dyn\" \":defs\" \":use\" \":vel\" \":ties\"])\n\n(def buffer-words\n (into [\":strokes\" \":gx\" \":gy\" \":ax\" \":step\" \":cycles\" \":name\" \":ref\" \":cents\" \":x\" \":y\" \":lo\" \":hi\" \":log\"]\n (map pr-str (sort (keys cv/tunings)))))\n\n(def component-words\n [\":class\" \":doc\" \":usage\" \":license\" \":io\" \":args\" \":receive\" \":view\" \":derive\" \":draw\" \":gesture\"\n \":persist\" \":size\" \":audio\" \":patch\" \":params\" \":model\" \":state\" \":value\" \":inlet\" \":out\" \":show\"\n \":effects\" \":later\" \":display\"])\n\n(defn ns-names\n \"The public names of a namespace, written with a prefix (\\\"api/clamp\\\"), when this runtime knows them.\"\n [ns-sym prefix]\n (try (vec (sort (map (fn [s] (str prefix s)) (keys (ns-publics ns-sym))))) (catch :default _ [])))\n\n(defn words-for [lang]\n (case lang\n \"faust\" faust-words\n \"edn\" tree-words\n \"component\" (vec (concat component-words (ns-names 'kairotic.api \"api/\") (ns-names 'clojure.core \"\")))\n \"clojurescript\" (vec (concat (ns-names 'clojure.core \"\") (ns-names 'clojure.string \"str/\")))\n \"pbind\" [\"#pat/seq\" \"#pat/choose\" \"#pat/shuffle\" \"#pat/white\" \"#pat/walk\" \"#pat/series\" \"#pat/hold\" \"#pat/chord\"\n \":degree\" \":note\" \":freq\" \":dur\" \":legato\" \":sustain\" \":amp\" \":scale\" \":root\" \":octave\" \":transpose\" \":rest\"]\n \"pattern\" (vec (concat (map str kairotic.patterns/code-names) (ns-names 'clojure.core \"\")))\n []))\n\n;; ───── the window ─────\n\n(defn cw-el [] ($ \"code-win\"))\n\n(defn cw-status!\n \"The foot of the window: whether the code is applied, and how its compilation went.\"\n []\n (when-let [{:keys [id dirty gone lang data? error]} @code-win]\n (when-let [el (.querySelector (cw-el) \".cw-foot\")]\n (let [b (when-not gone (get-in (patch-in (root-patch) (:path @code-win)) [:boxes id]))\n r (cond error {:status :error :error error}\n (and b (not data?)) (cbox/compiled lang (str (get-in b [:data :source]))))\n comp-st (case (:status r)\n :ok (str \"✓ \" (or (get-in r [:info :summary]) \"ready\"))\n :compiling \"compiling…\"\n :error (str \"✗ \" (first (str/split-lines (str (:error r)))))\n \"\")]\n (set! (.-className el) (str \"cw-foot\" (when (= :error (:status r)) \" err\")))\n (set! (.-textContent el)\n (cond gone (if (= \"component\" lang)\n \"This component is not in the work any more: copy what you need, then close.\"\n \"This box is not in the patch any more: copy what you need, then close.\")\n error (str \"✗ \" (first (str/split-lines (str error))))\n dirty (str \"edited · Ctrl/⌘+Enter applies\" (when (seq comp-st) (str \" · last applied: \" comp-st)))\n :else (str \"applied\" (when (seq comp-st) (str \" · \" comp-st)))))))))\n\n(defn cw-text [] (when-let [w @code-win] (if (:ed w) (.getValue (:ed w)) (.-value (:ta w)))))\n\n(defn wrap-path\n \"A call made in the sub-patch `path`, written from the patch on screen: (inside :b5 …) for each step down.\"\n [path code]\n (let [here (cmd-path)]\n (when-not (= here (vec (take (count here) path)))\n (fail \"That code belongs to a patch that is not on screen: go back to it to apply it.\"))\n (reduce (fn [c id] (str \"(inside \" id \" \" c \")\")) code (reverse (drop (count here) path)))))\n\n(defn apply-code! []\n (when-let [{:keys [id path original gone data?]} @code-win]\n (let [v (cw-text)]\n (cond\n gone nil\n (= v original) (do (swap! code-win assoc :dirty false :error nil) (cw-status!))\n (str/blank? v) (repl-print! \"err\" \"; the code is empty: write something, or delete the box\")\n :else (let [before @recent-errors\n _ (gesture! (wrap-path path (str \"(code \" id \" \" (pr-str v) \")\")))\n err (when-not (identical? before @recent-errors) (last @recent-errors))]\n (if err\n ;; what cannot be read is not applied: it stays here, edited, saying what is wrong\n (swap! code-win assoc :error (str \"not applied: \" err))\n (swap! code-win assoc :original v :dirty false :error nil))\n (cw-status!))))))\n\n(defn close-code-win! []\n (when-let [w @code-win]\n (when-let [fv (:fv w)] (.destroy fv))\n (when-let [c (:rcp w)] (.abort c))\n (when-let [ed (:ed w)] (.destroy ed))\n (when-let [el (cw-el)] (.remove el))\n (reset! code-win nil)\n (render-scene (current))))\n\n(defn ask-close! []\n (if (and (:dirty @code-win) (not (:gone @code-win)))\n (do (swap! code-win assoc :confirm true)\n (when-let [c (.querySelector (cw-el) \".cw-confirm\")] (set! (.-hidden c) false)))\n (close-code-win!)))\n\n(defn place-window!\n \"Over the box, inside the window of the browser; a wide one (a faust~ with its patch) beside the box,\n so that what the box shows in the patch (its parameters) stays in sight.\"\n ([el id b] (place-window! el id b false))\n ([el id b wide?]\n (let [r (when-let [g (.querySelector js/document (str \"#scene .box[data-box=\\\"\" (name id) \"\\\"]\"))] (.getBoundingClientRect g))\n vw (.-innerWidth js/window) vh (.-innerHeight js/window)\n ;; a wide one goes where it covers nothing of the box: beside it (on the side with more room, as\n ;; wide as that room) if a side has 560 px, else below or above it if there are 280, else beside\n ;; it if a side has 400; and over it as the others only when nothing else fits\n right-room (when r (- vw 16 (.-right r) 12)) left-room (when r (- (.-left r) 12 16))\n below-room (when r (- vh 16 (.-bottom r) 12)) above-room (when r (- (.-top r) 12 16))\n side-room (when r (max right-room left-room)) vert-room (when r (max below-room above-room))\n place (when (and wide? r)\n (cond (>= side-room 560) (if (>= right-room left-room) :right :left)\n (>= vert-room 280) (if (>= below-room above-room) :below :above)\n (>= side-room 400) (if (>= right-room left-room) :right :left)))\n w (case place\n :right (min 1040 right-room) :left (min 1040 left-room)\n (min (if wide? 1040 620) (- vw 32)))\n h (case place\n :below (min 520 below-room) :above (min 520 above-room)\n (min (if wide? 520 420) (- vh 32)))\n [x y] (case place\n :right [(+ (.-right r) 12) (.-top r)]\n :left [(- (.-left r) 12 w) (.-top r)]\n :below [(.-left r) (+ (.-bottom r) 12)]\n :above [(.-left r) (- (.-top r) 12 h)]\n [(if r (.-left r) 40) (if r (+ (.-top r) hdr) 80)])]\n (set! (.. el -style -width) (str w \"px\"))\n (set! (.. el -style -height) (str h \"px\"))\n (set! (.. el -style -left) (str (max 16 (min x (- vw w 16))) \"px\"))\n (set! (.. el -style -top) (str (max 16 (min y (- vh h 16))) \"px\")))))\n\n(defn drag-window!\n \"The window moves with its bar.\"\n [el e]\n (when-not (.closest (.-target e) \"button\")\n (.preventDefault e)\n (let [x0 (.-clientX e) y0 (.-clientY e)\n l0 (.-offsetLeft el) t0 (.-offsetTop el)\n move (fn [ev]\n (set! (.. el -style -left) (str (max 0 (min (- (.-innerWidth js/window) 80) (+ l0 (- (.-clientX ev) x0)))) \"px\"))\n (set! (.. el -style -top) (str (max 0 (min (- (.-innerHeight js/window) 40) (+ t0 (- (.-clientY ev) y0)))) \"px\")))\n up (fn up [_]\n (.removeEventListener js/window \"pointermove\" move)\n (.removeEventListener js/window \"pointerup\" up))]\n (.addEventListener js/window \"pointermove\" move)\n (.addEventListener js/window \"pointerup\" up))))\n\n(declare toggle-patch-view! toggle-recipe! find-recipe-click! find-recipe! play-recipe!)\n\n(defn window-shell [id b lang]\n (let [el (js/document.createElement \"div\")]\n (set! (.-id el) \"code-win\")\n (set! (.-className el) \"code-win\")\n (.setAttribute el \"role\" \"dialog\")\n (.setAttribute el \"aria-label\" (str \"Code of \" (name id)))\n (set! (.-innerHTML el)\n (str \"<div class=\\\"cw-bar\\\"><span class=\\\"cw-title\\\"><b>\" (esc (name id)) \"</b> \"\n (esc (if (definition? b)\n (let [c (get-in (cbox/compiled \"component\" (str (get-in b [:data :source]))) [:info :class])]\n (str \"component\" (when c (str \" · \" c))))\n (:text b)))\n \"</span>\"\n \"<span class=\\\"cw-lang\\\">\" (esc lang) \"</span>\"\n (when (= lang \"faust\")\n (str \"<button class=\\\"act cw-pv\\\" data-cw=\\\"patch\\\" aria-pressed=\\\"\" (not (false? (:faust-patch? @ui)))\n \"\\\" title=\\\"Show or hide its patch: the code as Faust's own elements\\\">Patch</button>\"\n \"<button class=\\\"act cw-pv\\\" data-cw=\\\"recipe\\\" aria-pressed=\\\"false\\\"\"\n \" title=\\\"Find the values of its sliders that sound closest to a sound: a recipe\\\">Recipe</button>\"))\n \"<button class=\\\"act primary\\\" data-cw=\\\"apply\\\" title=\\\"Apply the code (Ctrl/⌘+Enter)\\\">Apply</button>\"\n \"<button class=\\\"act cw-x\\\" data-cw=\\\"close\\\" title=\\\"Close (Esc)\\\" aria-label=\\\"Close\\\">×</button></div>\"\n \"<div class=\\\"cw-confirm\\\" hidden>Something is not applied. \"\n \"<button class=\\\"act primary\\\" data-cw=\\\"apply-close\\\">Apply and close</button>\"\n \"<button class=\\\"act\\\" data-cw=\\\"discard\\\">Discard</button>\"\n \"<button class=\\\"act\\\" data-cw=\\\"stay\\\">Keep editing</button></div>\"\n (when (= lang \"faust\")\n (str \"<div class=\\\"cw-rcp\\\" hidden><label>Sliders that sound like <select class=\\\"rcp-src\\\"></select></label>\"\n \"<select class=\\\"rcp-len\\\" title=\\\"How long it listens\\\"><option value=\\\"quick\\\">quick</option>\"\n \"<option value=\\\"careful\\\">careful</option></select>\"\n \"<button class=\\\"act primary\\\" data-cw=\\\"find\\\">Find</button>\"\n \"<span class=\\\"rcp-st\\\" aria-live=\\\"polite\\\"></span>\"\n \"<button class=\\\"act rcp-play\\\" data-cw=\\\"play-target\\\" hidden title=\\\"The sound it listened to (its first second)\\\">▶ sound</button>\"\n \"<button class=\\\"act rcp-play\\\" data-cw=\\\"play-found\\\" hidden title=\\\"The code at the values found\\\">▶ found</button>\"\n \"<input type=\\\"file\\\" accept=\\\"audio/*\\\" class=\\\"rcp-file\\\" hidden></div>\"))\n \"<div class=\\\"cw-body\\\"></div><div class=\\\"cw-foot\\\"></div>\"))\n (.addEventListener (.querySelector el \".cw-bar\") \"pointerdown\" (fn [e] (drag-window! el e)))\n (.addEventListener el \"click\"\n (fn [e]\n (case (some-> (.closest (.-target e) \"[data-cw]\") (.getAttribute \"data-cw\"))\n \"apply\" (apply-code!)\n \"patch\" (toggle-patch-view!)\n \"recipe\" (toggle-recipe!)\n \"find\" (find-recipe-click!)\n \"play-target\" (play-recipe! :target)\n \"play-found\" (play-recipe! :found)\n \"close\" (ask-close!)\n \"apply-close\" (do (apply-code!) (when-not (:dirty @code-win) (close-code-win!)))\n \"discard\" (close-code-win!)\n \"stay\" (do (swap! code-win assoc :confirm false)\n (set! (.-hidden (.querySelector el \".cw-confirm\")) true)\n (some-> (:ed @code-win) .focus))\n nil)))\n (when-let [f (.querySelector el \".rcp-file\")]\n (.addEventListener f \"change\"\n (fn [_] (when-let [file (aget (.-files f) 0)]\n (set! (.-value f) \"\")\n (find-recipe! (.then (.arrayBuffer file) snd/decode) (.-name file))))))\n ;; keys typed in the editor are the editor's (space, Delete, ⌘A… do not reach the patch)\n (.addEventListener el \"keydown\" (fn [e] (.stopPropagation e)))\n el))\n\n(defn textarea-editor!\n \"Without CodeMirror: a plain text area with the same keys.\"\n [body text]\n (let [ta (js/document.createElement \"textarea\")]\n (set! (.-className ta) \"cw-plain\")\n (set! (.-spellcheck ta) false)\n (set! (.-value ta) text)\n (.appendChild body ta)\n (.addEventListener ta \"input\" (fn [_] (swap! code-win assoc :dirty (not= (.-value ta) (:original @code-win)) :error nil) (cw-status!)\n (when-let [fv (:fv @code-win)] (.setCode fv (.-value ta)))))\n (.addEventListener ta \"keydown\"\n (fn [e]\n (let [k (.-key e)]\n (cond\n (and (= k \"Enter\") (or (.-ctrlKey e) (.-metaKey e))) (do (.preventDefault e) (apply-code!))\n (= k \"Escape\") (do (.preventDefault e) (ask-close!))\n (= k \"Tab\") (do (.preventDefault e)\n (let [a (.-selectionStart ta) z (.-selectionEnd ta) v (.-value ta)]\n (set! (.-value ta) (str (subs v 0 a) \" \" (subs v z)))\n (set! (.-selectionStart ta) (+ a 2))\n (set! (.-selectionEnd ta) (+ a 2))))))))\n (.focus ta)\n ta))\n\n(declare open-code-editor-at!)\n\n;; ───── the patch of a faust~ (@kairotic/faust-units) ─────\n\n(defn set-editor-text!\n \"Code the patch view wrote, into the editor: edited, not applied yet.\"\n [v]\n (when-let [{:keys [ed ta]} @code-win]\n (cond ed (.setValue ed v) ta (set! (.-value ta) v))\n (swap! code-win assoc :dirty (not= v (:original @code-win)) :error nil)\n (cw-status!)))\n\n(defn mount-faust-view!\n \"Draws the patch of the faust~ open in the window, in `pane`, once its module is loaded.\"\n [id pane text]\n (-> (api/import-module (lib/module-origins \"@kairotic/faust-units\" \"view.mjs\"))\n (.then (fn [m]\n (when (and @code-win (= id (:id @code-win)) (nil? (:fv @code-win)))\n (let [w @code-win\n fv ((.-mount m) pane #js {:code (if (or (:ed w) (:ta w)) (cw-text) text)\n :onCode (fn [c] (set-editor-text! c))\n :loadFaust (fn [] (kairotic.faust/load))})]\n (swap! code-win assoc :fv fv)))))\n (.catch (fn [e]\n (set! (.-innerHTML pane) (str \"<p class=\\\"cw-pv-err\\\">The patch could not be loaded: \" (esc (or (.-message e) e)) \"</p>\"))))))\n\n(defn toggle-patch-view!\n \"Shows or hides the patch beside the code of a faust~ (remembered for the next ones).\"\n []\n (when-let [body (some-> (cw-el) (.querySelector \".cw-body.split\"))]\n (let [show? (.contains (.-classList body) \"nopatch\")]\n (.toggle (.-classList body) \"nopatch\" (not show?))\n (swap! ui assoc :faust-patch? show?)\n (some-> (cw-el) (.querySelector \"[data-cw=patch]\") (.setAttribute \"aria-pressed\" (str show?))))))\n\n;; ───── the recipe of a faust~ (discussion #114, Study 35, @kairotic/faust-units) ─────\n;; The values of the sliders of the code in the editor that sound closest to a sound: the sound of a\n;; sample box of this patch, or a file. The code is compiled and played offline, a note of a second (a\n;; gate button, if it has one, held for 0.65 s), many times: a few random settings first, then a search\n;; that listens as features~ does (Meyda), the pitch heard apart (YIN, as pitch~) and held. What it finds\n;; is written in the editor, the sliders starting at those values: edited, not applied, so applying it is\n;; one event of the history and the box keeps its parameters in sight.\n\n(def recipe-meyda \"npm:meyda@5.6.3/dist/web/meyda.min.js\")\n(def recipe-lengths {\"quick\" {:bank 32 :budget 160} \"careful\" {:bank 64 :budget 400}})\n(defonce recipe-sounds (atom nil)) ; {:target Float32Array :found Float32Array} of the last search\n\n(defn rcp-el [sel] (some-> (cw-el) (.querySelector (str \".cw-rcp \" sel))))\n\n(defn rcp-status! [text & [err?]]\n (when-let [el (rcp-el \".rcp-st\")]\n (set! (.-textContent el) text)\n (set! (.-className el) (str \"rcp-st\" (when err? \" err\")))))\n\n(defn recipe-sources\n \"The sample boxes with a sound in the patch of the code window: [[id seconds] …], in the order of their ids.\"\n []\n (when-let [{:keys [path]} @code-win]\n (->> (:boxes (patch-in (root-patch) path))\n (filter (fn [[_ b]] (and (= \"sample\" (klass (:text b))) (snd/sample? (:data b)))))\n (map (fn [[id b]] [id (snd/seconds (:data b))]))\n (sort-by (fn [[id _]] (js/parseInt (subs (name id) 1) 10))))))\n\n(defn fill-recipe-sources! []\n (when-let [sel (rcp-el \".rcp-src\")]\n (let [was (.-value sel)]\n (set! (.-innerHTML sel)\n (str (str/join (for [[id secs] (recipe-sources)]\n (str \"<option value=\\\"\" (esc (name id)) \"\\\">\" (esc (name id)) \" · \"\n (.toFixed secs 1) \" s</option>\")))\n \"<option value=\\\"file\\\">a sound file…</option>\"))\n (when (some #(= was (.-value %)) (array-seq (.-options sel))) (set! (.-value sel) was)))))\n\n(defn toggle-recipe!\n \"Shows or hides the recipe's line under the bar of a faust~'s window.\"\n []\n (when-let [p (some-> (cw-el) (.querySelector \".cw-rcp\"))]\n (let [show? (.-hidden p)]\n (set! (.-hidden p) (not show?))\n (when show? (fill-recipe-sources!))\n (some-> (cw-el) (.querySelector \"[data-cw=recipe]\") (.setAttribute \"aria-pressed\" (str show?))))))\n\n(defn find-recipe-click!\n \"Find: from the sound chosen (a file asks for it first); Stop while it listens.\"\n []\n (if-let [c (:rcp @code-win)]\n (.abort c)\n (let [v (some-> (rcp-el \".rcp-src\") .-value)]\n (cond\n (or (nil? v) (= v \"file\")) (some-> (rcp-el \".rcp-file\") .click)\n :else (let [b (get-in (patch-in (root-patch) (:path @code-win)) [:boxes (keyword v)])]\n (if (snd/sample? (:data b))\n (find-recipe! (snd/sound-for (:data b)) v)\n (rcp-status! (str v \" has no sound any more\") true)))))))\n\n(defn find-recipe!\n \"Listens for the recipe of the code in the editor, the target being the promise of a sound ({:sr :chans}).\"\n [sound label]\n (when-let [{:keys [id path]} @code-win]\n (let [ctl (js/AbortController.)\n code (cw-text)\n {:keys [bank budget]} (get recipe-lengths (some-> (rcp-el \".rcp-len\") .-value) (get recipe-lengths \"quick\"))\n mine? (fn [] (and @code-win (= id (:id @code-win)) (= path (:path @code-win)) (identical? ctl (:rcp @code-win))))\n btn (rcp-el \"[data-cw=find]\")]\n (swap! code-win assoc :rcp ctl)\n (when btn (set! (.-textContent btn) \"Stop\"))\n (doseq [b (array-seq (.querySelectorAll (cw-el) \".rcp-play\"))] (set! (.-hidden b) true))\n (rcp-status! (str \"loading what listens to \" label \"…\"))\n (-> (js/Promise.all #js [(api/import-module (lib/module-origins \"@kairotic/faust-units\" \"recipe.mjs\"))\n (kairotic.faust/load)\n (api/load-script recipe-meyda)\n sound])\n (.then (fn [[m fx _ s]]\n (when-not (:chans s) (throw (js/Error. (str \"the sound of \" label \" is not in this browser\"))))\n (rcp-status! \"compiling…\")\n (.find m #js {:faust fx :code code :Meyda (.-Meyda js/window)\n :sound #js {:sr (:sr s) :chans (:chans s)}\n :bank bank :budget budget :signal (.-signal ctl)\n :onProgress (fn [phase done total best]\n (when (mine?)\n (rcp-status! (if (= phase \"bank\")\n (str \"listening to random settings \" done \"/\" total)\n (str \"searching \" done \"/\" total \" · distance \" (.toFixed best 2))))))})))\n (.then (fn [r]\n (when (mine?)\n (reset! recipe-sounds {:target (.-target r) :found (.-y r)})\n (doseq [b (array-seq (.querySelectorAll (cw-el) \".rcp-play\"))] (set! (.-hidden b) false))\n (let [p (.-pitch r)\n what (str \"distance \" (.toFixed (.-fx r) 2) \" (the nearest random setting: \" (.toFixed (.-nearestFx r) 2) \")\"\n (when (some? p) (str \" · pitch \" (api/midi-name (js/Math.round p)))))]\n (if (= (cw-text) code)\n (do (set-editor-text! (.-code r))\n (when-let [fv (:fv @code-win)] (.setCode fv (.-code r)))\n (rcp-status! (str \"found: \" what \" · in the code, Ctrl/⌘+Enter applies it\")))\n (rcp-status! (str \"found: \" what \", but the code changed meanwhile: not written\") true))))))\n (.catch (fn [e]\n (when (mine?)\n (if (= \"AbortError\" (.-name e))\n (rcp-status! \"stopped\")\n (rcp-status! (str \"✗ \" (or (.-message e) e)) true)))))\n (.finally (fn []\n (when (mine?)\n (swap! code-win dissoc :rcp)\n (when btn (set! (.-textContent btn) \"Find\")))))))))\n\n(defn play-recipe!\n \"Plays the sound the last search listened to (:target) or what it found (:found), once.\"\n [which]\n (when-let [y (get @recipe-sounds which)]\n (let [ac (eng/ctx) buf (.createBuffer ac 1 (.-length y) 44100) src (.createBufferSource ac)]\n (.copyToChannel buf y 0)\n (set! (.-buffer src) buf)\n (.connect src (.-destination ac))\n (.then (.resume ac) (fn [_] (.start src))))))\n\n(defn open-code-editor!\n \"Opens the code of a box in the editor window (or brings it back if it is the one open).\"\n [id] (open-code-editor-at! (cmd-path) id))\n\n(defn open-code-editor-at!\n \"Opens the code of box id of the sub-patch at path (from the patch the work starts at) in the editor\n window: a component box is not in the patch, so the Components tab opens it this way.\"\n [path id]\n (let [path (vec path) b (get-in (patch-in (root-patch) path) [:boxes id]) d (box-def b)]\n (cond\n (nil? b) nil\n (and @code-win (= id (:id @code-win)) (= path (:path @code-win))) (some-> (:ed @code-win) .focus)\n (and @code-win (:dirty @code-win) (not (:gone @code-win)))\n (do (ask-close!) (repl-print! \"out\" \"; first apply or discard the code that is open\"))\n :else\n (do\n (close-code-win!)\n (let [data? (fn? (:source (comp/model-of b)))\n lang (if data? \"edn\" (str (:language d)))\n original (str (comp/source-of b))\n text (if (and (not data?) (str/blank? original)) (or (:template d) \"\") original)\n el (window-shell id b lang)\n body (.querySelector el \".cw-body\")\n ;; a faust~: its patch on the left, the code on the right\n faust? (and (not data?) (= lang \"faust\"))\n pane (when faust? (js/document.createElement \"div\"))\n body (if faust?\n (let [t (js/document.createElement \"div\")]\n (set! (.-className body) (str \"cw-body split\" (when (false? (:faust-patch? @ui)) \" nopatch\")))\n (set! (.-className pane) \"cw-patch\")\n (set! (.-className t) \"cw-text\")\n (.appendChild body pane)\n (.appendChild body t)\n t)\n body)]\n (.appendChild (.-body js/document) el)\n (place-window! el id b faust?)\n (reset! code-win {:id id :path path :lang lang :data? data? :original original :dirty (not= text original)})\n (cw-status!)\n (render-scene (current))\n (when faust? (mount-faust-view! id pane text))\n (.then (load-cm)\n (fn [cm]\n (when (= (:id @code-win) id)\n (if-let [create (and cm (.-createEditor cm))]\n (let [ed (create #js {:parent body :doc text :language lang\n :words (clj->js (if data? buffer-words (words-for lang)))\n :onApply (fn [_] (apply-code!))\n :onCancel (fn [] (ask-close!))\n :onChange (fn [v] (swap! code-win assoc :dirty (not= v (:original @code-win)) :error nil) (cw-status!)\n (when-let [fv (:fv @code-win)] (.setCode fv v)))})]\n (swap! code-win assoc :ed ed)\n (.focus ed))\n (swap! code-win assoc :ta (textarea-editor! body text)))))))))))\n\n(defn refresh-code-win!\n \"After the patch changed: if the box is gone, say so; if its code changed elsewhere and nothing is\n edited here, show the new code.\"\n []\n (when-let [{:keys [id path ed ta dirty original]} @code-win]\n (let [b (get-in (patch-in (root-patch) path) [:boxes id])]\n (if (nil? b)\n (swap! code-win assoc :gone true)\n (let [src (str (comp/source-of b))]\n (swap! code-win assoc :gone false)\n (when (and (not dirty) (not= src original) (not (str/blank? src)))\n (swap! code-win assoc :original src)\n (cond ed (.setValue ed src) ta (set! (.-value ta) src))\n (when-let [fv (:fv @code-win)] (.setCode fv src))\n (swap! code-win assoc :dirty false))))\n (cw-status!))))\n\n(add-watch hist ::code-win (fn [_ _ _ _] (refresh-code-win!)))\n(add-watch perf ::code-win (fn [_ _ _ _] (refresh-code-win!)))\n(add-watch world ::code-win (fn [_ _ _ _] (refresh-code-win!)))\n\n;; ───────────────────────── the Code tab and the REPL line ─────────────────────────\n;; The same editor (CodeMirror, Clojure) replaces the text area of the Code tab and the input of the REPL\n;; once the bundle is loaded, a moment after the page starts. In the Code tab, Ctrl/⌘+Enter runs the code.\n;; In the REPL, Enter evaluates when the brackets are closed (otherwise it starts a new line; ⇧+Enter\n;; always does), and ↑ ↓ on the first or last line bring back what was written before.\n\n(defn command-words\n \"The commands of the page that have a doc string, for completion in the Code tab and the REPL.\"\n []\n (try (vec (sort (keep (fn [[s v]] (when (:doc (meta v)) (str s))) (ns-publics 'user))))\n (catch :default _ [])))\n\n(defn balanced?\n \"Whether every bracket of a piece of code is closed (outside strings, comments and characters).\"\n [s]\n (loop [cs (seq s) depth 0 in-str false]\n (if-let [c (first cs)]\n (cond\n in-str (case c \"\\\\\" (recur (nnext cs) depth true) \"\\\"\" (recur (next cs) depth false) (recur (next cs) depth true))\n (= c \"\\\"\") (recur (next cs) depth true)\n (= c \"\\\\\") (recur (nnext cs) depth false)\n (= c \";\") (recur (drop-while (fn [x] (not= x \"\\n\")) cs) depth false)\n (#{\"(\" \"[\" \"{\"} c) (recur (next cs) (inc depth) false)\n (#{\")\" \"]\" \"}\"} c) (recur (next cs) (dec depth) false)\n :else (recur (next cs) depth false))\n (and (<= depth 0) (not in-str)))))\n\n(defn host-for!\n \"A place for an editor next to element `el`, which hides: keys typed there stay there.\"\n [el cls]\n (let [h (js/document.createElement \"div\")]\n (set! (.-className h) cls)\n (.insertBefore (.-parentNode el) h el)\n (set! (.-hidden el) true)\n (.addEventListener h \"keydown\" (fn [e] (.stopPropagation e)))\n h))\n\n;; ───── the Code tab and the patch, seen together (issue #165) ─────\n;; Lines longer than 160 characters (the source of a code box, a buffer kept as data…) are folded after their\n;; first 48 characters, saying how many they hide; a click (or the fold gutter) shows them, and a line unfolded\n;; stays so while the tab is open. The lines of the boxes selected in the patch are marked, and the tab scrolls to\n;; them; the other way round, the cursor on a line of a box selects that box in the patch.\n\n(defonce code-unfolded (atom #{})) ; the lines unfolded by the person, by their beginning: \"(code :b7\"\n(defonce code-line-pick (atom false)) ; the selection comes from the cursor in the code: the tab does not scroll\n\n(defn line-key \"The beginning of a line of the code that names its box: \\\"(code :b7\\\", or nil.\" [text]\n (re-find #\"^\\([^\\s()]+ :b\\d+\" (str text)))\n\n(defn ids-in-line \"The box ids a line of code names, in order.\" [text]\n (map keyword (map (fn [m] (subs m 1)) (re-seq #\"(?<![\\w:-]):b\\d+(?![\\w-])\" (str text)))))\n\n(defn code-mark-lines!\n \"Marks the lines of the Code tab that name a box selected in the patch; returns their numbers.\"\n []\n (when-let [e @code-ed]\n (when (.-highlight e)\n (let [chosen (set (sel-ids))\n ls (if (empty? chosen) []\n (vec (keep-indexed (fn [i l] (when (some chosen (ids-in-line l)) (inc i)))\n (str/split-lines (.getValue e)))))]\n (.highlight e (clj->js ls))\n ls))))\n\n(defn code-tab-refresh!\n \"After the code of the tab is written again: long lines folded (not the ones unfolded), boxes marked.\"\n []\n (when-let [e @code-ed]\n (when (.-foldLong e) (.foldLong e 160 48 (fn [t] (contains? @code-unfolded (line-key t)))))\n (code-mark-lines!)))\n\n(defn code-line-chosen!\n \"The cursor went to a line of the Code tab: the boxes it names (one, or the two of a connect) are selected.\"\n [text]\n (let [p (current) ids (vec (distinct (filter (fn [id] (get-in p [:boxes id])) (ids-in-line text))))]\n (when (seq ids)\n (reset! code-line-pick true)\n (try (swap! ui assoc :sel (sel-of ids) :insp nil :nsel nil :tsel nil)\n (render-scene (current))\n (finally (reset! code-line-pick false)))\n ;; the patch shows the first one\n (some-> (.querySelector ($ \"scene\") (str \"g.box[data-box=\\\"\" (name (first ids)) \"\\\"]\"))\n (.scrollIntoView #js {:block \"nearest\" :inline \"nearest\"})))))\n\n;; the selection changed: its lines are marked, and the tab goes to them (unless the cursor chose them)\n(add-watch ui ::code-marks\n (fn [_ _ o n]\n (when (not= (:sel o) (:sel n))\n (let [ls (code-mark-lines!)]\n (when (and (seq ls) (not @code-line-pick) @code-ed (.-showLine @code-ed))\n (.showLine @code-ed (first ls)))))))\n\n(defn upgrade-code-tab! [cm]\n (when-not @code-ed\n (let [ta ($ \"code\") host (host-for! ta \"code-host\")\n ed ((.-createEditor cm)\n #js {:parent host :doc (.-value ta) :language \"clojurescript\" :words (clj->js (command-words))\n :onApply (fn [_] (run-panel-code!))\n :onChange (fn [_] (when-not (:dirty @ui) (swap! ui assoc :dirty true) (render-code (current))))\n :onLine (fn [_ text] (code-line-chosen! text))\n :onUnfold (fn [text] (when-let [k (line-key text)] (swap! code-unfolded conj k)))})]\n (.setAttribute (.-contentDOM (.-view ed)) \"aria-label\" \"Patch code\")\n (reset! code-ed ed)\n (code-tab-refresh!))))\n\n(defn upgrade-data-view!\n \"The Data view of the Code tab: the same editor, read-only, with EDN colours, folding and search.\"\n [cm]\n (when-not @data-ed\n (let [pre ($ \"edn\")\n host (host-for! pre \"data-host\")\n ed ((.-createEditor cm) #js {:parent host :doc (.-textContent pre) :language \"edn\" :readOnly true})]\n (.setAttribute (.-contentDOM (.-view ed)) \"aria-label\" \"The work as data (EDN)\")\n (reset! data-ed ed))))\n\n(defn upgrade-repl! [cm]\n (when-not @repl-ed\n (let [inp ($ \"repl-in\") host (host-for! inp \"repl-host\")\n ed (atom nil)\n free? (fn [] (not (.completing @ed)))]\n (reset! ed ((.-createEditor cm)\n #js {:parent host :doc (.-value inp) :language \"clojurescript\" :gutter false\n :placeholder (.-placeholder inp)\n :words (clj->js (concat (command-words) (ns-names 'clojure.core \"\")))\n :keys #js [#js {:key \"Enter\" :run (fn [] (when (and (free?) (balanced? (.getValue @ed))) (repl-submit!) true))}\n #js {:key \"Shift-Enter\" :run (fn [] (.newline @ed) true)}\n #js {:key \"ArrowUp\" :run (fn [] (boolean (and (free?) (= 1 (.cursorLine @ed)) (repl-recall! true))))}\n #js {:key \"ArrowDown\" :run (fn [] (boolean (and (free?) (= (.cursorLine @ed) (.lineCount @ed)) (repl-recall! false))))}]}))\n (.setAttribute (.-contentDOM (.-view @ed)) \"aria-label\" \"REPL\")\n (when-let [l (.querySelector js/document \"label[for=repl-in]\")]\n (.addEventListener l \"click\" (fn [_] (.focus @ed))))\n (reset! repl-ed @ed))))\n\n;; a moment after the page starts (not in an embed, which shows neither)\n(when-not embed-mode\n (js/setTimeout\n (fn [] (.then (load-cm) (fn [cm] (when cm (upgrade-code-tab! cm) (upgrade-data-view! cm) (upgrade-repl! cm)\n ;; the hosts take the place of what was shown: show again the view that was chosen\n (show-code-view! (or (:code-view @ui) :calls))))))\n 300))\n","page/15-presets.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 16 of 16: presets\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── presets from the keyframes of the history (issue #35) ─────────────────────────\n;; Every keyframe (◆ snapshot, or take kept from Perform) is a preset of the work: what it holds is the text\n;; of every box (kairotic.presets/configuration). A preset is recalled as one event that gives each box the\n;; text it had there; a morph moves the controls (boxes that keep their value in their text, a knob) between\n;; two presets as messages, as a drag does, until (morph :keep) writes them; a generated preset keeps what is\n;; the same in all of them and varies what changes, within its range. Everything acts on the whole work,\n;; wherever the view is, and in Perform it goes to the take, as any change does.\n\n(defn keyframes\n \"The keyframes of the history, in order of moment (the same order in every tab of a room):\n [{:n 1 :label \\\"intro\\\" :kind :snapshot :moment 4} …].\"\n []\n (->> (for [n (vals (:nodes @hist))\n [k ev] (map-indexed vector (:events n))\n :when (and (vector? ev) (= :mark (first ev)))\n :let [m (when (map? (second ev)) (second ev)) pos [(:id n) (inc k)]]]\n (cond-> {:kind (or (:kind m) :snapshot) :pos pos :moment (depth-of pos)}\n (seq (str (:label m))) (assoc :label (str (:label m)))))\n (sort-by (juxt :moment (fn [k] (str (first (:pos k))))))\n (map-indexed (fn [i k] (assoc k :n (inc i))))\n vec))\n\n(defn find-keyframe\n \"Keyframe `ref` among `kfs`: a number is its place in that list (1 = the first), a label the last one\n written with it.\"\n [kfs ref]\n (cond\n (number? ref) (or (when (integer? ref) (get kfs (dec ref)))\n (fail (str \"There is no keyframe \" ref \": there \" (if (= 1 (count kfs)) \"is 1\" (str \"are \" (count kfs))) \".\")))\n (or (string? ref) (keyword? ref))\n (or (last (filter (fn [k] (= (:label k) (name ref))) kfs))\n (fail (str \"No snapshot is called \" (pr-str (name ref)) \".\")))\n :else (fail \"A keyframe is a number (1 = the first) or the label of a snapshot.\")))\n\n(defn- need-history! []\n (when @scratch (fail \"Presets come from the history of a work.\"))\n (when (#{:connecting :none} (:mode @hist)) (fail \"Open a work first.\")))\n\n(defn- need-keyframes [kfs n]\n (when (< (count kfs) n)\n (fail (if (empty? kfs)\n \"There are no keyframes yet: ◆ Snapshot (or (snapshot \\\"name\\\")) keeps the work as it is now.\"\n (str \"That needs \" n \" keyframes, and there \" (if (= 1 (count kfs)) \"is 1\" (str \"are \" (count kfs))) \".\")))))\n\n(defn keyframe-config\n \"What a keyframe holds: the texts it keeps (a preset stored in a box: issue #45), or the work at its point.\"\n [k] (if (:texts k) (:texts k) (pst/configuration (patch-at (:pos k)))))\n(defn now-config [] (pst/configuration (work-patch)))\n\n(defn moment-label [k] (str \"keyframe \" (:n k) (when (:label k) (str \" (\" (:label k) \")\"))))\n\n(defn write-texts!\n \"Gives boxes of the work new texts ({engine-id text}), as one event of the history.\"\n [changes]\n (when (seq changes)\n (let [evs (vec (for [[f t] changes :let [path (pst/path-of f)]] (wrap-in (pop path) [:text (peek path) t])))]\n (dispatch-root! (if (= 1 (count evs)) (first evs) [:batch evs]))\n (doseq [t (vals changes)] (ensure-class! t))))\n changes)\n\n(defn control-values\n \"The values the controls among `texts` ({engine-id text}) keep: {engine-id value}.\"\n [texts]\n (into (sorted-map) (keep (fn [[f t]] (when-let [c (pst/control t)] [f (:v c)])) texts)))\n\n(declare presets-list)\n\n(defn presets-box\n \"A presets box of the work by its engine id (:b18, or :b5.b2 inside a sub-patch).\"\n [f] (or (get-in (eng/flat (engine-patch)) [:boxes f]) (fail (str \"There is no presets box \" f))))\n\n(defn recall\n \"Recalls a keyframe as a preset: every box of the work that is also there takes the text it had there (its\n arguments, and the values its controls keep), as one event. Boxes added or removed since, lines and\n buffers stay as they are. (recall 2) · (recall \\\"intro\\\") · (recall :b18 2), among the presets of that box.\"\n ([ref]\n (need-history!)\n (let [kfs (keyframes) _ (need-keyframes kfs 1)\n k (find-keyframe kfs ref)\n changes (pst/recall-changes (now-config) (keyframe-config k))]\n (write-texts! changes)\n {:recalled (moment-label k) :changed (count changes)}))\n ([f ref]\n (let [kfs (presets-list (presets-box f)) _ (need-keyframes kfs 1)\n k (find-keyframe kfs ref)\n changes (pst/recall-changes (now-config) (keyframe-config k))]\n (write-texts! changes)\n {:recalled (moment-label k) :changed (count changes)})))\n\n(defonce last-morph (atom {})) ; the values the last morph gave the controls: {engine-id value}\n\n(defn morph-with!\n \"Moves the controls between keyframes a and b at t, as messages (nothing is written): {engine-id value}.\"\n ([a b t] (morph-with! a b t #{}))\n ([a b t exclude]\n (let [vals (pst/morph-values (now-config) (keyframe-config a) (keyframe-config b) (max 0 (min 1 t)) exclude)]\n (doseq [[f v] vals]\n (try (inject-local! f 0 v) (catch :default e (js/console.error \"morph\" e))))\n (reset! last-morph vals)\n (when (seq vals) (render-overlay!))\n vals)))\n\n(defn morph\n \"Moves the controls (boxes that keep their value in their text, such as knobs) between two keyframes, as a\n drag does: (morph 1 2 0.5) is halfway. Nothing is written until (morph :keep), which keeps the values of\n the last morph in their texts, as one event.\"\n ([how]\n (when-not (= how :keep) (fail \"Use (morph a b t), or (morph :keep) to keep the last morph.\"))\n (need-history!)\n (let [changes (pst/keep-changes (now-config) @last-morph)]\n (write-texts! changes)\n (reset! last-morph {})\n {:kept (count changes)}))\n ([a b t]\n (need-history!)\n (when-not (number? t) (fail \"t is a number between 0 and 1: (morph 1 2 0.5).\"))\n (let [kfs (keyframes)]\n (need-keyframes kfs 1)\n (morph-with! (find-keyframe kfs a) (find-keyframe kfs b) t))))\n\n(defn generate\n \"A new preset from the keyframes: what is the same in all of them stays; a number that changes takes a value\n within its range (geometric in a box written with log, whole if it always was); a word that changes is one\n of theirs. Written as one event. (generate) · (generate 42), a seed: the same seed, the same preset ·\n (generate 42 [1 3]) from some keyframes only · (generate :b18 42) among the presets of that box.\"\n ([] (generate (js/Math.floor (* (js/Math.random) 1e9))))\n ([seed] (generate seed nil))\n ([x y]\n (let [box (when (keyword? x) x)\n seed (if box y x)\n refs (when-not box y)]\n (when-not box (need-history!))\n (when-not (number? seed) (fail \"The seed is a number: (generate 42).\"))\n (let [all (if box (presets-list (presets-box box)) (keyframes))\n kfs (if (seq refs) (mapv (fn [r] (find-keyframe all r)) refs) all)\n _ (need-keyframes kfs 2)\n changes (pst/generate-changes (now-config) (mapv keyframe-config kfs) (pst/rng seed))]\n (write-texts! changes)\n {:generated (count changes) :seed seed :from (mapv :n kfs)}))))\n\n;; ───── the presets box: what it asks for, done here ─────\n\n(defn stored-keyframes\n \"The presets a box keeps in its data, as keyframes: [{:n :label :kind :texts}].\"\n [b] (vec (map-indexed (fn [i p] (assoc p :n (inc i))) (get-in b [:data :presets]))))\n\n(defn presets-list\n \"The keyframes a presets box uses: the presets it keeps, if any (issue #45: they were chosen when they were\n kept), or, of the keyframes of the history, those its arguments name (numbers, labels), in that order, or all.\"\n [b]\n (let [stored (stored-keyframes b)]\n (if (seq stored)\n stored\n (let [_ (need-history!)\n all (keyframes)\n refs (map (fn [x] (if (keyword? x) (name x) x)) (comp/args-of (:text b)))]\n (if (seq refs) (mapv (fn [r] (find-keyframe all r)) refs) all)))))\n\n(defn presets!\n \"Keeps presets in a presets box: (presets! :b18 [{:label \\\"calm\\\" :texts {:b13 \\\"knob 0.5 50 2 log strobe\\\"}} …]).\n They are part of the patch: its code, links and embeds carry them. (presets! :b18 nil) forgets them.\"\n [id v]\n (let [b (need-box id)]\n (when-not (= \"presets\" (klass (:text b))) (fail (str id \" is not a presets box\")))\n (dispatch! [:in id (if (seq v) [:store v] [:clear])])\n (count (rel/sane-presets v))))\n\n(defn store-presets!\n \"Keeps in a presets box the keyframes it uses from the history (only what changes between them), so they\n travel with the patch: (store-presets! :b18).\"\n [id]\n (let [b (need-box id)]\n (when-not (= \"presets\" (klass (:text b))) (fail (str id \" is not a presets box\")))\n (need-history!)\n (let [kfs (presets-list (assoc b :data nil)) _ (need-keyframes kfs 1)\n v (rel/stored-presets (mapv (fn [k] (assoc k :config (keyframe-config k))) kfs))]\n (presets! id v))))\n\n(defn- emit-values! [f vals]\n (when (seq vals)\n (try (eng/emit! engine-patch f 0 vals) (catch :default e (js/console.error \"presets\" e)))))\n\n(defn presets-effect!\n \"What a presets box (engine id f) asked for: a recall and a generation are gestures of the work (written in\n the REPL, as any gesture); a morph moves the controls as messages.\"\n [f [_ [op & xs]] _]\n (js/setTimeout\n (fn []\n (try\n (let [b (or (get-in (eng/flat (engine-patch)) [:boxes f]) (fail \"the box is not in the work\"))\n kfs (presets-list b)\n own? (seq (stored-keyframes b))]\n (case op\n :recall (let [_ (need-keyframes kfs 1)\n k (find-keyframe kfs (first xs))\n changes (pst/recall-changes (now-config) (keyframe-config k))]\n (gesture! (if own? (str \"(recall \" f \" \" (:n k) \")\") (str \"(recall \" (:n k) \")\")))\n (emit-values! f (control-values changes)))\n :generate (let [_ (need-keyframes kfs 2)\n seed (or (first xs) (js/Math.floor (* (js/Math.random) 1e9)))\n now (now-config)\n changes (pst/generate-changes now (mapv keyframe-config kfs) (pst/rng seed))]\n (gesture! (if own?\n (str \"(generate \" f \" \" seed \")\")\n (str \"(generate \" seed (when (not= kfs (keyframes)) (str \" \" (pr-str (mapv :n kfs)))) \")\")))\n (emit-values! f (control-values changes)))\n :keep (gesture! \"(morph :keep)\")\n ;; a position on the right inlet: 1.5 is halfway from the first keyframe of the box to the second.\n ;; The controls upstream of the box (a knob that drives it) are left where they are.\n :morph-at (do (need-keyframes kfs 2)\n (let [[a b t] (pst/between (first xs) (count kfs))\n exclude (reaching (:lines (eng/flat (engine-patch))) #{f})]\n (emit-values! f (morph-with! (nth kfs (dec a)) (nth kfs (dec b)) t exclude))))\n :morph (let [[a b t] xs\n exclude (reaching (:lines (eng/flat (engine-patch))) #{f})]\n (emit-values! f (morph-with! (find-keyframe kfs a) (find-keyframe kfs b) t exclude)))\n nil))\n (catch :default e\n (repl-print! \"err\" (esc (str \"; presets \" (name f) \": \" (or (.-message e) e)))))))\n 0))\n\n;; the page receives the effects of boxes: presets here, the rest as before (03-history-view.cljs)\n(swap! eng/rt assoc :effect-hook\n (fn [f [k _ :as e] at] (if (= k :presets) (presets-effect! f e at) (tree-effect! f e at))))\n","page/16-release.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 17 of 17: release\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── release, and points of the history forgotten (issue #45) ─────────────────────────\n;; A release is a copy of the work with a compact history: one point per keyframe (its label kept), each\n;; written as the changes from the one before, then the work as it is, with every presets box keeping its\n;; presets (so they travel with the patch). The original work and its history are not touched.\n;; In a solo or local work, points of the history can be forgotten: the moments after them stay exactly as\n;; they were, and the work at those moments is lost. Branch points and the tip of a branch cannot be forgotten.\n\n;; ───── release ─────\n\n(defn- box-data-path\n \"Where the data of a box at engine id f is, inside the patch: :b5.b2 → [:boxes :b5 :data :boxes :b2 :data].\"\n [f] (vec (concat (mapcat (fn [id] [:boxes id :data]) (pst/path-of f)))))\n\n(defn with-stored-presets\n \"The patch with every presets box keeping its presets: those it keeps already, or the keyframes it uses.\"\n [p]\n (reduce (fn [p [f t]]\n (if (and (= \"presets\" (klass t)) (empty? (get-in p (conj (box-data-path f) :presets))))\n (let [b (get-in (eng/flat p) [:boxes f])\n kfs (try (presets-list (assoc b :data nil)) (catch :default _ nil))]\n (if (seq kfs)\n (assoc-in p (box-data-path f)\n {:presets (rel/stored-presets (mapv (fn [k] (assoc k :config (keyframe-config k))) kfs))})\n p))\n p))\n p (pst/configuration p)))\n\n(defn release-events\n \"The compact history of the work: for each keyframe (in order of moment) the changes from the one before and\n its mark, then the changes to the work as it is now (with its presets boxes keeping their presets).\"\n []\n (let [kfs (keyframes)\n ;; one line (#117): the lines its patch uses go inside it, each as it played at that point\n final (with-stored-presets (inline-lines (work-patch)))]\n (loop [prev empty-patch [k & more] kfs out []]\n (if k\n (let [[nid i] (:pos k)\n [op m] (nth (:events (node nid)) (dec i))\n p (inline-lines (patch-at (:pos k)) (:fronts m))\n e (rel/as-event (rel/patch-diff prev p))\n ;; its fronts were points of lines the release does not have\n mark [op (if (map? m) (dissoc m :fronts) m)]]\n (recur p more (cond-> out e (conj e) true (conj mark))))\n (let [e (rel/as-event (rel/patch-diff prev final))]\n (cond-> out e (conj e)))))))\n\n(defn history-size [] (reduce + 0 (map (fn [n] (count (:events n))) (vals (:nodes @hist)))))\n\n(defn release\n \"A release of the work: a new solo work (a local one without an account) with a compact history, one point\n per keyframe and then the work as it is, its presets boxes keeping their presets. The original stays as it\n is. (release) · (release \\\"name\\\").\"\n ([] (release nil))\n ([nm]\n (when @scratch (fail \"A release is made from a work.\"))\n (when (#{:connecting :none} (:mode @hist)) (fail \"Open a work first.\"))\n (when @perf (fail \"You are in Perform: (compose) first.\"))\n (let [evs (release-events)\n from (history-size)\n nm (str (or (not-empty (str nm)) (str (or (:name @work) \"Work\") \" · release\")))\n now (js/Date.now)\n origin (str (name (or (:kind @work) :local)) \":\" (:id @work))\n report {:release nm :points (count evs) :from from :keyframes (count (keyframes))}]\n (if (and @dbref (uid) (:writable @hist))\n (let [db @dbref\n ref (.doc (.collection db (coll-for :solo)))\n id (.-id ref)\n hcoll (str (coll-for :solo) \"/\" id \"/history\")\n hid (.-id (.doc (.collection db hcoll)))\n n {:id hid :parent nil :at 0 :author (my-author) :session session-id :t now :merge nil :events evs}]\n (-> (.set ref (clj->js {:name nm :created now :author (uid) :simultaneity_ms (:simul-ms @settings)\n :origin origin :release true}))\n (.then (fn [_] (.set (.doc db (str hcoll \"/\" hid)) (node->js n))))\n (.then (fn [_] (open-work! :solo id nm)))\n (.catch db-failed!))\n (assoc report :to :solo))\n (let [lid (str \"local-\" (.toString (js/Math.floor (* (js/Math.random) 2176782336)) 36) (.toString now 36))]\n (open-work! :local \"release\" nm)\n (reset! cache {})\n (swap! hist assoc :nodes {lid {:id lid :parent nil :at 0 :author (my-author) :session session-id :t now\n :merge nil :events evs}})\n (swap! world assoc :pos [lid (count evs)] :auto true :prev-pos nil)\n (render-all!)\n (assoc report :to :local))))))\n\n;; ───── forgetting points of the history ─────\n\n(defonce picked (atom #{})) ; points of the history chosen to be forgotten: #{[node-id k] …}\n\n(defn forget-allowed? [] (boolean (and (#{:solo :local} (:kind @work)) (not @perf) (not @lesson) (not @scratch))))\n\n(defn forget-blocker\n \"Why point [nid k] cannot be forgotten, or nil.\"\n [[nid k]]\n (let [n (node nid)]\n (cond\n (nil? n) \"it is not in the history\"\n (not (< 0 k (count (:events n)))) \"it is the tip of a branch, or its start\"\n (some (fn [c] (and (= (:parent c) nid) (= (:at c) k))) (vals (:nodes @hist))) \"a branch starts there\"\n (some (fn [c] (= (:merge c) [nid k])) (vals (:nodes @hist))) \"a merge brought it elsewhere\")))\n\n(defn- runs\n \"Consecutive numbers as [first last] runs: #{2 3 5} → [[2 3] [5 5]].\"\n [ks]\n (reduce (fn [acc k] (if (and (seq acc) (= k (inc (second (peek acc))))) (conj (pop acc) [(first (peek acc)) k]) (conj acc [k k])))\n [] (sort ks)))\n\n(defn- squash-node\n \"The events of node nid with the points `ks` forgotten, and how its old points map to the new ones.\"\n [nid ks]\n (let [evs (vec (:events (node nid)))\n rs (runs ks)\n ;; each run k1…k2: the events from k1 to k2+1 become the changes from the point before to the one after\n ;; (and the mark of that next point, if it is a keyframe, stays a point of its own)\n repl (into {} (for [[k1 k2] rs\n :let [diff (rel/as-event (rel/patch-diff (patch-at [nid (dec k1)]) (patch-at [nid (inc k2)])))\n nxt (nth evs k2)\n mark? (and (vector? nxt) (= :mark (first nxt)))]]\n [k1 {:to k2 :evs (vec (remove nil? (if mark? [diff nxt] [diff])))}]))\n [new-evs mapping]\n (loop [i 1 out [] m {0 0}]\n (if (> i (count evs))\n [out m]\n (if-let [{:keys [to] r :evs} (get repl i)]\n ;; old points i…to are gone; the point after the run (to+1) is the last of its replacement\n (let [out (into out r) last-old (inc to)]\n (recur (inc last-old) out (assoc m last-old (count out))))\n (let [out (conj out (nth evs (dec i)))]\n (recur (inc i) out (assoc m i (count out)))))))]\n {:events new-evs :map mapping}))\n\n(defn forget-points\n \"Forgets points of the history of a solo or local work: [[\\\"node-id\\\" k] …]. The moments after them stay as\n they were; the work at those moments is lost (and a keyframe there with it). Branch points and tips cannot\n be forgotten. It cannot be undone.\"\n [pts]\n (when-not (forget-allowed?)\n (fail (if (= :room (:kind @work))\n \"In a shared room the history belongs to everyone: make a release (a copy) to get a compact version.\"\n \"Points can be forgotten in a solo or local work, outside Perform and lessons.\")))\n (let [pts (set (map (fn [[nid k]] [(str nid) k]) pts))]\n (when (empty? pts) (fail \"Which points? Select them with ⇧+click in the history.\"))\n (doseq [p pts] (when-let [why (forget-blocker p)] (fail (str \"Point \" (pr-str p) \" cannot be forgotten: \" why \".\"))))\n (let [by-node (group-by first pts)\n plans (into {} (for [[nid ps] by-node] [nid (squash-node nid (map second ps))]))\n remap (fn [[nid k :as pos]] (if-let [m (:map (get plans nid))]\n ;; a forgotten point goes to the next point kept\n [nid (or (get m k) (some (fn [j] (get m j)) (range k (+ k 1 (count (:events (node nid)))))) k)]\n pos))\n before (history-size)]\n (swap! hist update :nodes\n (fn [ns]\n (into {} (for [[id n] ns]\n [id (cond-> n\n (contains? plans id) (assoc :events (:events (get plans id)))\n (contains? plans (:parent n)) (assoc :at (second (remap [(:parent n) (:at n)])))\n (and (vector? (:merge n)) (contains? plans (first (:merge n)))) (assoc :merge (remap (:merge n))))]))))\n (swap! world (fn [w] (cond-> w (:pos w) (update :pos remap) (:prev-pos w) (assoc :prev-pos nil))))\n (reset! cache {})\n (reset! picked #{})\n ;; a solo work: the changed segments are written again\n (when (persist?)\n (doseq [n (vals (:nodes @hist))\n :when (or (contains? plans (:id n)) (contains? plans (:parent n))\n (and (vector? (:merge n)) (contains? plans (first (:merge n)))))\n :when (not (str/starts-with? (:id n) \"local-\"))]\n (let [path (str (hist-path) \"/\" (:id n)) body (node->js n)]\n (enqueue! path (fn [] (.set (.doc @dbref path) body))))))\n (render-all!)\n {:forgotten (count pts) :events-before before :events-after (history-size)})))\n\n;; ───── interface: ⇧+click picks points, Forget… and Release… ─────\n\n(defn mark-picked!\n \"Marks in the drawn history the points chosen to be forgotten.\"\n [svg]\n (when (seq @picked)\n (doseq [el (array-seq (.querySelectorAll svg \"[data-goto]\"))]\n (let [[nid k] (str/split (.getAttribute el \"data-goto\") #\"\\|\")]\n (when (contains? @picked [nid (js/parseInt k 10)]) (.add (.-classList el) \"picked\")))))\n (when-let [b ($ \"forget-btn\")]\n (set! (.-hidden b) (empty? @picked))\n (set! (.-textContent b) (str \"Forget \" (count @picked) \"…\"))))\n\n(defn toggle-pick!\n \"⇧+click on a point of the history: chosen to be forgotten, or not any more.\"\n [nid k]\n (cond\n (not (forget-allowed?))\n (repl-print! \"err\" (esc (if (= :room (:kind @work))\n \"; in a shared room points cannot be forgotten: a release (a copy) gives a compact version\"\n \"; points can be forgotten in a solo or local work, outside Perform and lessons\")))\n (forget-blocker [nid k]) (repl-print! \"err\" (esc (str \"; that point cannot be forgotten: \" (forget-blocker [nid k]))))\n :else (do (swap! picked (fn [s] (if (contains? s [nid k]) (disj s [nid k]) (conj s [nid k]))))\n (render-tree!))))\n\n(defn release-pop [] (floating \"release-pop\" \"perform-pop\"))\n\n(defn release-ask!\n \"Shows the popup of Forget… or Release… with `html` (not ask!, which is the Claude tab's button, 07-claude.cljs).\"\n [html]\n (let [el (release-pop)]\n (set! (.-innerHTML el) html)\n (set! (.-hidden el) false)))\n\n(.addEventListener (release-pop) \"click\"\n (fn [e]\n (when-let [a (.. e -target -dataset -rel)]\n (set! (.-hidden (release-pop)) true)\n (case a\n \"forget\" (gesture! (str \"(forget-points \" (pr-str (vec (sort @picked))) \")\"))\n \"release\" (gesture! \"(release)\")\n nil))))\n\n(when-let [b ($ \"forget-btn\")]\n (.addEventListener b \"click\"\n (fn [_]\n (let [n (count @picked)]\n (release-ask! (str \"<p><b>Forget \" n (if (= 1 n) \" point\" \" points\") \" of the history?</b> The work at \"\n (if (= 1 n) \"that moment\" \"those moments\") \" will be lost (and any snapshot there); the moments after \"\n (if (= 1 n) \"it\" \"them\") \" stay exactly as they are. This cannot be undone.</p>\"\n \"<div class=\\\"pp-actions\\\"><button class=\\\"act primary\\\" data-rel=\\\"forget\\\">Forget \"\n (if (= 1 n) \"it\" \"them\") \"</button><button class=\\\"act\\\" data-rel=\\\"cancel\\\">Cancel</button></div>\"))))))\n\n(when-let [b ($ \"release-btn\")]\n (.addEventListener b \"click\"\n (fn [_]\n (let [k (count (keyframes))]\n (release-ask! (str \"<p><b>Release</b> · a new work with a compact history: \" k (if (= 1 k) \" keyframe\" \" keyframes\")\n \" (out of \" (history-size) \" events) and then the work as it is; presets boxes keep their presets, so \"\n \"they travel with the patch. This work stays as it is.</p>\"\n \"<div class=\\\"pp-actions\\\"><button class=\\\"act primary\\\" data-rel=\\\"release\\\">Make the release</button>\"\n \"<button class=\\\"act\\\" data-rel=\\\"cancel\\\">Cancel</button></div>\"))))))\n\n;; another work opened: nothing is picked\n(add-watch work ::release (fn [_ _ o n] (when (not= (select-keys o [:kind :id]) (select-keys n [:kind :id])) (reset! picked #{}))))\n","page/17-sounds.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page, part 18 of 18: sounds\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n\n(in-ns 'user)\n\n;; ───────────────────────── sounds: the data of sample boxes ─────────────────────────\n;; A sample box keeps a description of its sound in the work ({:audio hash :sr :frames :channels :peaks});\n;; the samples stay in this browser (kairotic.sounds). A recording reaches the history as a gesture,\n;; (sample! :bN {…}), which is also how the work's code writes it.\n\n(defn need-sample [id]\n (let [b (need-box id)]\n (when-not (= \"sample\" (klass (:text b))) (fail (str id \" is not a sample box\")))\n b))\n\n(defn sample!\n \"The sound of a sample box, as a description: (sample! :b4 {:audio \\\"5a2c…\\\" :sr 48000 :frames 96000\n :channels 1 :peaks […]}) — what a recording or (load-sound! :b4) writes — or only a URL,\n (sample! :b4 {:url \\\"https://…/voice.ogg\\\"}), fetched by every browser that opens the work.\n (sample! :b4 nil) empties it.\"\n [id d]\n (need-sample id)\n (if (snd/sample? (snd/sane d))\n (do (dispatch! [:in id [:set d]]) (snd/seconds (snd/sane d)))\n (do (dispatch! [:in id [:clear]]) 0)))\n\n(defn sound-of \"The description of the sound of a sample box ({} if it is empty).\" [id]\n (or (:data (need-sample id)) {}))\n\n(defn sound-file-name [d] (str \"kairotic-\" (.slice (str (:audio d)) 0 8) \".wav\"))\n\n(defn save-sound\n \"Saves the sound of a sample box as a WAV file (16 bits), if this browser has it: (save-sound :b4).\"\n [id]\n (let [d (sound-of id)]\n (when-not (snd/sample? d) (fail (str id \" has no sound\")))\n (-> (js/Promise.all #js [(snd/sound-for d) (snd/lib)])\n (.then (fn [[s L]]\n (if-not s\n (repl-print! \"err\" (esc (str \"; \" id \": its sound is not in this browser (it was recorded elsewhere)\")))\n (let [a (.createElement js/document \"a\")]\n (set! (.-href a) (js/URL.createObjectURL (.wav L (:chans s) (:sr s))))\n (set! (.-download a) (sound-file-name d))\n (.click a))))))\n (sound-file-name d)))\n\n(defn decode-sound!\n \"A sound file (a File or Blob) into the sample box id: decoded at the sample rate of the engine, kept\n in this browser, written as a gesture. Promise of its length in seconds.\"\n [id file]\n (-> (.arrayBuffer file)\n (.then snd/decode)\n (.then (fn [{:keys [sr chans]}] (snd/keep! sr chans)))\n (.then (fn [d] (gesture! (str \"(sample! \" id \" \" (pr-str d) \")\")) (snd/seconds d)))\n (.catch (fn [e] (repl-print! \"err\" (esc (str \"; \" id \": could not read that sound (\" (or (.-message e) e) \")\")))))))\n\n(defn url-sound!\n \"Loads the sound at url into the sample box id: fetched, decoded, kept in this browser and written as a\n gesture, its URL included, so every browser that opens the work fetches it too. Promise of its length.\"\n [id url]\n (let [d (snd/sane {:url url})]\n (-> (snd/sound-for d)\n (.then (fn [_] (let [full (merge (snd/about d) d)]\n (gesture! (str \"(sample! \" id \" \" (pr-str full) \")\"))\n (snd/seconds full))))\n (.catch (fn [e] (repl-print! \"err\" (esc (str \"; \" id \": \" (or (.-message e) e)))))))))\n\n(defn load-sound!\n \"Brings a sound into a sample box (wav, mp3, ogg, flac… whatever this browser can decode):\n (load-sound! :b4) opens the file chooser; (load-sound! :b4 \\\"https://…/voice.ogg\\\") loads it from a URL,\n which every browser that opens the work fetches by itself (a shared session, a link, a test).\"\n ([id]\n (need-sample id)\n (let [input (.createElement js/document \"input\")]\n (set! (.-type input) \"file\")\n (set! (.-accept input) \"audio/*\")\n (.addEventListener input \"change\" (fn [_] (when-let [f (aget (.-files input) 0)] (decode-sound! id f))))\n (.click input)\n :choose-a-file))\n ([id url]\n (need-sample id)\n (when-not (snd/url? url) (fail (str (pr-str url) \" is not a URL a sound can be loaded from\")))\n (url-sound! id url)\n :loading))\n\n;; ───── sources of sounds: Freesound ─────\n;; github:owner/repo@ref/path needs nothing; freesound:id needs an API key of whoever opens the work (each\n;; person their own, from freesound.org/apiv2/apply), kept only in this browser.\n\n(defn freesound-key!\n \"Keeps your Freesound API key in this browser (never in a work, a link or a room): (freesound-key! \\\"…\\\").\n (freesound-key! nil) forgets it. Get one at https://freesound.org/apiv2/apply\"\n [k]\n (if (snd/set-freesound-key! (when (string? k) (str/trim k)))\n (do (reset! snd/status {}) :kept-in-this-browser)\n :forgotten))\n\n(defn sounds\n \"Searches Freesound: (sounds \\\"kick\\\") · (sounds \\\"rain\\\" {:max 30}) seconds at most · {:license \\\"cc0\\\"}\n only CC0. Prints the first results, each with the line that loads it: (load-sound! :bN \\\"freesound:123\\\").\"\n ([q] (sounds q {}))\n ([q {:keys [max license]}]\n (let [filters (cond-> []\n (number? max) (conj (str \"duration:[0 TO \" max \"]\"))\n (= \"cc0\" (some-> license str str/lower-case)) (conj \"license:\\\"Creative Commons 0\\\"\"))]\n (-> (snd/freesound-get \"search/text/\"\n (cond-> {:query (str q) :fields \"id,name,username,license,duration\" :page_size 12}\n (seq filters) (assoc :filter (str/join \" \" filters))))\n (.then (fn [j]\n (let [rs (:results j)]\n (repl-print! \"out\" (esc (str \"; Freesound: \" (:count j) \" sounds for \" (pr-str q)\n (when (seq rs) \" — the first ones:\"))))\n (doseq [x rs]\n (repl-print! \"out\" (esc (str \"(load-sound! :bN \\\"freesound:\" (:id x) \"\\\") ; \"\n (:name x) \" · \" (:username x) \" · \" (snd/license-label (:license x))\n \" · \" (comp/nice (or (:duration x) 0)) \" s\")))))))\n (.catch (fn [e] (repl-print! \"err\" (esc (str \"; \" (or (.-message e) e)))))))\n :searching)))\n\n(defn credits\n \"The credits of the sounds of the work (those that brought theirs, from Freesound): one line each.\"\n []\n (let [walk (fn walk [p]\n (mapcat (fn [[_ b]]\n (cond (= \"patch\" (klass (:text b))) (walk (:data b))\n (= \"sample\" (klass (:text b)))\n (when-let [c (:credit (merge (:data b) (snd/about (:data b))))] [c])))\n (:boxes p)))\n cs (distinct (walk (work-patch)))]\n (mapv (fn [{:keys [name author license page]}] (str \"\\\"\" name \"\\\" by \" author (when license (str \" (\" license \")\")) \" — \" page)) cs)))\n\n;; a sample box asked (a recording finished, or `clear`): done as a gesture, so it is an event of the history\n(let [before (:effect-hook @eng/rt)]\n (swap! eng/rt assoc :effect-hook\n (fn [f [k x :as e] at]\n (if (= k :sample)\n (js/setTimeout\n (fn []\n (cond\n (not (get-in (current) [:boxes f]))\n (repl-print! \"err\" (esc (str \"; \" (name f) \" is inside a sub-patch: a recording is kept only by the sample boxes of the patch on screen\")))\n (= :set (first x)) (gesture! (str \"(sample! \" f \" \" (pr-str (second x)) \")\"))\n (= :url (first x)) (url-sound! f (second x))\n :else (gesture! (str \"(sample! \" f \" nil)\"))))\n 0)\n (when before (before f e at))))))\n","page/18-lines.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page: lines (discussion #117, phase 1)\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n;;\n;; A work is a project of lines: independent histories, each a whole tree of its own (branches, merges,\n;; snapshots), shown as tabs above the patch. The main line is the work as it always was; the others are\n;; studies, sketches, parts. Their segments are kept with the work's history, each one marked with its line\n;; (00-work.cljs), and their names in <work>/lines, one document per line. The tab on screen is the line\n;; everything else works on: the patch, the history view, Perform and its jams, Share/Export, Claude.\n;; The engine plays the line where ▶ was pressed, whichever tab is on screen (decision 6, 00-work.cljs).\n;; One line is used inside another as `patch @name` (phase 2, below).\n\n(in-ns 'user)\n\n;; ───────────────────────── names ─────────────────────────\n\n(defn line-entry [lid] (get-in @line-state [:index lid]))\n\n(defn line-name\n \"The name of line lid as the tabs show it.\"\n [lid]\n (or (not-empty (:name (line-entry lid))) (if (= lid main-line) \"main\" \"a line\")))\n\n(defn known-lines\n \"Every line of the work: the main one, those with a name, and those whose segments arrived before their name.\"\n []\n (-> (set (keys (:index @line-state))) (into (keys (:other @hist))) (conj main-line (active-line))))\n\n(defn line-order [lid] [(if (= lid main-line) 0 1) (or (:created (line-entry lid)) 9e15) (line-name lid)])\n\n(defn tab-lines\n \"The lines shown as tabs, in order: the main one first, then by creation (the one on screen always).\"\n []\n (sort-by line-order (remove (fn [l] (and (:archived (line-entry l)) (not= l (active-line)))) (known-lines))))\n\n(defn archived-lines [] (sort-by line-order (filter (fn [l] (and (:archived (line-entry l)) (not= l (active-line)))) (known-lines))))\n\n(defn line-by-name\n \"The id of the line called nm (or with that id), archived or not.\"\n [nm]\n (let [nm (str/trim (str nm)) ls (known-lines)]\n (or (first (filter (fn [l] (= nm (line-name l))) (sort-by line-order ls)))\n (when (contains? ls nm) nm))))\n\n(defn ref-slug\n \"How a box writes a line's name after @: its spaces as - (patch @bass-line uses the line \\\"bass line\\\").\"\n [nm] (str/replace (str/trim (str nm)) #\"\\s+\" \"-\"))\n\n(defn line-by-ref\n \"The id of the line a `patch @r` box uses: by its name (spaces as -), or by a name it had before.\"\n [r]\n (let [ls (sort-by line-order (known-lines))]\n (or (first (filter (fn [l] (= r (ref-slug (line-name l)))) ls))\n (first (filter (fn [l] (some (fn [a] (= r (ref-slug a))) (:aliases (line-entry l)))) ls))\n (when (contains? (set ls) r) r))))\n\n;; ───────────────────────── storage: <work>/lines/<id> ─────────────────────────\n\n(defn lines-path [] (when-let [b (work-base)] (str b \"/lines\")))\n\n(defn on-lines\n \"The names of the lines, as they arrive (they are only ever added to or changed: a line is archived, not deleted).\"\n [snap]\n (let [incoming (into {} (for [d (array-seq (.-docs snap)) :when (.-exists d)\n :let [m (js->clj (.data d))]]\n [(.-id d) {:name (let [n (get m \"name\")] (when (string? n) n))\n :created (let [t (get m \"created\")] (if (number? t) t 0))\n :archived (true? (get m \"archived\"))\n :aliases (let [a (get m \"aliases\")] (if (sequential? a) (vec (filter string? a)) []))}]))]\n (swap! line-state update :index merge incoming)))\n\n(defn save-line!\n \"Writes what changed of line lid's entry (its name, archived) where the others read it.\"\n [lid changes]\n (swap! line-state update-in [:index lid] merge changes)\n (when (persist?)\n (let [path (str (lines-path) \"/\" lid)\n body (clj->js (merge (select-keys (line-entry lid) [:name :created :archived :aliases]) {:author (my-author)} changes))]\n (enqueue! path (fn [] (.set (.doc @dbref path) body))))))\n\n(defn new-line-id []\n (if (persist?)\n (.-id (.doc (.collection @dbref (lines-path))))\n (str \"l\" (.toString (js/Math.floor (* (js/Math.random) 2176782336)) 36) (.toString (js/Date.now) 36))))\n\n;; ───────────────────────── a line used as a sub-patch: patch @name (phase 2) ─────────────────────────\n;; A `patch @name` box reads the line called name: at its newest point (it follows the line, so it changes\n;; as the line advances, like an abstraction of Max or Pd), or at the point it is pinned to ([:pin id pos]).\n;; While performing, the lines followed stay where they were when Perform started (decision 4); away from\n;; the newest point of the line on screen, they read where they were at the last snapshot before it, if it\n;; kept them (decision 5). Inside a line used so, adc~ and dac~ are quiet: they play when the line plays\n;; alone, and sound goes in and out through inlet~ / outlet~ (decision 7).\n\n(defn line-nodes [lid] (if (= lid (active-line)) (:nodes @hist) (get-in @hist [:other lid] {})))\n\n(defn nodes-front [nodes]\n (when (seq nodes) (let [n (apply max-key (fn [n] (or (:t n) 0)) (vals nodes))] [(:id n) (count (:events n))])))\n\n(defn nodes-depth\n \"How many events from the root of a line to pos (its moment).\"\n [nodes [nid idx]]\n (loop [nid nid acc idx guard 0]\n (let [n (get nodes nid)]\n (if (and n (:parent n) (get nodes (:parent n)) (< guard 512))\n (recur (:parent n) (+ acc (:at n)) (inc guard))\n acc))))\n\n(defonce ref-cache (atom {})) ; [line pos] → [its nodes, the patch]\n\n(defn line-patch-at [lid pos]\n (let [nodes (line-nodes lid) [k p] (get @ref-cache [lid pos])]\n (if (identical? k nodes)\n p\n (let [p (if pos (nodes-patch nodes pos) empty-patch)]\n (swap! ref-cache (fn [c] (assoc (if (> (count c) 200) {} c) [lid pos] [nodes p])))\n p))))\n\n(defonce fronts-cache (atom [nil nil nil]))\n\n(defn snapshot-fronts\n \"Where the lines followed were at the last snapshot before the point on screen, when it is not the newest\n point of its line (decision 5): {line pos}, or nil.\"\n []\n (let [here (norm (:pos @world)) nodes (:nodes @hist) [k1 k2 v] @fronts-cache]\n (if (and (identical? k1 nodes) (= k2 here))\n v\n (let [v (when (and here (not= here (newest-tip)))\n (some (fn [e] (when (and (vector? e) (= :mark (first e))) (:fronts (second e))))\n (reverse (mapcat (fn [g] (seg-events g 0)) (segments here)))))]\n (reset! fronts-cache [nodes here v])\n v))))\n\n(defn ref-pos\n \"The point of its line that box b reads.\"\n [b lid]\n (or (:pin b)\n (get-in @perf [:pins lid])\n (get (snapshot-fronts) lid)\n (nodes-front (line-nodes lid))))\n\n(defn resolve-ref\n \"{:line :pos :pinned :patch} for a `patch @name` box, or {:error}.\"\n [b]\n (let [r (eng/line-ref b) lid (when r (line-by-ref r))]\n (cond (nil? r) {:error \"not a patch @name box\"}\n (nil? lid) {:error (str \"There is no line called \" r \" in this work.\")}\n :else (let [pos (ref-pos b lid)]\n {:line lid :pos pos :pinned (some? (:pin b)) :patch (if pos (line-patch-at lid pos) empty-patch)}))))\n\n(defn refs-in\n \"The `patch @name` boxes of a patch, through its embedded patches: [[path id box] …].\"\n ([p] (refs-in p []))\n ([p path]\n (mapcat (fn [[id b]]\n (cond (line-ref? b) [[path id b]]\n (embedded? b) (refs-in (or (:data b) empty-patch) (conj path id))\n :else []))\n (:boxes p))))\n\n(defn lines-reached\n \"Every line reached from patch p through references, at the point each one is read: {line pos}.\"\n [p]\n (loop [todo [p] seen {} guard 0]\n (if (or (empty? todo) (> guard 64))\n seen\n (let [found (for [[_ _ b] (refs-in (peek todo)) :let [r (resolve-ref b)] :when (:line r)] r)\n new (remove (fn [r] (contains? seen (:line r))) found)]\n (recur (into (pop todo) (map :patch new))\n (into seen (map (fn [r] [(:line r) (:pos r)]) found)) (inc guard))))))\n\n(defn check-ref-text!\n \"Fails when box text t is a `patch @name` that cannot be: no such line, or one that would contain itself.\"\n [t]\n (when-let [r (eng/line-ref {:text t})]\n (let [lid (line-by-ref r) here (active-line)]\n (cond (nil? lid) (fail (str \"There is no line called \" r \" in this work (spaces in a name are written -).\"))\n (= lid here) (fail \"A line cannot contain itself.\")\n (contains? (lines-reached (line-patch-at lid (nodes-front (line-nodes lid)))) here)\n (fail (str (line-name lid) \" already uses \" (line-name here) \": that would be a cycle.\"))\n :else nil))))\n\n(defn followed-fronts\n \"The lines the work on screen follows (not pinned), where each one is now: {line pos}.\"\n []\n (into {} (for [[lid pos] (lines-reached (work-patch))\n :when (not-any? (fn [[_ _ b]] (and (:pin b) (= lid (line-by-ref (eng/line-ref b))))) (refs-in (work-patch)))]\n [lid pos])))\n\n(defn quiet\n \"A line as a sub-patch plays: without its adc~ and dac~ (decision 7).\"\n [p]\n (let [io (set (keep (fn [[id b]] (when (#{\"adc~\" \"dac~\"} (klass (:text b))) id)) (:boxes p)))]\n (if (empty? io)\n p\n (-> p (update :boxes (fn [bx] (into (sorted-map) (remove (fn [[id _]] (io id)) bx))))\n (update :lines (fn [ls] (vec (remove (fn [[a _ b _]] (or (io a) (io b))) ls))))))))\n\n(reset! eng/line-resolver (fn [b] (let [r (resolve-ref b)] (when-let [p (:patch r)] (quiet p)))))\n\n(defn ref-badge\n \"What a `patch @name` box shows beside its name: ↻ following its line, ⌖ and the moment it is pinned to,\n ⚠ when something is wrong.\"\n [b]\n (let [r (resolve-ref b)]\n (cond (:error r) \"⚠\"\n (or (ref-warning b)) \"⚠\"\n (:pinned r) (str \"⌖\" (nodes-depth (line-nodes (:line r)) (:pos r)))\n :else \"↻\")))\n\n(defn ref-warning\n \"Why a `patch @name` box may not do what it seems, or nil.\"\n [b]\n (let [r (resolve-ref b) cls (frequencies (map (comp klass :text) (vals (:boxes (:patch r)))))]\n (cond (:error r) (:error r)\n (and (cls \"dac~\") (not (cls \"outlet~\")))\n (str (line-name (:line r)) \" has dac~ but no outlet~: nothing comes out here (its dac~ plays only when the line plays alone)\")\n (and (cls \"adc~\") (not (cls \"inlet~\")))\n (str (line-name (:line r)) \" has adc~ but no inlet~: no sound goes in (its adc~ listens only when the line plays alone)\")\n :else nil)))\n\n(defn need-ref [id]\n (let [b (or (get-in (current) [:boxes id]) (fail (str \"There is no box \" id)))]\n (when-not (line-ref? b) (fail (str id \" is not a patch @name box\")))\n b))\n\n(defn pin-ref\n \"(pin-ref :b3): the line box :b3 uses stays at the point it reads now. (pin-ref :b3 [node n]) at that one.\"\n ([id] (pin-ref id nil))\n ([id pos]\n (let [b (need-ref id)\n pos (or pos (:pos (resolve-ref b)) (fail (str (eng/line-ref b) \" has no history yet: nothing to pin\")))]\n (dispatch! [:pin id (vec pos)])\n pos)))\n\n(defn follow-ref\n \"(follow-ref :b3): the box follows its line again (its newest point).\"\n [id]\n (need-ref id)\n (dispatch! [:pin id nil])\n :follows)\n\n(declare need-switch)\n\n(defn open-ref\n \"(open-ref :b3): the line box :b3 uses, in its tab (at the point it is pinned to, if it is).\"\n [id]\n (let [b (need-ref id) r (resolve-ref b)]\n (when (:error r) (fail (:error r)))\n (need-switch (:line r))\n (swap! ui assoc :follow nil)\n (when (:pinned r)\n (swap! world assoc :pos (:pos r) :auto false :prev-pos nil))\n (line-name (:line r))))\n\n;; ───── a line's tab while the line that plays uses it (decision 6, what you play there) ─────\n;; When the line that plays uses the line on screen (following it, and the tab is at its newest point), the\n;; tab shows that line where it plays: its first instance. What you play there goes to every instance.\n\n(defn instances-in\n \"Where line lid plays inside patch p, through embedded patches and the lines p uses: [path …].\"\n [lid p path depth]\n (if (> depth 12)\n []\n (vec (mapcat (fn [[id b]]\n (cond (line-ref? b)\n (let [r (resolve-ref b)]\n (cond (:error r) []\n (= lid (:line r)) (if (:pinned r) [] [(conj path id)])\n :else (instances-in lid (:patch r) (conj path id) (inc depth))))\n (embedded? b) (instances-in lid (or (:data b) empty-patch) (conj path id) (inc depth))\n :else []))\n (:boxes p)))))\n\n(defonce instances-cache (atom [nil nil nil nil]))\n\n(defn view-instances\n \"Where the line on screen plays inside the line that plays: [path …] (empty when it does not, or when its\n tab is not at its newest point, or in Perform).\"\n []\n (if-not (and (playing-elsewhere?) (not @perf) (= (norm (:pos @world)) (newest-tip)))\n []\n (let [off (off-screen-patch (playing-line)) nodes (:nodes @hist) a (active-line)\n [k1 k2 k3 v] @instances-cache]\n (if (and (identical? k1 off) (identical? k2 nodes) (= k3 a))\n v\n (let [v (instances-in a off [] 0)] (reset! instances-cache [off nodes a v]) v)))))\n\n;; ───── one line, when the work leaves: links and releases (decision 8) ─────\n;; A link or a release carries one patch, not the lines of a work: every `patch @name` in it becomes an\n;; embedded patch holding its line at the point it reads (its pin, the fronts given — those a snapshot kept —\n;; or its newest point), quiet as it played there (without its adc~ and dac~), and so on inside it.\n\n(defn inline-lines\n \"Patch p with every `patch @name` (through embedded patches, and inside the lines it uses) made an embedded\n patch holding its line: at its pin, at (fronts line) when given, or as it reads now.\"\n ([p] (inline-lines p nil 0))\n ([p fronts] (inline-lines p fronts 0))\n ([p fronts depth]\n (if (> depth 16)\n p\n (update p :boxes\n (fn [bx]\n (into (empty bx)\n (for [[id b] bx]\n [id (cond\n (line-ref? b)\n (let [lid (line-by-ref (eng/line-ref b))\n pos (when lid (or (:pin b) (get fronts lid) (ref-pos b lid)))\n inner (if pos (line-patch-at lid pos) empty-patch)]\n (-> b (dissoc :pin)\n (assoc :text (str \"patch \" (eng/line-ref b))\n :data (quiet (inline-lines inner fronts (inc depth))))))\n (embedded? b) (update b :data (fn [d] (when d (inline-lines d fronts (inc depth)))))\n :else b)])))))))\n\n;; ───── from a box to a line and back (decision 2) ─────\n\n(declare check-line-name)\n\n(defn inline-ref\n \"(inline-ref :b3): the line box :b3 uses becomes a copy inside the box (an embedded patch), as it plays now:\n detached from the line, which stays as it is.\"\n [id]\n (let [b (need-ref id) r (resolve-ref b)]\n (when (:error r) (fail (:error r)))\n (dispatch! [:batch [[:text id (str \"patch \" (eng/line-ref b))] [:pin id nil]\n [:data id (quiet (inline-lines (:patch r)))]]])\n id))\n\n(defn events-inside\n \"The events that reached the inside of box id (in the patch at path) along ev: [:in :b2 [:in :b5 e]] for\n path [:b2] and id :b5 gives e, through batches.\"\n [path id ev]\n (letfn [(walk [path ev]\n (cond (not (vector? ev)) []\n (= :batch (first ev)) (mapcat (fn [e] (walk path e)) (second ev))\n (seq path) (if (and (= :in (first ev)) (= (first path) (second ev))) (walk (rest path) (nth ev 2 nil)) [])\n :else [ev]))]\n (walk path ev)))\n\n(defn box-history\n \"The history box id had inside it (in the patch at path of the line on screen), from the root to here: the\n events it received, from the last time it was made (or loaded).\"\n [path id]\n (let [evs (mapcat (fn [g] (seg-events g 0)) (segments (norm (:pos @world))))]\n (reduce (fn [acc ev]\n (reduce (fn [acc e]\n (let [[op a x] e]\n (case op\n (:box :delete) (if (= a id) [] acc)\n :data (if (= a id) (if (map? x) [[:load x]] []) acc)\n :in (if (= a id) (conj acc x) acc)\n :load (if-let [d (get-in a [:boxes id :data])] [[:load d]] [])\n :clear []\n acc)))\n acc (events-inside path id ev)))\n [] evs)))\n\n(defn write-line-node!\n \"A first segment for line lid (not on screen): events evs, saved as any other.\"\n [lid evs]\n (let [id (new-id)\n n {:id id :parent nil :at 0 :author (my-author) :session session-id :t (js/Date.now) :merge nil\n :events (vec evs) :line lid}]\n (swap! hist assoc-in [:other lid id] n)\n (when (and (persist?) (not (str/starts-with? id \"local-\")))\n (let [path (str (hist-path) \"/\" id) body (node->js n)]\n (enqueue! path (fn [] (.set (.doc @dbref path) body)))))\n id))\n\n(defn extract-line\n \"(extract-line :b3 \\\"filters\\\"): the embedded patch :b3 becomes a new line, with the history it had inside the\n box, and the box uses it (patch @filters, following it).\"\n [id nm]\n (when (or @perf @lesson @scratch) (fail \"Not now: lines change outside Perform, a lesson or the scratch patch.\"))\n (let [b (or (get-in (current) [:boxes id]) (fail (str \"There is no box \" id)))]\n (when-not (embedded? b) (fail (str id \" is not an embedded patch\")))\n (let [nm (check-line-name nm nil)\n evs (box-history (cmd-path) id)\n evs (if (and (empty? evs) (seq (:boxes (:data b)))) [[:load (:data b)]] evs)\n lid (new-line-id)]\n (save-line! lid {:name nm :created (js/Date.now) :archived false})\n (when (seq evs) (write-line-node! lid evs))\n (dispatch! [:batch [[:text id (str \"patch @\" (ref-slug nm))] [:data id nil]]])\n nm)))\n\n;; a line that changes changes what its users play: the engine's flat patch is made again\n(add-watch hist ::refs (fn [_ _ o n] (when-not (and (identical? (:nodes o) (:nodes n)) (identical? (:other o) (:other n)))\n (reset! eng/flat-cache [nil nil]))))\n\n;; ───────────────────────── the line on screen ─────────────────────────\n\n(defn switch-line!\n \"Puts line lid on screen: its segments become the history, at the point its tab was left (or its newest).\n The engine goes on playing the line where ▶ was pressed (decision 6): the boxes of the one on screen are\n known to it under the prefix of their line, so nothing of what they show or hold meets the other's. With\n the engine stopped, what the boxes showed is forgotten, as when another work opens. False when it cannot\n be now (in Perform, a lesson or the scratch patch).\"\n [lid]\n (cond\n (= lid (active-line)) true\n (or @perf @lesson @scratch) false\n :else\n (let [from (active-line) on? (eng/running?)]\n (swap! line-state (fn [st] (-> st (assoc-in [:pos from] (:pos @world)) (assoc :active lid))))\n (reset! world {:pos nil :auto true :prev-pos nil :jumped-at 0})\n (swap! hist (fn [h] (-> h\n (assoc-in [:other from] (:nodes h))\n (assoc :nodes (get-in h [:other lid] {}))\n (update :other dissoc lid))))\n (reset! cache {})\n (when-not on? (reset-patch-state!))\n (reset! view-path [])\n (swap! ui assoc :sel nil :drag nil :wire nil :merge-pick false)\n (let [saved (get-in @line-state [:pos lid])]\n (swap! world assoc :pos (if (and saved (node (first saved))) saved (newest-tip))))\n (publish-presence!)\n (transport-info!)\n (render-all!)\n (render-lines!)\n ;; the official classes its boxes use and no definition of its own brings (one asked for while\n ;; another line was on screen waits for this one)\n (ensure-classes!)\n true)))\n\n;; ───────────────────────── commands (what the tabs write in the REPL) ─────────────────────────\n\n(defn check-line-name [nm except]\n (let [nm (str/trim (str nm))]\n (cond (str/blank? nm) (fail \"A line needs a name.\")\n (> (count nm) 40) (fail \"A line's name: 40 characters at most.\")\n (re-find #\"[\\n\\r\\\"]\" nm) (fail \"A line's name: one line, without quotes.\")\n (some (fn [l] (and (not= l except) (= nm (line-name l)))) (known-lines))\n (fail (str \"There is already a line called \" (pr-str nm) \".\"))\n :else nm)))\n\n(defn need-line [nm]\n (or (line-by-name nm) (fail (str \"There is no line called \" (pr-str (str nm)) \". (work-lines) lists them.\"))))\n\n(defn need-switch [lid]\n (when-not (switch-line! lid)\n (fail \"Not now: lines change outside Perform, a lesson or the scratch patch.\")))\n\n(defn go-line\n \"(go-line \\\"sketch\\\"): puts the line called so on screen (its tab). (go-line) says which one is.\"\n ([] (line-name (active-line)))\n ([nm]\n (let [lid (need-line nm)]\n (need-switch lid)\n (swap! ui assoc :follow nil)\n (line-name lid))))\n\n(defn new-line\n \"(new-line \\\"sketch\\\"): a new line in this work, empty, with a history of its own; it goes on screen.\"\n [nm]\n (when-not (:kind @work) (fail \"Open or create a work first.\"))\n (when (or @perf @lesson @scratch) (fail \"Not now: lines change outside Perform, a lesson or the scratch patch.\"))\n (let [nm (check-line-name nm nil) lid (new-line-id)]\n (save-line! lid {:name nm :created (js/Date.now) :archived false})\n (need-switch lid)\n (swap! ui assoc :follow nil)\n nm))\n\n(defn rename-line\n \"(rename-line \\\"intro\\\"): another name for the line on screen. (rename-line \\\"old\\\" \\\"new\\\") for any line.\"\n ([nm] (rename-line (line-name (active-line)) nm))\n ([old nm]\n (let [lid (need-line old) nm (check-line-name nm lid) was (line-name lid)]\n ;; the old name stays as an alias: boxes of other lines (and older points) that say patch @old still find it\n (save-line! lid {:name nm :created (or (:created (line-entry lid)) (if (= lid main-line) 0 (js/Date.now)))\n :aliases (vec (distinct (remove #{nm} (conj (vec (:aliases (line-entry lid))) was))))})\n ;; the boxes of the line on screen that use it say the new name\n (when-not (or @perf @scratch)\n (let [evs (for [[path id b] (refs-in (work-patch)) :when (= lid (line-by-ref (eng/line-ref b)))]\n (wrap-in path [:text id (str/join \" \" (into [\"patch\" (str \"@\" (ref-slug nm))] (drop 2 (str/split (str/trim (:text b)) #\"\\s+\"))))]))]\n (when (seq evs) (dispatch-root! [:batch (vec evs)]))))\n (render-lines!)\n nm)))\n\n(defn archive-line\n \"(archive-line \\\"sketch\\\"): hides a line's tab (it is kept, with its history: (restore-line \\\"sketch\\\")).\n The main line cannot be archived.\"\n ([] (archive-line (line-name (active-line))))\n ([nm]\n (let [lid (need-line nm)]\n (when (= lid main-line) (fail \"The main line cannot be archived.\"))\n (when (= lid (active-line)) (need-switch main-line))\n (save-line! lid {:archived true})\n (render-lines!)\n (line-name lid))))\n\n(defn restore-line\n \"(restore-line \\\"sketch\\\"): its tab again, on screen.\"\n [nm]\n (let [lid (need-line nm)]\n (save-line! lid {:archived false})\n (need-switch lid)\n (line-name lid)))\n\n(defn work-lines\n \"The lines of this work: {:on \\\"main\\\" :lines [\\\"main\\\" \\\"sketch\\\" …] :archived […]}.\"\n []\n {:on (line-name (active-line)) :lines (mapv line-name (tab-lines)) :archived (mapv line-name (archived-lines))})\n\n;; ───────────────────────── the tabs ─────────────────────────\n\n(defonce line-edit (atom nil)) ; nil, :new, or the id of the line being renamed\n\n(defn render-lines! []\n (let [el ($ \"line-tabs\")\n show? (and (:kind @work) (not @lesson) (not embed-mode))]\n (set! (.-hidden el) (not show?))\n (when show?\n (let [ed @line-edit\n others (remove :same @peers)\n on-line (fn [l] (count (filter (fn [p] (= (or (:line p) main-line) l)) others)))\n busy? (boolean (or @perf @scratch))]\n (set! (.-innerHTML el)\n (str (apply str\n (for [l (tab-lines) :let [sel? (= l (active-line)) n (on-line l)]]\n (if (= ed l)\n (str \"<input id=\\\"line-name-in\\\" data-line=\\\"\" (esc l) \"\\\" value=\\\"\" (esc (line-name l)) \"\\\" aria-label=\\\"Name of the line\\\" spellcheck=\\\"false\\\" autocomplete=\\\"off\\\">\")\n (str \"<button class=\\\"ltab\\\" role=\\\"tab\\\" data-line=\\\"\" (esc l) \"\\\" aria-selected=\\\"\" sel? \"\\\"\"\n (when (and busy? (not sel?)) \" disabled\")\n \" title=\\\"\" (if sel? \"The line on screen · double-click to rename it\" (str \"Put the line \" (esc (line-name l)) \" on screen\")) \"\\\">\"\n (when (= l main-line) \"<span class=\\\"star\\\" title=\\\"the main line\\\">★</span>\")\n (when (= l (playing-line)) \"<span class=\\\"plays\\\" title=\\\"The engine plays this line (■ stops it, ▶ on another tab plays that one)\\\">▶</span>\")\n (esc (line-name l))\n (when (pos? n) (str \"<span class=\\\"who\\\" title=\\\"\" n (if (= 1 n) \" person\" \" people\") \" on this line\\\">●\" (when (> n 1) n) \"</span>\"))\n (when (and sel? (not= l main-line) (not busy?)) \"<span class=\\\"x\\\" data-line-archive=\\\"1\\\" title=\\\"Archive this line (it is kept, with its history)\\\">×</span>\")\n \"</button>\"))))\n (if (= ed :new)\n \"<input id=\\\"line-name-in\\\" placeholder=\\\"name of the new line\\\" aria-label=\\\"Name of the new line\\\" spellcheck=\\\"false\\\" autocomplete=\\\"off\\\">\"\n (str \"<button class=\\\"ladd\\\" id=\\\"line-add\\\" title=\\\"A new line: an empty history of its own, in this work\\\" aria-label=\\\"New line\\\"\"\n (when busy? \" disabled\") \">+</button>\"))\n (let [arch (archived-lines)]\n (when (seq arch)\n (str \"<select id=\\\"line-restore\\\" aria-label=\\\"Archived lines\\\"><option value=\\\"\\\">archived (\" (count arch) \")</option>\"\n (apply str (for [l arch] (str \"<option value=\\\"\" (esc l) \"\\\">restore \" (esc (line-name l)) \"</option>\")))\n \"</select>\")))))\n (when ed (when-let [i ($ \"line-name-in\")] (.focus i) (.select i)))))))\n\n(defn line-gesture! [code] (swap! line-edit (constantly nil)) (gesture! code))\n\n(let [el ($ \"line-tabs\")]\n (.addEventListener el \"click\"\n (fn [e]\n (let [t (.-target e)]\n (cond\n (.closest t \"[data-line-archive]\")\n (line-gesture! \"(archive-line)\")\n (.closest t \"#line-add\")\n (do (reset! line-edit :new) (render-lines!))\n :else\n (when-let [b (.closest t \"button.ltab\")]\n (let [lid (.getAttribute b \"data-line\")]\n (when (not= lid (active-line)) (line-gesture! (str \"(go-line \" (pr-str (line-name lid)) \")\")))))))))\n (.addEventListener el \"dblclick\"\n (fn [e]\n (when-let [b (.closest (.-target e) \"button.ltab\")]\n (let [lid (.getAttribute b \"data-line\")]\n (when (= lid (active-line)) (reset! line-edit lid) (render-lines!))))))\n (.addEventListener el \"change\"\n (fn [e]\n (when (= \"line-restore\" (.. e -target -id))\n (let [lid (.. e -target -value)]\n (when (seq lid) (line-gesture! (str \"(restore-line \" (pr-str (line-name lid)) \")\")))))))\n (.addEventListener el \"keydown\"\n (fn [e]\n (when (= \"line-name-in\" (.. e -target -id))\n (let [k (.-key e) v (str/trim (.. e -target -value)) ed @line-edit]\n (cond\n (= k \"Escape\") (do (reset! line-edit nil) (render-lines!))\n (= k \"Enter\") (do (.preventDefault e)\n (cond (str/blank? v) (do (reset! line-edit nil) (render-lines!))\n (= ed :new) (line-gesture! (str \"(new-line \" (pr-str v) \")\"))\n (= v (line-name ed)) (do (reset! line-edit nil) (render-lines!))\n :else (line-gesture! (str \"(rename-line \" (pr-str (line-name ed)) \" \" (pr-str v) \")\"))))\n :else nil)))))\n (.addEventListener el \"focusout\"\n (fn [e]\n (when (and (= \"line-name-in\" (.. e -target -id)) @line-edit)\n (js/setTimeout (fn [] (when (and @line-edit (not= ($ \"line-name-in\") (.-activeElement js/document)))\n (reset! line-edit nil) (render-lines!)))\n 150)))))\n\n(add-watch eng/rt ::lines (fn [_ _ o n] (when (not= (:on o) (:on n)) (render-lines!))))\n(add-watch line-state ::render (fn [_ _ o n] (when (not= o n) (render-lines!))))\n(add-watch work ::lines (fn [_ _ o n] (when (not= (select-keys o [:kind :id]) (select-keys n [:kind :id])) (render-lines!))))\n(add-watch peers ::lines (fn [_ _ _ _] (render-lines!)))\n(add-watch perf ::lines (fn [_ _ o n] (when (not= (some? o) (some? n)) (render-lines!))))\n(add-watch lesson ::lines (fn [_ _ _ _] (render-lines!)))\n(add-watch hist ::lines (fn [_ _ o n] (when (not= (set (keys (:other o))) (set (keys (:other n)))) (render-lines!))))\n(render-lines!)\n","page/19-files.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · the page: a work as a file (discussion #149)\n;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).\n;;\n;; A .kairotic is a zip (kairotic/kfile.mjs) holding a whole work, in EDN:\n;; manifest.edn {:format 1 :kairotic \"0.2.0-alpha\" :made <ms> :kind :history | :release :anonymous bool}\n;; work.edn {:name … :simultaneity-ms … :origin …}\n;; lines.edn {\"main\" {:name \"main\"} \"<id>\" {:name \"sketch\" :created … :archived false :aliases […]}}\n;; history.edn every segment of every line, as the history keeps them\n;; people.edn {author {:name :color}} (not when anonymous)\n;; sounds/<hash>.wav the sounds recorded, 32-bit float (samples from URLs stay references)\n;; Opening one makes a new work (solo, or local without a database); the file and any other work are not\n;; touched. Exported as a release, it holds one line with a compact history (as a link or a release has).\n\n(in-ns 'user)\n\n(def kfile-format 1)\n\n(defn kfile-lib \"Promise of kairotic/kfile.mjs.\" [] (.kairoticImport js/window \"kairotic/kfile.mjs\"))\n\n;; ───────────────────────── what a work is, as data ─────────────────────────\n\n(defn all-segments\n \"Every segment of the work: those of the line on screen and of every other line.\"\n [] (vec (concat (vals (:nodes @hist)) (mapcat vals (vals (:other @hist))))))\n\n(defn recorded-sounds\n \"The keys of the sounds recorded that the events use (those from a URL stay references).\"\n [segs]\n (set (for [x (tree-seq coll? seq (mapv :events segs))\n :when (and (map? x) (string? (:audio x)) (not (snd/url? (:url x))))]\n (:audio x))))\n\n(defn anonymize\n \"The segments with every author and session made a plain name of its own (p1, p2… s1, s2…).\"\n [segs]\n (let [ids (fn [k pre] (into {} (map-indexed (fn [i a] [a (str pre (inc i))]) (distinct (keep k segs)))))\n as (ids :author \"p\") ss (ids :session \"s\")]\n (mapv (fn [n] (cond-> (assoc n :author (get as (:author n) \"p0\"))\n (:session n) (assoc :session (get ss (:session n)))))\n segs)))\n\n(defn work-data\n \"The work as the file keeps it: {:manifest :work :lines :history :people}.\"\n [{:keys [release anonymous]}]\n (let [now (js/Date.now)\n segs (if release\n [{:id \"release\" :parent nil :at 0 :author (my-author) :session session-id :t now :merge nil\n :events (release-events)}]\n (all-segments))\n segs (mapv (fn [n] (select-keys n [:id :parent :at :author :session :t :merge :events :line])) segs)\n segs (if anonymous (anonymize segs) segs)\n idx (:index @line-state)]\n {:manifest {:format kfile-format :kairotic version :made now :kind (if release :release :history) :anonymous (boolean anonymous)}\n :work (cond-> {:name (or (:name @work) \"Untitled\") :simultaneity-ms (:simul-ms @settings)}\n (and (not anonymous) (:kind @work)) (assoc :origin (str (name (:kind @work)) \":\" (:id @work))))\n :lines (if release\n {main-line {:name (line-name (active-line))}}\n (into {main-line (select-keys (get idx main-line {:name \"main\"}) [:name :created :archived :aliases])}\n (for [l (known-lines) :when (not= l main-line)]\n [l (select-keys (merge {:name (line-name l)} (get idx l)) [:name :created :archived :aliases])])))\n :history segs\n :people (when-not anonymous (into {} (for [a (distinct (map :author segs)) :let [p (get @profiles a)] :when p] [a p])))}))\n\n(defn export-bytes\n \"Promise of the bytes of a .kairotic of the work: {:release true} for a release, {:anonymous true} without\n who made it.\"\n [opts]\n (let [d (work-data opts)\n hashes (recorded-sounds (:history d))]\n (-> (js/Promise.all (clj->js (for [h hashes] (.then (snd/sound h) (fn [s] [h s])))))\n (.then (fn [found]\n (let [found (array-seq found)]\n (.then (kfile-lib)\n (fn [K]\n (let [have (filter (fn [[_ s]] (some? s)) found)\n missing (vec (for [[h s] found :when (nil? s)] h))\n edn (fn [nm x] #js {:name nm :data (pr-str x)})]\n (.zip K (clj->js\n (concat\n [(edn \"manifest.edn\" (cond-> (:manifest d) (seq missing) (assoc :missing-sounds missing)))\n (edn \"work.edn\" (:work d))\n (edn \"lines.edn\" (:lines d))\n (edn \"history.edn\" (:history d))]\n (when (seq (:people d)) [(edn \"people.edn\" (:people d))])\n (for [[h s] have]\n #js {:name (str \"sounds/\" h \".wav\") :deflate false\n :data (.wav K (:sr s) (:chans s))})))))))))))))\n\n(defn file-name [nm ext]\n (str (or (not-empty (-> (str nm) str/lower-case (str/replace #\"[^a-z0-9\\u00e0-\\u024f]+\" \"-\") (str/replace #\"^-|-$\" \"\"))) \"work\") ext))\n\n(defn download-bytes! [bytes nm]\n (let [a (js/document.createElement \"a\")\n url (js/URL.createObjectURL (js/Blob. #js [bytes] #js {:type \"application/zip\"}))]\n (set! (.-href a) url)\n (set! (.-download a) nm)\n (.appendChild js/document.body a)\n (.click a)\n (.remove a)\n (js/setTimeout (fn [] (js/URL.revokeObjectURL url)) 4000)))\n\n(defn export-work\n \"(export-work): downloads the work as a file (.kairotic), with its whole history, every line and the sounds\n recorded. (export-work :release) a release of it (one line, one point per keyframe);\n (export-work {:anonymous true}) without who made it (also {:release true :anonymous true}).\"\n ([] (export-work {}))\n ([opts]\n (when-not (:kind @work) (fail \"Open a work first.\"))\n (when @perf (fail \"You are in Perform: (compose) first.\"))\n (let [opts (cond (map? opts) opts (= :release opts) {:release true} (= :anonymous opts) {:anonymous true} :else {})\n nm (file-name (str (or (:name @work) \"work\") (when (:release opts) \" release\")) \".kairotic\")]\n (-> (export-bytes opts)\n (.then (fn [b]\n (download-bytes! b nm)\n (repl-print! \"out\" (esc (str \"; \" nm \" · \" (js/Math.round (/ (.-length b) 1024)) \" KB\")))))\n (.catch (fn [e] (repl-print! \"err\" (esc (str \"Could not export the work: \" (or (.-message e) e)))))))\n nm)))\n\n;; ───────────────────────── opening one ─────────────────────────\n\n(defn sane-segment [n]\n (when (and (map? n) (string? (:id n)) (seq (:id n)))\n {:id (:id n)\n :parent (when (string? (:parent n)) (:parent n))\n :at (if (number? (:at n)) (:at n) 0)\n :author (str (or (:author n) \"unknown\"))\n :session (when (string? (:session n)) (:session n))\n :t (if (number? (:t n)) (:t n) 0)\n :merge (when (valid-pos? (:merge n)) (:merge n))\n :line (when (and (string? (:line n)) (seq (:line n)) (not= main-line (:line n))) (:line n))\n :events (if (sequential? (:events n)) (vec (filter (fn [e] (and (vector? e) (keyword? (first e)))) (:events n))) [])}))\n\n(defn read-work-bytes\n \"Promise of what a .kairotic holds: {:manifest :work :lines :history :people :sounds {hash {:sr :chans}}}.\"\n [bytes]\n (.then (kfile-lib)\n (fn [K]\n (.then (.unzip K bytes)\n (fn [files]\n (let [by (into {} (for [f (array-seq files)] [(.-name f) (.-data f)]))\n edn (fn [nm] (when-let [b (get by nm)]\n (try (clojure.edn/read-string (.text K b))\n (catch :default e (throw (js/Error. (str nm \": \" (.-message e))))))))\n manifest (edn \"manifest.edn\")]\n (when-not (map? manifest) (throw (js/Error. \"This is not a Kairotic work (it has no manifest.edn).\")))\n (when (> (or (:format manifest) 0) kfile-format)\n (throw (js/Error. (str \"This work was saved by a newer Kairotic (format \" (:format manifest) \"): update this page.\"))))\n {:manifest manifest\n :work (or (edn \"work.edn\") {})\n :lines (let [l (edn \"lines.edn\")] (if (map? l) l {}))\n :history (vec (keep sane-segment (edn \"history.edn\")))\n :people (or (edn \"people.edn\") {})\n :sounds (into {} (for [[nm b] by :let [[_ h] (re-matches #\"sounds/([0-9a-z]+)\\.wav\" nm)] :when h]\n (let [s (.unwav K b)] [h {:sr (.-sr s) :chans (.-chans s)}])))}))))))\n\n(defn sane-lines [ls]\n (into {} (for [[k v] ls :when (and (string? k) (map? v))]\n [k (cond-> {:name (str (or (:name v) (if (= k main-line) \"main\" \"a line\")))\n :created (if (number? (:created v)) (:created v) 0)\n :archived (true? (:archived v))}\n (sequential? (:aliases v)) (assoc :aliases (vec (filter string? (:aliases v)))))])))\n\n(defn fresh-ids\n \"The segments with the ids made in a local work (local-…, never saved, so never extended there either) made\n ids of their own, and every reference to them (a parent, a merge, a [:merge-from …] event) with them.\"\n [segs]\n (let [m (into {} (for [n segs :when (str/starts-with? (:id n) \"local-\")]\n [(:id n) (str \"f\" (.toString (js/Math.floor (* (js/Math.random) 2176782336)) 36) (.toString (js/Date.now) 36)\n (.toString (js/Math.floor (* (js/Math.random) 1296)) 36))]))\n f (fn [x] (get m x x))]\n (if (empty? m)\n segs\n (mapv (fn [n] (cond-> (-> n (update :id f) (update :parent (fn [p] (when p (f p)))))\n (:merge n) (update :merge (fn [[a i]] [(f a) i]))\n true (update :events (fn [evs] (mapv (fn [e] (if (= :merge-from (first e)) (assoc e 1 (f (second e))) e)) evs)))))\n segs))))\n\n(defn open-work-data!\n \"Makes a new work of what a file holds: solo when there is a database to write it to, else local.\n Promise of its name.\"\n [{:keys [work lines people sounds] :as d} fallback-name]\n (let [history (fresh-ids (:history d))\n nm (str (or (not-empty (str (:name work))) fallback-name \"Opened work\"))\n simul (let [v (:simultaneity-ms work)] (if (and (number? v) (<= 0 v 10000)) v 1500))\n lines (sane-lines lines)\n main (into {} (for [n history :when (nil? (:line n))] [(:id n) n]))\n other (reduce (fn [m n] (assoc-in m [(:line n) (:id n)] n)) {} (filter :line history))]\n (-> (js/Promise.all (clj->js (for [[h s] sounds] (snd/store! h (:sr s) (:chans s)))))\n (.then\n (fn [_]\n (when (seq people) (swap! profiles merge people))\n (if (and @dbref (uid) (:writable @hist))\n (let [db @dbref\n ref (.doc (.collection db (coll-for :solo)))\n id (.-id ref)\n base (str (coll-for :solo) \"/\" id)]\n (busy! \"Opening the file…\")\n (-> (.set ref (clj->js {:name nm :created (js/Date.now) :author (uid) :simultaneity_ms simul :origin \"file\"}))\n (.then (fn [_] (reduce (fn [p n] (.then p (fn [_] (.set (.doc db (str base \"/history/\" (:id n))) (node->js n)))))\n (js/Promise.resolve nil) history)))\n (.then (fn [_] (reduce (fn [p [l e]] (.then p (fn [_] (.set (.doc db (str base \"/lines/\" l)) (clj->js e)))))\n (js/Promise.resolve nil) lines)))\n (.then (fn [_] (busy! nil) (open-work! :solo id nm) nm))))\n (do (open-work! :local \"file\" nm)\n (reset! cache {})\n (swap! hist assoc :nodes main :other other :loaded true)\n (swap! settings assoc :simul-ms simul)\n (swap! line-state assoc :index lines)\n (swap! world assoc :pos (newest-tip) :auto true :prev-pos nil)\n (render-all!)\n (render-lines!)\n nm)))))))\n\n(defn open-work-bytes!\n \"Promise: the work a .kairotic holds (its bytes), opened as a new work.\"\n ([bytes] (open-work-bytes! bytes nil))\n ([bytes fallback]\n (-> (read-work-bytes bytes)\n (.then (fn [d] (open-work-data! d fallback)))\n (.then (fn [nm] (repl-print! \"out\" (esc (str \"; opened from a file: «\" nm \"»\"))) nm)))))\n\n(defn open-work-file!\n \"Asks for a .kairotic file and opens the work it holds, as a new one.\"\n []\n (let [in ($ \"kfile-in\")]\n (set! (.-value in) \"\")\n (.click in)\n :choosing))\n\n(.addEventListener ($ \"kfile-in\") \"change\"\n (fn [e]\n (when-let [f (aget (.. e -target -files) 0)]\n (-> (.arrayBuffer f)\n (.then (fn [ab] (open-work-bytes! (js/Uint8Array. ab) (str/replace (.-name f) #\"\\.kairotic$\" \"\"))))\n (.catch (fn [err]\n (busy! nil)\n (repl-print! \"err\" (esc (str \"Could not open \" (.-name f) \": \" (or (.-message err) err))))))))))\n\n;; ───────────────────────── the Share/Export panel: first, the work as a file ─────────────────────────\n\n(.addEventListener ($ \"ep-file\") \"click\"\n (fn [e]\n (when-let [b (.closest (.-target e) \"[data-kfile]\")]\n (let [anon (.-checked ($ \"ep-anon\"))\n release (= \"release\" (.getAttribute b \"data-kfile\"))]\n (gesture! (str \"(export-work \" (pr-str (cond-> {} release (assoc :release true) anon (assoc :anonymous true))) \")\"))))))\n","page/19-html.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · page · html boxes (issue #146)\n;; Loaded right after 05-gestures (app/index.html), not last: the startup (11) already draws the patch,\n;; and the scene calls these.\n;; An html box draws a small HTML document (kairotic.hiccup) inside the patch: a foreignObject in the\n;; box, holding an element of its own with a shadow root, so its styles stay inside and the page's stay\n;; out. The scene is written again with innerHTML on every change, so each html box keeps its element\n;; here (by engine id) and it is put back into its slot after the scene is written, like the notation of\n;; a score: what is typed or dragged in it is not lost. It is only built again when its view changes.\n;;\n;; Using an element sends the box [:ui outlet value name], a message: while a slider moves only here (and\n;; to a jam), as a knob does while it is dragged. When it is let go, a menu is chosen or a text entered,\n;; the box keeps the value of the named element, as a knob keeps its value in its text: (values! :bN\n;; {name value}), one event of the history (this tab already sent the value: it is not sent again). An\n;; element without a name (a button) is a gesture written in the REPL, (send! :bN [:ui …]).\n\n(defonce html-nodes (atom {})) ; engine id → {:id :view :host :root :built}\n(defonce html-focus (atom nil))\n(defonce html-pressed (atom nil)) ; the element of an html box under a pressed pointer (a slider being dragged) ; {:f :i :start :end}: the element that had the focus before the scene was written\n\n(defn html-slot-svg\n \"The slot of an html box, under its header: its element is put in it after the scene is written.\"\n [id b w h]\n (str \"<foreignObject class=\\\"html-slot\\\" data-box=\\\"\" (esc (name id)) \"\\\" x=\\\"2\\\" y=\\\"\" hdr\n \"\\\" width=\\\"\" (max 0 (- w 4)) \"\\\" height=\\\"\" (max 0 (- h hdr 3)) \"\\\"></foreignObject>\"))\n\n(defn html-values\n \"The values an html box shows: the ones its elements start with, under what it keeps or did since.\"\n [f e]\n (let [b (get-in (current) [:boxes (:id e)])]\n (merge (get-in e [:built :defaults]) (hic/current-values (:data b) (get-in @eng/rt [:states f])))))\n\n(defn html-in-use\n \"The element of an html box whose value is left alone: one being dragged, or a field being typed in.\"\n [e]\n (let [a (.-activeElement (:root e))]\n (or (when (and @html-pressed (.contains (:root e) @html-pressed)) @html-pressed)\n (when (and a (or (= \"TEXTAREA\" (.-tagName a))\n (and (= \"INPUT\" (.-tagName a)) (#{\"text\" \"number\"} (.-type a)))))\n a))))\n\n(defn html-sync-kept!\n \"When the values an html box keeps change (back in the history, kept just now, someone else in a room),\n what its elements did since is forgotten: it shows what it keeps.\"\n [f e]\n (let [kept (hic/clean-values (get-in (current) [:boxes (:id e) :data :values]))]\n (when (not= kept (:kept e))\n (swap! html-nodes assoc-in [f :kept] kept)\n (when (contains? e :kept)\n (swap! eng/rt (fn [rt] (if (get-in rt [:states f]) (update-in rt [:states f] dissoc :values :from) rt)))))))\n\n(defn html-update!\n \"Shows the current values in the html box with engine id f (not in the element being used).\"\n [f]\n (when-let [e (get @html-nodes f)]\n (html-sync-kept! f e)\n (try (hic/refresh! (:built e) (html-values f e) (html-in-use e))\n (catch :default ex (js/console.error \"html box\" ex)))))\n\n(defn refresh-html-boxes! [] (doseq [f (keys @html-nodes)] (html-update! f)))\n\n(defn html-event!\n \"An element of an html box was used: what it gives goes to the box.\"\n [f ev]\n (when-let [e (get @html-nodes f)]\n (let [el (some-> (.-target ev) (.closest \"[data-k]\"))\n k (some-> el .-dataset .-k js/parseInt)\n bind (when (and k (js/isFinite k)) (get-in e [:built :binds k]))]\n (when bind\n (when-let [[v commit?] (hic/element-value el bind (.-type ev))]\n (let [msg [:ui (:out bind) v (:name bind)]]\n (cond\n (not commit?) (send-flat-quiet! f msg)\n ;; a named element: sent here, and kept in the box as one event (a knob let go)\n (:name bind) (do (send-flat-quiet! f msg)\n (gesture! (str \"(values! \" (:id e) \" \" (pr-str {(:name bind) v}) \")\")))\n :else (gesture! (str \"(send! \" (:id e) \" \" (pr-str msg) \")\")))))))))\n\n(defn html-make!\n \"Builds the element of an html box (engine id f, id in the view) for its view.\"\n [f id view]\n (let [host (js/document.createElement \"div\")\n root (.attachShadow host #js {:mode \"open\"})\n style (js/document.createElement \"style\")\n built (hic/build view {})]\n (set! (.-className host) \"html-host\")\n (set! (.-textContent style) hic/base-css)\n (.appendChild root style)\n (when (:node built) (.appendChild root (:node built)))\n ;; what is pressed or typed in it is its own: the patch does not move the box, select it or play\n (doseq [t [\"pointerdown\" \"mousedown\" \"touchstart\" \"dblclick\" \"contextmenu\" \"keydown\" \"keyup\"]]\n (.addEventListener host t (fn [ev] (.stopPropagation ev))))\n (.addEventListener root \"pointerdown\" (fn [ev] (reset! html-pressed (.-target ev))))\n (doseq [t [\"input\" \"change\" \"click\"]]\n (.addEventListener root t (fn [ev] (html-event! f ev))))\n (let [e {:id id :view view :host host :root root :built built}]\n (swap! html-nodes assoc f e)\n e)))\n\n(defn html-save-focus!\n \"Before the scene is written: which element of an html box has the focus (and where its text cursor is).\"\n []\n (reset! html-focus\n (some (fn [[f e]]\n (when-let [a (.-activeElement (:root e))]\n (let [all (vec (array-seq (.querySelectorAll (:root e) \"*\")))\n i (first (keep-indexed (fn [i x] (when (identical? x a) i)) all))]\n (when i {:f f :i i\n :start (try (.-selectionStart a) (catch :default _ nil))\n :end (try (.-selectionEnd a) (catch :default _ nil))}))))\n @html-nodes)))\n\n(defn mount-html-slots!\n \"After the scene is written: each html box gets its element back (built again only if its view changed).\"\n []\n (let [seen (atom #{})]\n (doseq [slot (array-seq (.querySelectorAll ($ \"scene\") \".html-slot\"))]\n (let [id (keyword (.. slot -dataset -box)) b (get-in (current) [:boxes id])]\n ;; the data may have changed (going back in the history): its values are shown again below\n (when b\n (let [f (fid id) view (hic/view-of (:data b)) old (get @html-nodes f)\n e (if (and old (= view (:view old)))\n (do (swap! html-nodes assoc-in [f :id] id) old)\n (html-make! f id view))]\n (swap! seen conj f)\n (.appendChild slot (:host e))))))\n ;; the element that had the focus gets it back\n (when-let [{:keys [f i start end]} @html-focus]\n (when-let [e (get @html-nodes f)]\n (when-let [el (nth (vec (array-seq (.querySelectorAll (:root e) \"*\"))) i nil)]\n (try (.focus el #js {:preventScroll true})\n (when (and (number? start) (number? end)) (.setSelectionRange el start end))\n (catch :default _ nil)))))\n (reset! html-focus nil)\n ;; the elements of boxes no longer drawn are forgotten (they are built again if they come back)\n (swap! html-nodes select-keys @seen)))\n\n;; A message can reach an html box while nothing draws the overlay (the engine stopped, a msg clicked\n;; elsewhere): when the state the engine keeps for one of them changes, they are refreshed, once a frame.\n(defonce html-frame (atom false))\n(defonce html-watch\n (add-watch eng/rt ::html\n (fn [_ _ old new]\n (when (and (not @html-frame) (seq @html-nodes)\n (some (fn [f] (not (identical? (get-in old [:states f]) (get-in new [:states f])))) (keys @html-nodes)))\n (reset! html-frame true)\n (js/requestAnimationFrame (fn [_] (reset! html-frame false) (refresh-html-boxes!)))))))\n\n;; a pointer let go anywhere: no element of an html box is being dragged any more\n(defonce html-release\n (doseq [t [\"pointerup\" \"pointercancel\"]]\n (.addEventListener js/window t (fn [_] (reset! html-pressed nil)) true)))\n","page/20-talk.cljs":"(in-ns 'user)\n;; ───────────────────────── talking in a room (discussion #135, Studies 34 and 36) ─────────────────────────\n;; In a shared room, the pages of the people in it find each other through the relay's rooms (/signal,\n;; beside GUN's /gun: relay 0.3) and open a WebRTC connection to each other: a reliable data channel for\n;; what is said, and an audio and a video track that stay empty until someone turns the microphone or the\n;; camera on (so turning them on never renegotiates). The same socket gives the relay's time: the clock\n;; every page of the room agrees on (talk-now).\n;;\n;; What is said is ephemeral: it lives in these pages. Keeping it makes it a gesture of the work — a\n;; message a text annotation (layer :talk, on the box it names: @b3), a voice note a sample box (its sound\n;; kept by hash, and handed to every page of the room), a frame of someone's camera an image annotation.\n;; What is yours is kept at once; what is someone else's asks them first, and cannot be kept once they\n;; have left. The model is kairotic.talk (tk/…).\n\n;; the room's channels and tempo, in 21-net.cljs\n(declare net-on-share! net-on-tempo! net-joined!)\n\n(defonce talk-room (atom {:ws nil :key nil :id nil :peers {} :n 0 :clock (tk/new-clock) :timer nil}))\n(defonce talk-state (atom {:items {} :order [] :asks [] :mine-asks {} :pieces {} :talking false}))\n(defonce talk-media (atom {:mic nil :cam nil :rec nil}))\n\n(defn talk-name [] (let [n (str/trim (str (some-> ($ \"talk-name\") .-value)))] (if (seq n) n \"someone\")))\n(defn talk-me [] {:id (:id @talk-room) :who (my-author) :name (talk-name)})\n(defn talk-ms [] (+ (.-timeOrigin js/performance) (js/performance.now)))\n\n(defn talk-now\n \"The room's shared time in ms (the relay's clock as this page reads it), or this page's time outside a room.\"\n [] (or (tk/shared-time (:clock @talk-room) (talk-ms)) (talk-ms)))\n\n(defn talk-signal-url\n \"Where the rooms are: ?signal=… if given, else the /signal of the page's relay (nil without a relay).\"\n []\n (or (not-empty (.get (js/URLSearchParams. (.. js/window -location -search)) \"signal\"))\n (tk/signal-url (first (current-relays)))))\n\n;; ───────── bytes ─────────\n\n(defn talk-b64 [buf]\n (let [b (js/Uint8Array. buf) parts #js []]\n (loop [i 0] (when (< i (.-length b))\n (.push parts (.apply (.-fromCharCode js/String) nil (.subarray b i (min (.-length b) (+ i 8192)))))\n (recur (+ i 8192))))\n (js/btoa (.join parts \"\"))))\n\n(defn talk-bytes [s] (let [bin (js/atob s) out (js/Uint8Array. (.-length bin))]\n (dotimes [i (.-length bin)] (aset out i (.charCodeAt bin i))) out))\n\n(defn talk-sha [bytes]\n (.then (.digest js/crypto.subtle \"SHA-256\" bytes)\n (fn [d] (apply str (map (fn [x] (.padStart (.toString x 16) 2 \"0\")) (js/Array.from (.subarray (js/Uint8Array. d) 0 16)))))))\n\n;; ───────── sending ─────────\n\n(defn talk-signal! [m]\n (when-let [ws (:ws @talk-room)] (when (= 1 (.-readyState ws)) (.send ws (js/JSON.stringify (clj->js m))))))\n\n(defn talk-to! [id m]\n (let [dc (get-in @talk-room [:peers id :dc])]\n (if (and dc (= \"open\" (.-readyState dc)))\n (.send dc (js/JSON.stringify (clj->js m)))\n (talk-signal! {:to id :data {:talk m}}))))\n\n(defn talk-to-all! [m] (doseq [id (keys (:peers @talk-room))] (talk-to! id m)))\n\n(defn talk-item [o] (let [m (js->clj o :keywordize-keys true)] (cond-> m (:kind m) (update :kind keyword))))\n\n;; ───────── drawing ─────────\n\n(defn talk-msg! [text kind] (when-let [el ($ \"talk-state\")] (set! (.-innerHTML el) text) (set! (.-className el) (str \"talk-state \" kind))))\n\n(defn render-talk-peers! []\n (when-let [el ($ \"talk-peers\")]\n (let [ps (:peers @talk-room)]\n (set! (.-innerHTML el)\n (if (:id @talk-room)\n (str \"<span class=\\\"tpeer\" (when (:talking @talk-state) \" talk\") \"\\\">\" (esc (talk-name)) \" <i>you</i></span>\"\n (apply str (for [[id p] (sort-by (comp :n val) ps)]\n (str \"<span class=\\\"tpeer\" (when (= \"p2p\" (:state p)) \" p2p\") (when (:talk p) \" talk\") \"\\\" data-peer=\\\"\" (esc id) \"\\\">\"\n (esc (or (not-empty (:name p)) \"someone\")) \" <i>\" (:state p) (when (:talk p) \" · talking\") (when (:camera p) \" · camera\") \"</i></span>\"))))\n \"\")))\n (doseq [[id p] (:peers @talk-room)]\n (when-let [t (.querySelector js/document (str \".ttile[data-peer='\" id \"']\"))]\n (if (:talk p) (.add (.-classList t) \"talk\") (.remove (.-classList t) \"talk\"))))))\n\n(defn talk-anchor-chips [as]\n (apply str (for [a as] (str \"<span class=\\\"tchip\\\">\" (esc (cond (:box a) (str \"@\" (:box a)) (:point a) (str \"#\" (:point a)) :else (str \"^\" (:beat a)))) \"</span>\"))))\n\n(defn talk-item-state [it]\n (let [a (get-in @talk-state [:mine-asks (:id it)])]\n (cond (:kept it) \"<span class=\\\"tst ok\\\">kept</span>\"\n (= a :asked) (str \"<span class=\\\"tst\\\">asked \" (esc (:name it)) \"…</span>\")\n (= a :declined) (str \"<span class=\\\"tst bad\\\">\" (esc (:name it)) \" declined</span>\")\n (= a :gone) (str \"<span class=\\\"tst bad\\\">\" (esc (:name it)) \" has left: it can't be kept</span>\")\n :else \"\")))\n\n(defn render-talk-chat! []\n (when-let [el ($ \"talk-chat\")]\n (let [{:keys [items order]} @talk-state\n at-end (< (- (.-scrollHeight el) (.-scrollTop el) (.-clientHeight el)) 30)]\n (set! (.-innerHTML el)\n (if (seq order)\n (apply str\n (for [id order :let [it (get items id)] :when it]\n (str \"<div class=\\\"titem\" (when (= (my-author) (:author it)) \" mine\") \"\\\" data-item=\\\"\" (esc id) \"\\\">\"\n \"<div class=\\\"twho\\\">\" (esc (:name it)) \"<time>\" (.slice (.toISOString (js/Date. (:t it))) 11 19) \"</time></div>\"\n \"<div class=\\\"tside\\\">\"\n (when-not (:kept it) (str \"<button class=\\\"act small\\\" data-talk-keep=\\\"\" (esc id) \"\\\" title=\\\"Keep it in the work\\\">Keep</button>\"))\n (talk-item-state it) \"</div>\"\n \"<div class=\\\"twhat\\\">\"\n (case (:kind it)\n :message (str (esc (:text it)) (when (seq (:anchors it)) (str \"<div>\" (talk-anchor-chips (:anchors it)) \"</div>\")))\n :note (if (:url it)\n (str \"voice note · \" (.toFixed (or (:dur it) 0) 1) \" s <audio controls preload=\\\"none\\\" src=\\\"\" (:url it) \"\\\"></audio>\")\n \"voice note · arriving…\")\n :frame (str \"<img alt=\\\"a frame of \" (esc (:name it)) \"\\\" src=\\\"\" (:image it) \"\\\">\")\n \"\")\n \"</div></div>\")))\n (if (:id @talk-room)\n \"<p class=\\\"ask-note\\\">What you say here is for the people in the room now; <b>Keep</b> makes it part of the work.</p>\"\n \"\")))\n (when at-end (set! (.-scrollTop el) (.-scrollHeight el))))))\n\n(defn render-talk-asks! []\n (when-let [el ($ \"talk-asks\")]\n (let [as (:asks @talk-state)]\n (set! (.-hidden el) (empty? as))\n (set! (.-innerHTML el)\n (apply str (for [{:keys [item-id by-name kind]} as :let [it (get-in @talk-state [:items item-id])]]\n (str \"<div class=\\\"task\\\"><div><b>\" (esc by-name) \"</b> wants to keep your \"\n (case kind \"note\" \"voice note\" \"frame\" \"video frame\" \"message\")\n (when (= :message (:kind it)) (str \" “\" (esc (subs (:text it) 0 (min 80 (count (:text it))))) \"”\"))\n \" in the work.</div><div class=\\\"ask-bar\\\"><button class=\\\"act primary small\\\" data-talk-answer=\\\"yes\\\" data-id=\\\"\" (esc item-id) \"\\\">Allow</button>\"\n \"<button class=\\\"act small\\\" data-talk-answer=\\\"no\\\" data-id=\\\"\" (esc item-id) \"\\\">Decline</button></div></div>\")))))))\n\n(defn render-talk! []\n (let [in-room (and (= :room (:kind @work)) (talk-signal-url))]\n (when-let [el ($ \"talk-off\")]\n (set! (.-hidden el) (boolean in-room))\n (set! (.-innerHTML el)\n (cond (not= :room (:kind @work)) \"Talking happens in a <b>shared room</b>: open or create one in <b>Sessions</b>, and everyone in it can write, talk, send voice notes and see each other.\"\n :else \"This page has no relay (<code>?peer=off</code>, or claude.ai): rooms to talk need a relay 0.3 (<code>npx @kairotic/relay</code>).\")))\n (when-let [el ($ \"talk-on\")] (set! (.-hidden el) (not in-room))))\n (render-talk-peers!) (render-talk-chat!) (render-talk-asks!))\n\n;; ───────── items: said here, and arriving ─────────\n\n(defn talk-add! [it]\n (when-not (get-in @talk-state [:items (:id it)])\n (swap! talk-state (fn [t] (-> t (assoc-in [:items (:id it)] it) (update :order conj (:id it))))))\n (render-talk-chat!))\n\n(defn talk-say!\n \"Says something to the people in the room: (talk-say! \\\"from #12, @b3 enters\\\").\"\n [text]\n (when-let [m (tk/message (talk-me) text (talk-now))]\n (talk-add! m)\n (talk-to-all! {:item m})\n (:id m)))\n\n;; ───────── keeping: a gesture of the work ─────────\n\n(defn talk-free-y\n \"Where on the paper the next kept thing goes: under the last one of layer :talk.\"\n []\n (let [ms (filter (fn [[_ m]] (and (= :talk (:layer m)) (= :patch (first (:at m))))) (:marks (current)))]\n (+ 30 (reduce max 0 (map (fn [[_ m]] (+ (nth (:at m) 2) (if (= :image (:kind m)) (:h m) 0))) ms)))))\n\n(defn talk-mark! [m] (gesture! (str \"(mark :talk \" (next-mark-id) \" \" (pr-str m) \")\")))\n\n(defn talk-keep-message! [it]\n (let [box (some (fn [a] (when-let [b (:box a)] (let [k (keyword b)] (when (get-in (current) [:boxes k]) k)))) (:anchors it))\n txt (str (:name it) \": \" (:text it))]\n (talk-mark! {:kind :text :at (if box [box 0 -12] [:patch 30 (+ 20 (talk-free-y))]) :txt txt})\n (js/Promise.resolve {})))\n\n(defn talk-keep-note! [it]\n (-> (snd/decode (.-buffer (.slice (talk-bytes (:b64 it)))))\n (.then (fn [{:keys [sr chans]}] (snd/keep! sr chans)))\n (.then (fn [d]\n (let [id (next-id) [x y] (auto-pos)]\n (gesture! (str \"(box \" id \" \\\"sample\\\" \" x \" \" y \")\"))\n (gesture! (str \"(sample! \" id \" \" (pr-str d) \")\"))\n (talk-mark! {:kind :text :at [id 0 -10] :txt (str \"voice note · \" (:name it))})\n {:sound (:audio d)})))))\n\n(defn talk-keep-frame! [it]\n (let [y (+ 20 (talk-free-y))]\n (talk-mark! {:kind :image :at [:patch 30 y] :src (:image it) :w 160 :h 120})\n (talk-mark! {:kind :text :at [:patch 30 (+ y 134)] :txt (str \"frame · \" (:name it))})\n (js/Promise.resolve {})))\n\n(defn talk-kept! [k]\n (when (get-in @talk-state [:items (:item k)]) (swap! talk-state assoc-in [:items (:item k) :kept] true))\n (render-talk-chat!))\n\n(defn talk-keep-now!\n \"Keeps an item (mine, or allowed): a gesture of the work here; every page of the room hears that it was\n kept, and a sound is handed to them under its hash.\"\n [it]\n (-> (case (:kind it) :message (talk-keep-message! it) :note (talk-keep-note! it) :frame (talk-keep-frame! it) (js/Promise.resolve {}))\n (.then (fn [extra]\n (let [k (merge {:item (:id it) :kind (name (:kind it)) :by (talk-name)} extra)]\n (talk-kept! k) (talk-to-all! {:kept k}))))\n (.catch (fn [e] (talk-msg! (str \"could not keep it: \" (esc (or (.-message e) e))) \"bad\")))))\n\n(defn talk-keep!\n \"Keeps something said in the room, by its id: at once if it is yours, else asking whoever said it.\"\n [id]\n (when-let [it (get-in @talk-state [:items id])]\n (let [[what peer] (tk/keep-step (talk-me) it (keys (:peers @talk-room)))]\n (case what\n :keep (talk-keep-now! it)\n :ask (do (swap! talk-state assoc-in [:mine-asks id] :asked)\n (talk-to! peer {:ask {:item-id id :by-name (talk-name) :kind (name (:kind it))}}))\n :gone (swap! talk-state assoc-in [:mine-asks id] :gone))\n (render-talk-chat!))))\n\n(defn talk-answer! [id yes?]\n (let [ask (first (filter #(= id (:item-id %)) (:asks @talk-state)))]\n (swap! talk-state update :asks (fn [as] (vec (remove #(= id (:item-id %)) as))))\n (render-talk-asks!)\n (when ask (talk-to! (:from ask) {:answer {:item-id id :ok yes?}}))))\n\n;; a sound kept by someone else: this page keeps its copy under the same hash, so the work sounds here too\n(defn talk-on-kept! [o]\n (let [k (js->clj o :keywordize-keys true)]\n (talk-kept! k)\n (when-let [h (:sound k)]\n (when-let [it (get-in @talk-state [:items (:item k)])]\n (when (:b64 it)\n (-> (snd/decode (.-buffer (.slice (talk-bytes (:b64 it)))))\n (.then (fn [{:keys [sr chans]}] (snd/store! h sr chans)))\n (.catch (fn [e] (js/console.error \"talk: a kept sound\" e)))))))))\n\n;; ───────── what arrives from a peer ─────────\n\n(defn talk-on! [peer o]\n (cond\n (.-item o) (talk-add! (assoc (talk-item (.-item o)) :peer peer))\n (.-piece o) (let [p (js->clj (.-piece o) :keywordize-keys true)\n [st whole] (tk/gather (:pieces @talk-state) p)]\n (swap! talk-state assoc :pieces st)\n (when whole\n (let [bytes (talk-bytes whole)]\n (.then (talk-sha bytes)\n (fn [h] (when-let [[id it] (first (filter (fn [[_ it]] (= h (:hash it))) (:items @talk-state)))]\n (swap! talk-state update-in [:items id] assoc :b64 whole\n :url (js/URL.createObjectURL (js/Blob. #js [bytes] #js {:type (:mime it)})))\n (render-talk-chat!)))))))\n (.-state o) (let [s (.-state o)]\n (swap! talk-room update-in [:peers peer] merge {:talk (.-talk s) :camera (.-camera s) :name (.-name s) :who (.-who s)})\n (when-let [t (.querySelector js/document (str \".ttile[data-peer='\" peer \"']\"))]\n (set! (.-hidden t) (not (.-camera s)))\n (set! (.-textContent (.querySelector t \".tlabel\")) (.-name s)))\n (render-talk-peers!))\n (.-ask o) (do (swap! talk-state update :asks conj (assoc (js->clj (.-ask o) :keywordize-keys true) :from peer))\n (render-talk-asks!)\n ;; asked: the Room tab says so\n (when-let [t ($ \"tab-talk\")] (.add (.-classList t) \"attn\")))\n (.-answer o) (let [{:keys [item-id ok]} (js->clj (.-answer o) :keywordize-keys true)]\n (swap! talk-state assoc-in [:mine-asks item-id] (if ok :allowed :declined))\n (if ok (talk-keep-now! (get-in @talk-state [:items item-id])) (render-talk-chat!)))\n (.-kept o) (talk-on-kept! (.-kept o))\n ;; @kairotic/net (21-net.cljs): a value shared on a channel, the room's tempo\n (.-share o) (net-on-share! (.-share o))\n (.hasOwnProperty o \"tempo\") (net-on-tempo! (.-tempo o))))\n\n;; ───────── voice notes ─────────\n\n(defn talk-note-start! []\n (when-let [mic (:mic @talk-media)]\n (let [mime (or (first (filter #(.isTypeSupported js/MediaRecorder %) [\"audio/webm;codecs=opus\" \"audio/ogg;codecs=opus\" \"audio/mp4\"])) \"\")\n stream (js/MediaStream. #js [(.clone (first (.getAudioTracks mic)))])\n rec (js/MediaRecorder. stream (if (seq mime) #js {:mimeType mime} #js {}))\n chunks #js []]\n (set! (.-enabled (first (.getAudioTracks stream))) true)\n (set! (.-ondataavailable rec) (fn [e] (.push chunks (.-data e))))\n (set! (.-onstop rec)\n (fn [_]\n (doseq [t (.getTracks stream)] (.stop t))\n (let [blob (js/Blob. chunks #js {:type (.-mimeType rec)})]\n (-> (.arrayBuffer blob)\n (.then (fn [buf]\n (-> (.decodeAudioData (eng/ctx) (.slice buf 0))\n (.then (fn [ab]\n (.then (talk-sha (js/Uint8Array. buf))\n (fn [h]\n (let [b64 (talk-b64 buf)\n it {:kind :note :id (str (my-author) \"-\" (js/Math.round (talk-ms))) :author (my-author)\n :peer (:id @talk-room) :name (talk-name) :t (talk-now) :hash h :mime (.-mimeType rec) :dur (.-duration ab)}]\n (talk-add! (assoc it :b64 b64 :url (js/URL.createObjectURL blob)))\n (talk-to-all! {:item it})\n (doseq [p (tk/pieces h b64)] (talk-to-all! {:piece p}))))))))))\n (.catch (fn [e] (talk-msg! (str \"the note: \" (esc (.-message e))) \"bad\")))))))\n (.start rec)\n (swap! talk-media assoc :rec rec)\n (js/setTimeout (fn [] (when (= rec (:rec @talk-media)) (.stop rec) (swap! talk-media assoc :rec nil))) 60000))))\n\n(defn talk-note-stop! []\n (when-let [rec (:rec @talk-media)] (swap! talk-media assoc :rec nil) (when (= \"recording\" (.-state rec)) (.stop rec))))\n\n;; ───────── microphone, push to talk, camera ─────────\n\n(defn talk-senders! []\n (doseq [[_ p] (:peers @talk-room) :let [pc (:pc p)] :when pc\n tr (.getTransceivers pc) :let [kind (.. tr -receiver -track -kind)]]\n (.catch (.replaceTrack (.-sender tr) (case kind\n \"audio\" (some-> (:mic @talk-media) .getAudioTracks first)\n \"video\" (some-> (:cam @talk-media) .getVideoTracks first)\n nil))\n (fn [_] nil))))\n\n(defn talk-send-state! []\n (talk-to-all! {:state {:talk (:talking @talk-state) :camera (some? (:cam @talk-media)) :name (talk-name) :who (my-author)}}))\n\n(defn talk-push! [on?]\n (when-let [mic (:mic @talk-media)]\n (when (not= on? (:talking @talk-state))\n (doseq [t (.getAudioTracks mic)] (set! (.-enabled t) on?))\n (swap! talk-state assoc :talking on?)\n (when-let [b ($ \"talk-ptt\")] (.setAttribute b \"aria-pressed\" (str on?)) (set! (.-textContent b) (if on? \"Talking…\" \"Hold to talk\")))\n (talk-send-state!) (render-talk-peers!))))\n\n(defn talk-mic! []\n (-> (.getUserMedia js/navigator.mediaDevices #js {:audio #js {:echoCancellation true :noiseSuppression true :autoGainControl true}})\n (.then (fn [s]\n (doseq [t (.getAudioTracks s)] (set! (.-enabled t) false))\n (swap! talk-media assoc :mic s)\n (doseq [id [\"talk-ptt\" \"talk-note\"]] (set! (.-disabled ($ id)) false))\n (set! (.-disabled ($ \"talk-mic\")) true)\n (talk-senders!)))\n (.catch (fn [e] (talk-msg! (str \"microphone: \" (esc (.-message e))) \"bad\")))))\n\n(defn talk-own-tile! []\n (let [t (or (.querySelector js/document \".ttile[data-peer='me']\")\n (let [d (js/document.createElement \"div\")]\n (set! (.-className d) \"ttile\") (.setAttribute d \"data-peer\" \"me\")\n (set! (.-innerHTML d) \"<video autoplay playsinline muted></video><span class=\\\"tlabel\\\"></span><button class=\\\"act small\\\" data-talk-frame=\\\"me\\\">Keep a frame</button>\")\n (.prepend ($ \"talk-tiles\") d) d))]\n (set! (.-textContent (.querySelector t \".tlabel\")) (str (talk-name) \" (you)\"))\n (set! (.-srcObject (.querySelector t \"video\")) (:cam @talk-media))\n (set! (.-hidden t) (nil? (:cam @talk-media)))))\n\n(defn talk-cam! []\n (if-let [c (:cam @talk-media)]\n (do (doseq [t (.getTracks c)] (.stop t))\n (swap! talk-media assoc :cam nil) (talk-senders!) (talk-own-tile!) (talk-send-state!)\n (.setAttribute ($ \"talk-cam\") \"aria-pressed\" \"false\"))\n (-> (.getUserMedia js/navigator.mediaDevices #js {:video #js {:width 320 :height 240 :frameRate 15}})\n (.then (fn [s] (swap! talk-media assoc :cam s) (talk-senders!) (talk-own-tile!) (talk-send-state!)\n (.setAttribute ($ \"talk-cam\") \"aria-pressed\" \"true\")))\n (.catch (fn [e] (talk-msg! (str \"camera: \" (esc (.-message e))) \"bad\"))))))\n\n(defn talk-frame!\n \"A frame of a camera tile (\\\"me\\\" or a peer's id), small, as something said in the room (and so kept like the rest).\"\n [peer-id]\n (when-let [v (.querySelector js/document (str \".ttile[data-peer='\" peer-id \"'] video\"))]\n (when (pos? (.-videoWidth v))\n (let [c (js/document.createElement \"canvas\")]\n (set! (.-width c) 160) (set! (.-height c) 120)\n (.drawImage (.getContext c \"2d\") v 0 0 160 120)\n (let [mine? (= peer-id \"me\") p (get-in @talk-room [:peers peer-id])\n it {:kind :frame :id (str \"f-\" (js/Math.round (talk-ms)) \"-\" (rand-int 1e6))\n :author (if mine? (my-author) (:who p)) :peer (if mine? (:id @talk-room) peer-id)\n :name (if mine? (talk-name) (:name p)) :t (talk-now) :image (.toDataURL c \"image/jpeg\" 0.6)}]\n (talk-add! it) (talk-to-all! {:item it})\n (:id it))))))\n\n;; ───────── the room: its peers and their connections ─────────\n\n(defn talk-tile! [id]\n (or (.querySelector js/document (str \".ttile[data-peer='\" id \"']\"))\n (let [d (js/document.createElement \"div\")]\n (set! (.-className d) \"ttile\") (.setAttribute d \"data-peer\" id) (set! (.-hidden d) true)\n (set! (.-innerHTML d) (str \"<video autoplay playsinline muted></video><span class=\\\"tlabel\\\"></span>\"\n \"<button class=\\\"act small\\\" data-talk-frame=\\\"\" (esc id) \"\\\">Keep a frame</button>\"))\n (.append ($ \"talk-tiles\") d) d)))\n\n(defn talk-add-peer! [id nm]\n (swap! talk-room (fn [r] (-> r (assoc-in [:peers id] {:name nm :n (:n r) :state \"relay\" :pending []}) (update :n inc))))\n (render-talk-peers!))\n\n(defn talk-drop-peer! [id]\n (when-let [pc (get-in @talk-room [:peers id :pc])] (.close pc))\n (some-> (.querySelector js/document (str \".ttile[data-peer='\" id \"']\")) .remove)\n (some-> (.querySelector js/document (str \"audio.taudio[data-peer='\" id \"']\")) .remove)\n (swap! talk-room update :peers dissoc id)\n (swap! talk-state update :asks (fn [as] (vec (remove #(= id (:from %)) as))))\n (render-talk-asks!) (render-talk-peers!))\n\n(defn talk-pc! [id initiator?]\n (let [pc (js/RTCPeerConnection. #js {:iceServers #js [#js {:urls \"stun:stun.l.google.com:19302\"}]})\n dc (.createDataChannel pc \"talk\" #js {:negotiated true :id 1 :ordered true})\n state! (fn [s] (when (get-in @talk-room [:peers id]) (swap! talk-room assoc-in [:peers id :state] s) (render-talk-peers!)))]\n (set! (.-onicecandidate pc) (fn [ev] (when-let [c (.-candidate ev)] (talk-signal! {:to id :data {:candidate (.toJSON c)}}))))\n (set! (.-onopen dc) (fn [_] (state! \"p2p\") (talk-send-state!)))\n (set! (.-onclose dc) (fn [_] (state! \"relay\")))\n (set! (.-onmessage dc) (fn [ev] (talk-on! id (js/JSON.parse (.-data ev)))))\n (set! (.-ontrack pc)\n (fn [ev]\n (let [tr (.-track ev) s (js/MediaStream. #js [tr])]\n (if (= \"audio\" (.-kind tr))\n (let [a (or (.querySelector js/document (str \"audio.taudio[data-peer='\" id \"']\"))\n (let [a (js/document.createElement \"audio\")]\n (set! (.-className a) \"taudio\") (.setAttribute a \"data-peer\" id) (set! (.-autoplay a) true)\n (.append js/document.body a) a))]\n (set! (.-srcObject a) s) (.catch (.play a) (fn [_] nil)))\n (let [t (talk-tile! id)]\n (set! (.-srcObject (.querySelector t \"video\")) s)\n (set! (.-textContent (.querySelector t \".tlabel\")) (or (get-in @talk-room [:peers id :name]) \"\")))))))\n (when initiator?\n (.addTransceiver pc \"audio\" #js {:direction \"sendrecv\"})\n (.addTransceiver pc \"video\" #js {:direction \"sendrecv\"}))\n (swap! talk-room update-in [:peers id] merge {:pc pc :dc dc})\n (when initiator?\n (talk-senders!)\n (-> (.createOffer pc) (.then #(.setLocalDescription pc %))\n (.then #(talk-signal! {:to id :data {:sdp (.toJSON (.-localDescription pc))}}))))\n pc))\n\n(defn talk-from! [id data]\n (when (get-in @talk-room [:peers id])\n (cond\n (.-sdp data)\n (let [d (.-sdp data) pc (or (get-in @talk-room [:peers id :pc]) (talk-pc! id false))]\n (-> (.setRemoteDescription pc d)\n (.then (fn [_]\n (doseq [c (get-in @talk-room [:peers id :pending])] (.catch (.addIceCandidate pc c) (fn [_] nil)))\n (swap! talk-room assoc-in [:peers id :pending] [])\n (when (= \"offer\" (.-type d))\n (doseq [tr (.getTransceivers pc)] (set! (.-direction tr) \"sendrecv\"))\n (talk-senders!)\n (-> (.createAnswer pc) (.then #(.setLocalDescription pc %))\n (.then #(talk-signal! {:to id :data {:sdp (.toJSON (.-localDescription pc))}}))))))\n (.catch (fn [e] (js/console.error \"talk: WebRTC\" e)))))\n (.-candidate data)\n (let [pc (get-in @talk-room [:peers id :pc])]\n (if (and pc (.-remoteDescription pc))\n (.catch (.addIceCandidate pc (.-candidate data)) (fn [_] nil))\n (swap! talk-room update-in [:peers id :pending] conj (.-candidate data))))\n (.-talk data) (talk-on! id (.-talk data)))))\n\n(defn talk-on-signal! [f]\n (cond\n (.-pong f) (swap! talk-room update :clock tk/clock-sample (.-pong f) (.-t f) (talk-ms))\n (.-welcome f) (let [w (.-welcome f)]\n (swap! talk-room assoc :id (.-id w))\n (talk-msg! \"in the room\" \"ok\")\n (doseq [p (.-peers w)] (talk-add-peer! (.-id p) (.-name p)) (talk-pc! (.-id p) true))\n (render-talk!))\n (.-joined f) (let [j (.-joined f)] (talk-add-peer! (.-id j) (.-name j)) (net-joined! (.-id j)))\n (.-left f) (talk-drop-peer! (.-left f))\n (.-from f) (talk-from! (.-from f) (.-data f))\n (.-error f) (talk-msg! (esc (.-error f)) \"bad\")))\n\n(defn talk-ping! [] (talk-signal! {:ping (talk-ms)}))\n\n(defn talk-leave! []\n (when-let [t (:timer @talk-room)] (js/clearInterval t))\n (doseq [id (keys (:peers @talk-room))] (talk-drop-peer! id))\n (when-let [ws (:ws @talk-room)] (set! (.-onclose ws) nil) (.close ws))\n (swap! talk-room assoc :ws nil :key nil :id nil :peers {} :clock (tk/new-clock) :timer nil)\n ;; what was said goes with the room\n (reset! talk-state {:items {} :order [] :asks [] :mine-asks {} :pieces {} :talking false})\n (render-talk!))\n\n(defn talk-join! [k url]\n (talk-leave!)\n (let [ws (try (js/WebSocket. url) (catch :default e (talk-msg! (esc (.-message e)) \"bad\") nil))]\n (when ws\n (swap! talk-room assoc :ws ws :key k)\n (talk-msg! \"connecting…\" \"\")\n (set! (.-onopen ws)\n (fn [_]\n (talk-signal! {:join k :name (talk-name)})\n (doseq [i (range 8)] (js/setTimeout talk-ping! (* 60 i)))\n (swap! talk-room assoc :timer (js/setInterval talk-ping! 2000))))\n (set! (.-onmessage ws) (fn [ev] (talk-on-signal! (js/JSON.parse (.-data ev)))))\n (set! (.-onerror ws) (fn [_] (talk-msg! \"the relay has no rooms (relay 0.3 or later)\" \"bad\")))\n (set! (.-onclose ws) (fn [_] (when (= ws (:ws @talk-room)) (talk-msg! \"out of the room\" \"\") (swap! talk-room assoc :ws nil :id nil) (render-talk!)))))))\n\n(defn talk-sync!\n \"In the room the open work is (a shared room, with a relay), or in none.\"\n []\n (let [url (talk-signal-url)\n k (when (and url (= :room (:kind @work)) (:id @work)) (str \"kairotic-\" (:id @work)))]\n (cond (and k (not= k (:key @talk-room))) (talk-join! k url)\n (and (nil? k) (:key @talk-room)) (talk-leave!)\n :else (render-talk!))))\n\n(defn talk-audio-in\n \"Promise of the bytes of voice received from the room so far (all its connections): to see that it flows.\"\n []\n (js/Promise.all (clj->js (for [[_ p] (:peers @talk-room) :when (:pc p)]\n (.then (.getStats (:pc p))\n (fn [r] (let [n (atom 0)]\n (.forEach r (fn [s & _] (when (and (= \"inbound-rtp\" (.-type s)) (= \"audio\" (.-kind s)))\n (swap! n + (or (.-bytesReceived s) 0)))))\n @n)))))))\n\n;; ───────── wiring ─────────\n\n(defn talk-hold! [el down up]\n (.addEventListener el \"pointerdown\" (fn [e] (when-not (.-disabled el) (.preventDefault e) (down))))\n (doseq [t [\"pointerup\" \"pointercancel\" \"pointerleave\"]] (.addEventListener el t (fn [_] (up)))))\n\n(when ($ \"panel-talk\")\n (set! (.-value ($ \"talk-name\")) (or (try (.getItem js/localStorage \"kairotic-name\") (catch :default _ nil))\n (str \"player \" (.toUpperCase (.slice (.toString (js/Math.random) 36) 2 5)))))\n (.addEventListener ($ \"talk-name\") \"change\"\n (fn [_] (try (.setItem js/localStorage \"kairotic-name\" (talk-name)) (catch :default _ nil)) (talk-send-state!) (render-talk-peers!)))\n (.addEventListener ($ \"talk-send\") \"click\" (fn [_] (talk-say! (.-value ($ \"talk-say\"))) (set! (.-value ($ \"talk-say\")) \"\")))\n (.addEventListener ($ \"talk-say\") \"keydown\"\n (fn [e] (when (= \"Enter\" (.-key e)) (.stopPropagation e) (talk-say! (.-value ($ \"talk-say\"))) (set! (.-value ($ \"talk-say\")) \"\"))))\n (.addEventListener ($ \"talk-mic\") \"click\" (fn [_] (talk-mic!)))\n (.addEventListener ($ \"talk-cam\") \"click\" (fn [_] (talk-cam!)))\n (talk-hold! ($ \"talk-ptt\") #(talk-push! true) #(talk-push! false))\n (talk-hold! ($ \"talk-note\") (fn [] (.setAttribute ($ \"talk-note\") \"aria-pressed\" \"true\") (talk-note-start!))\n (fn [] (.setAttribute ($ \"talk-note\") \"aria-pressed\" \"false\") (talk-note-stop!)))\n (.addEventListener ($ \"panel-talk\") \"click\"\n (fn [e] (let [t (.-target e)]\n (when-let [id (.getAttribute t \"data-talk-keep\")] (talk-keep! id))\n (when-let [a (.getAttribute t \"data-talk-answer\")] (talk-answer! (.getAttribute t \"data-id\") (= a \"yes\")))\n (when-let [p (.getAttribute t \"data-talk-frame\")] (talk-frame! p)))))\n (.addEventListener ($ \"tab-talk\") \"click\" (fn [_] (.remove (.-classList ($ \"tab-talk\")) \"attn\") (render-talk!)))\n (add-watch work :talk (fn [_ _ o n] (when (not= [(:kind o) (:id o)] [(:kind n) (:id n)]) (talk-sync!))))\n (talk-sync!))\n","page/21-net.cljs":"(in-ns 'user)\n;; ───────────────────────── the room's channels and tempo (@kairotic/net, discussion #135) ─────────────────────────\n;; Boxes of @kairotic/net (share, shared, pulse) reach the room through window.kairoticRoom, so a package\n;; never touches the page: a value shared on a channel goes to every page of the room (this one too, as\n;; a bus), and the tempo is one for the whole room — started on any page, the same beat on all, from the\n;; room's clock (talk-now). Outside a room they work for this page alone.\n\n(defonce net-listeners (atom {})) ; channel → {key fn}\n(defonce net-tempo (atom nil)) ; {:t0 shared-ms :bpm b} or nil\n(defonce net-tempo-watchers (atom {})) ; key → fn\n\n(defn net-deliver! [ch v from]\n (doseq [[_ f] (get @net-listeners ch)] (try (f v from) (catch :default e (js/console.error \"share\" e)))))\n\n(defn net-share!\n \"Shares a value on a channel of the room: (net-share! \\\"notes\\\" [60 64 67]).\"\n [ch v]\n (let [edn (pr-str v)]\n (when (< (count edn) 60000)\n (talk-to-all! {:share {:ch (str ch) :v edn :from (talk-name)}})\n (net-deliver! (str ch) v (talk-name)))\n v))\n\n(defn net-on-share! [o]\n (let [v (try (clojure.edn/read-string {:default (fn [_ x] x)} (.-v o)) (catch :default _ ::bad))]\n (when-not (= v ::bad) (net-deliver! (str (.-ch o)) v (.-from o)))))\n\n(defn net-set-tempo!\n \"The tempo of the room: {:t0 shared-ms :bpm b} (beat 0 at t0), or nil to stop. Every page of the room hears it.\"\n [t]\n (reset! net-tempo t)\n (talk-to-all! {:tempo t})\n t)\n\n(defn net-on-tempo! [t]\n (reset! net-tempo (when t {:t0 (.-t0 t) :bpm (.-bpm t)})))\n\n(defn net-joined! [id] (talk-to! id {:tempo @net-tempo}))\n\n(defn net-beat \"The beat of the room now (fractional), or nil without a tempo.\" []\n (when-let [{:keys [t0 bpm]} @net-tempo] (/ (* (- (talk-now) t0) bpm) 60000)))\n\n(defn net-start!\n \"Starts the room's tempo at bpm: beat 0 on the next whole second plus one, the same for every page.\"\n [bpm]\n (let [n (talk-now)]\n (net-set-tempo! {:t0 (+ 1000 (* 1000 (js/Math.ceil (/ n 1000)))) :bpm (api/clamp bpm 20 400)})))\n\n(defn net-bpm!\n \"Changes the tempo of the room keeping the beat where it is (no jump).\"\n [bpm]\n (if-let [b (net-beat)]\n (let [bpm (api/clamp bpm 20 400) n (talk-now)]\n (net-set-tempo! {:t0 (- n (/ (* b 60000) bpm)) :bpm bpm}))\n (net-start! bpm)))\n\n(add-watch net-tempo :watchers (fn [_ _ _ t] (doseq [[_ f] @net-tempo-watchers] (try (f t) (catch :default _ nil)))))\n\n;; what the boxes of @kairotic/net see\n(set! (.-kairoticRoom js/window)\n #js {:now (fn [] (talk-now))\n :inRoom (fn [] (boolean (:id @talk-room)))\n :share (fn [ch v] (net-share! ch v))\n :onShare (fn [ch f] (let [k (gensym \"l\")] (swap! net-listeners assoc-in [(str ch) k] f)\n (fn [] (swap! net-listeners update (str ch) dissoc k))))\n :tempo (fn [] @net-tempo)\n :start (fn [bpm] (net-start! bpm))\n :bpm (fn [bpm] (net-bpm! bpm))\n :stop (fn [] (net-set-tempo! nil))})\n\n;; ───────── the tempo in the Room tab, with a metronome ─────────\n\n(defonce net-metro (atom {:on false :until nil}))\n\n(defn net-click! [at-ms down?]\n (let [c (eng/ctx) t (+ (.-currentTime c) (max 0 (/ (- at-ms (talk-now)) 1000)))\n o (.createOscillator c) g (.createGain c)]\n (set! (.. o -frequency -value) (if down? 1760 1320))\n (.setValueAtTime (.-gain g) 0.3 t) (.exponentialRampToValueAtTime (.-gain g) 0.001 (+ t 0.05))\n (.connect o g) (.connect g (.-destination c)) (.start o t) (.stop o (+ t 0.06))))\n\n(defn net-text! [el v] (when (and el (not= v (.-textContent el))) (set! (.-textContent el) v)))\n\n(defn net-frame! [& _]\n (let [t @net-tempo\n shown (some-> ($ \"panel-talk\") .-hidden not)]\n ;; nothing to draw unless the Room tab is open, and nothing to do without a tempo or a room\n (when (and shown (or t (:id @talk-room)))\n (let [n (talk-now) el ($ \"net-beat\") b (net-beat)]\n (net-text! el (cond (nil? b) \"·\" (neg? b) (str \"in \" (.toFixed (/ (- (:t0 t) n) 1000) 1) \" s\") :else (str (inc (js/Math.floor b)))))\n (when el (.toggle (.-classList el) \"on\" (boolean (and b (>= b 0) (< (mod b 1) 0.15)))))\n (net-text! ($ \"net-clock\") (if (tk/clock-offset (:clock @talk-room)) (str \"clock ±\" (.toFixed (tk/clock-error (:clock @talk-room)) 1) \" ms\") \"\"))))\n ;; the metronome: clicks 150 ms ahead on the audio clock\n (when (and t (:on @net-metro))\n (let [n (talk-now) from (max n (or (:until @net-metro) n)) to (+ n 150)\n per (/ 60000 (:bpm t))]\n (doseq [k (range (js/Math.ceil (/ (* (- from (:t0 t)) (:bpm t)) 60000)) (inc (js/Math.floor (/ (* (- to (:t0 t)) (:bpm t)) 60000))))\n :let [at (+ (:t0 t) (* k per))] :when (and (>= k 0) (>= at from) (< at to))]\n (net-click! at (zero? (mod k 4))))\n (swap! net-metro assoc :until to))))\n (js/requestAnimationFrame net-frame!))\n\n(when ($ \"net-start\")\n (.addEventListener ($ \"net-start\") \"click\" (fn [_] (.resume (eng/ctx)) (net-start! (js/parseFloat (.-value ($ \"net-bpm\")))) nil))\n (.addEventListener ($ \"net-stop\") \"click\" (fn [_] (net-set-tempo! nil) nil))\n (.addEventListener ($ \"net-bpm\") \"change\" (fn [_] (when @net-tempo (net-bpm! (js/parseFloat (.-value ($ \"net-bpm\"))))) nil))\n (.addEventListener ($ \"net-metro\") \"change\"\n (fn [_] (.resume (eng/ctx)) (swap! net-metro assoc :on (.-checked ($ \"net-metro\")) :until nil) nil))\n (add-watch net-tempo :tab (fn [_ _ _ t] (when (and t ($ \"net-bpm\")) (set! (.-value ($ \"net-bpm\")) (str (js/Math.round (:bpm t)))))))\n (net-frame!))\n","page/22-learn.cljs":"(in-ns 'user)\n;; ───────────────────────── learn: move a controller, and it moves a box (discussion #135) ─────────────────────────\n;; (learn :b5), or Learn with a box selected: the next controller that moves — a MIDI controller or key, a\n;; gamepad's stick or button, a phone's tilt, an OSC address — is wired to that box, as gestures of the\n;; work anyone can read and change: the source (midiin, gamepad, motion or oscin; one already in the patch\n;; if there is one) → control (that one control) → scale (from the controller's range to the box's: a\n;; knob's min and max, logarithmic if it is) → the box. While it waits, this page listens to the page's MIDI,\n;; the gamepads, the motion of the device and the OSC bridge if one is open; ▶ is not needed.\n;;\n;; Two scopes, asked each time (the last one is remembered):\n;; for the work the chain above, in the patch: the same for everyone in a room (each page reads its own\n;; devices), part of the piece\n;; only for me nothing in the work: the mapping is kept in this browser, for this work, and the page\n;; applies it as your own gesture — so in a jam the others hear it too (13-perform.cljs).\n;; Each player brings their own instrument without touching the work of the others.\n\n(defonce learn-state (atom nil)) ; {:target :bN :off [fns] :base {...}} while it waits\n\n(defn learn-banner! [html]\n (let [el (floating \"learn-pop\" \"perform-pop\")]\n (if html\n (do (set! (.-innerHTML el) html) (set! (.-hidden el) false))\n (set! (.-hidden el) true))))\n\n(defn learn-stop! []\n (when-let [s @learn-state] (doseq [f (:off s)] (try (f) (catch :default _ nil))))\n (reset! learn-state nil)\n (when-let [b ($ \"learn-toggle\")] (.remove (.-classList b) \"on\"))\n (learn-banner! nil))\n\n;; ── what a source is, and how to reach its events ──\n;; kind → [the source class, its event outlet, the controller's range]\n(def learn-sources\n {\"cc\" [\"midiin\" 2 [0 1]] \"note\" [\"midiin\" 2 [0 1]] \"pad\" [\"gamepad\" 0 [-1 1]]\n \"tilt\" [\"motion\" 2 [0 1]] \"osc\" [\"oscin\" 0 [0 1]]})\n\n(defn learn-range\n \"The range of a box's input: a knob's (or any class with :min and :max) [min max log?], else [0 1 false].\"\n [b]\n (let [d (comp/lookup (comp/klass (:text b))) a (when d (comp/args-for d (:text b)))]\n (if (and (map? a) (number? (:min a)) (number? (:max a)))\n [(:min a) (:max a) (boolean (:log a))]\n [0 1 false])))\n\n(defn learn-ranges\n \"[in-lo in-hi lo hi log?]: the controller's range and the box's, for spec (see learn-wire!).\"\n [target spec]\n (let [[_ _ [in-lo in-hi]] (get learn-sources (first spec))\n ;; a gamepad's buttons go 0…1, its sticks −1…1\n [in-lo in-hi] (if (and (= \"pad\" (first spec)) (not (re-matches #\"lx|ly|rx|ry|a\\d+\" (second spec)))) [0 1] [in-lo in-hi])\n [lo hi lg] (learn-range (get-in (current) [:boxes target]))]\n [in-lo in-hi lo hi lg]))\n\n(defn learn-wire!\n \"Wires the control found (spec: [kind which & more], as the words of a control box) to the box learning.\"\n [target spec]\n (let [p (current) tb (get-in p [:boxes target])\n [cls outlet] (get learn-sources (first spec))\n [in-lo in-hi lo hi lg] (learn-ranges target spec)\n existing (some (fn [[id b]] (when (= cls (comp/klass (:text b))) id)) (sort-by key (:boxes p)))\n x (:x tb) y (:y tb)\n src (or existing (next-id))]\n (when-not existing (gesture! (str \"(box \" src \" \" (pr-str cls) \" \" (- x 0) \" \" (max 0 (- y 150)) \")\")))\n (let [ctl (next-id)]\n (gesture! (str \"(box \" ctl \" \" (pr-str (str \"control \" (str/join \" \" spec))) \" \" x \" \" (max 0 (- y 105)) \")\"))\n (let [sc (next-id)]\n (gesture! (str \"(box \" sc \" \" (pr-str (str \"scale \" (api/nice in-lo) \" \" (api/nice in-hi) \" \" (api/nice lo) \" \" (api/nice hi) (when lg \" log\"))) \" \" x \" \" (max 0 (- y 60)) \")\"))\n (gesture! (str \"(connect \" src \" \" outlet \" \" ctl \" 0)\"))\n (gesture! (str \"(connect \" ctl \" 0 \" sc \" 0)\"))\n (gesture! (str \"(connect \" sc \" 0 \" target \" 0)\"))\n ;; an OSC value's range is unknown: the scale learns it from the next values\n (when (= \"osc\" (first spec)) (send! sc :learn))\n [src ctl sc]))))\n\n(declare mine-add!)\n\n(defn learn-found! [spec]\n (when-let [{:keys [target scope]} @learn-state]\n (learn-stop!)\n (if (= scope :me)\n (do (mine-add! {:spec spec :box target :range (learn-ranges target spec)})\n (repl-print! \"out\" (esc (str \"; learnt for you only: \" (str/join \" \" spec) \" → \" target \" (in this browser, not in the work: (my-controls))\")))\n spec)\n (let [made (learn-wire! target spec)]\n (repl-print! \"out\" (esc (str \"; learnt for the work: \" (str/join \" \" spec) \" → \" target (when (= \"osc\" (first spec)) \" (move it end to end: the scale learns its range)\"))))\n made))))\n\n;; ── listening, while it waits ──\n\n(defn learn-listen-midi! []\n (let [on (fn [e] (let [[s a b] (js/Array.from (.-data e)) hi (bit-and s 0xF0) ch (inc (bit-and s 0x0F))]\n (cond (and (= hi 0xB0) (not (#{0 6 32 38 98 99 100 101} a))) (learn-found! [\"cc\" (str a) (str ch)])\n (and (= hi 0x90) (pos? b)) (learn-found! [\"note\" (str a)]))))\n ins (atom [])]\n (when-let [p (or (.-kairoticMidi js/window) (when (.-requestMIDIAccess js/navigator)\n (let [p (.requestMIDIAccess js/navigator #js {:sysex false})]\n (set! (.-kairoticMidi js/window) p) p)))]\n (.then p (fn [m] (when @learn-state\n (reset! ins (vec (js/Array.from (.values (.-inputs m)))))\n (doseq [i @ins] (.addEventListener i \"midimessage\" on)))))\n (.catch p (fn [_] nil)))\n (fn [] (doseq [i @ins] (.removeEventListener i \"midimessage\" on)))))\n\n(defn learn-pads []\n (let [raw (or (.-kairoticFakePads js/window) (when (.-getGamepads js/navigator) (.getGamepads js/navigator)) #js [])]\n (vec (for [p (js/Array.from raw) :when p]\n {:index (.-index p) :std (= \"standard\" (.-mapping p)) :axes (vec (js/Array.from (.-axes p)))\n :buttons (mapv (fn [b] (.-pressed b)) (js/Array.from (.-buttons p)))}))))\n\n(def learn-pad-buttons [\"a\" \"b\" \"x\" \"y\" \"lb\" \"rb\" \"lt\" \"rt\" \"back\" \"start\" \"ls\" \"rs\" \"up\" \"down\" \"left\" \"right\" \"home\"])\n\n(defn learn-listen-pads! []\n (let [base (atom (learn-pads)) alive (atom true)]\n (letfn [(poll [& _]\n (when (and @alive @learn-state)\n (let [now (learn-pads)\n found (first (for [p now :let [b (first (filter #(= (:index %) (:index p)) @base))]\n x (concat\n (for [[k v] (map-indexed vector (:axes p))\n :when (> (js/Math.abs (- v (get-in b [:axes k] 0))) 0.5)]\n (if (and (:std p) (< k 4)) (nth [\"lx\" \"ly\" \"rx\" \"ry\"] k) (str \"a\" k)))\n (for [[k on] (map-indexed vector (:buttons p))\n :when (and on (not (get-in b [:buttons k])))]\n (if (and (:std p) (< k 17)) (nth learn-pad-buttons k) (str \"b\" k))))]\n x))]\n (if found (learn-found! [\"pad\" found]) (js/requestAnimationFrame poll)))))]\n (poll))\n (fn [] (reset! alive false))))\n\n(defn learn-listen-motion! []\n (let [base (atom nil)\n on (fn [e] (when (number? (.-gamma e))\n (if-let [[g b] @base]\n (cond (> (js/Math.abs (- (.-gamma e) g)) 20) (learn-found! [\"tilt\" \"x\"])\n (> (js/Math.abs (- (.-beta e) b)) 20) (learn-found! [\"tilt\" \"y\"]))\n (reset! base [(.-gamma e) (.-beta e)]))))]\n (.addEventListener js/window \"deviceorientation\" on)\n (fn [] (.removeEventListener js/window \"deviceorientation\" on))))\n\n(defn learn-listen-osc! []\n ;; only through a bridge an oscin or oscout of this page has already opened\n (let [socks (when-let [all (.-kairoticOsc js/window)] (vec (js/Object.values all)))\n on (fn [f] (when (and (.-address f) (number? (aget (or (.-args f) #js []) 0))) (learn-found! [\"osc\" (.-address f)])))]\n (doseq [s socks] (.push (.-listeners s) on))\n (fn [] (doseq [s socks] (set! (.-listeners s) (.filter (.-listeners s) (fn [x & _] (not= x on))))))))\n\n;; ── only for me: mappings kept in this browser, for this work, applied as your own gestures ──\n\n(defonce learn-scope (atom (if (= \"me\" (try (.getItem js/localStorage \"kairotic-learn-scope\") (catch :default _ nil))) :me :work)))\n(defonce mine (atom [])) ; [{:spec [...] :box :bN :range [in-lo in-hi lo hi log?]} …] of the open work\n(defonce mine-off (atom [])) ; what stops the listeners\n(defonce mine-last (atom {})) ; [spec box] → last value sent (a moving stick or tilt sends only changes)\n(defonce mine-raw (atom {})) ; spec → last reading of a polled controller (only a move plays)\n\n(declare mine-apply!)\n\n(defn mine-moved!\n \"A reading of a controller that is read all the time (a stick, a tilt): it plays only when it moves, not\n the first time it is read (the box keeps its value until the controller is touched).\"\n [spec v]\n (let [old (get @mine-raw spec)]\n (swap! mine-raw assoc spec v)\n (when (and (some? old) (> (js/Math.abs (- v old)) 0.003)) (mine-apply! spec v))))\n\n(defn mine-key [] (str \"kairotic-controls:\" (name (or (:kind @work) :local)) \":\" (or (:id @work) \"local\")))\n\n(defn mine-save! []\n (try (.setItem js/localStorage (mine-key) (pr-str @mine)) (catch :default _ nil)))\n\n(defn mine-load! []\n (reset! mine (or (try (some-> (.getItem js/localStorage (mine-key)) clojure.edn/read-string vec) (catch :default _ nil)) [])))\n\n(defn mine-value\n \"A controller's value through a mapping's ranges: what goes to the box.\"\n [[in-lo in-hi lo hi lg] v]\n (let [u (api/clamp (if (== in-lo in-hi) 0 (/ (- v in-lo) (- in-hi in-lo))) 0 1)]\n (api/nice (if (and lg (pos? lo) (pos? hi)) (* lo (js/Math.pow (/ hi lo) u)) (+ lo (* u (- hi lo)))))))\n\n(defn mine-apply!\n \"A controller (spec as Learn writes it) moved to v: every mapping of it plays its box, as a gesture of yours.\"\n [spec v]\n (doseq [{s :spec box :box r :range} @mine\n :when (and (= s spec) (get-in (current) [:boxes box]))]\n (let [out (mine-value r v)]\n (when (not= out (get @mine-last [spec box]))\n (swap! mine-last assoc [spec box] out)\n (inject-local! box 0 out)))))\n\n(defn mine-listen! []\n (doseq [f @mine-off] (try (f) (catch :default _ nil)))\n (reset! mine-off [])\n (let [kinds (set (map (comp first :spec) @mine))]\n (when (or (kinds \"cc\") (kinds \"note\"))\n (let [on (fn [e] (let [[s a b] (js/Array.from (.-data e)) hi (bit-and s 0xF0) ch (inc (bit-and s 0x0F))]\n (cond (= hi 0xB0) (do (mine-apply! [\"cc\" (str a) (str ch)] (/ b 127)) (mine-apply! [\"cc\" (str a)] (/ b 127)))\n (= hi 0x90) (mine-apply! [\"note\" (str a)] (/ b 127))\n (= hi 0x80) (mine-apply! [\"note\" (str a)] 0))))\n ins (atom [])]\n (when-let [p (or (.-kairoticMidi js/window) (when (.-requestMIDIAccess js/navigator)\n (let [p (.requestMIDIAccess js/navigator #js {:sysex false})]\n (set! (.-kairoticMidi js/window) p) p)))]\n (.catch (.then p (fn [m] (reset! ins (vec (js/Array.from (.values (.-inputs m)))))\n (doseq [i @ins] (.addEventListener i \"midimessage\" on))))\n (fn [_] nil)))\n (swap! mine-off conj (fn [] (doseq [i @ins] (.removeEventListener i \"midimessage\" on))))))\n (when (kinds \"pad\")\n (let [alive (atom true)]\n (letfn [(poll [& _]\n (when @alive\n (doseq [p (learn-pads)\n [k v] (map-indexed vector (:axes p))]\n (mine-moved! [\"pad\" (if (and (:std p) (< k 4)) (nth [\"lx\" \"ly\" \"rx\" \"ry\"] k) (str \"a\" k))] v))\n (doseq [p (learn-pads)\n [k on] (map-indexed vector (:buttons p))]\n (mine-moved! [\"pad\" (if (and (:std p) (< k 17)) (nth learn-pad-buttons k) (str \"b\" k))] (if on 1 0)))\n (js/requestAnimationFrame poll)))]\n (poll))\n (swap! mine-off conj (fn [] (reset! alive false)))))\n (when (kinds \"tilt\")\n (let [on (fn [e] (when (number? (.-gamma e))\n (mine-moved! [\"tilt\" \"x\"] (api/clamp (/ (+ (.-gamma e) 90) 180) 0 1))\n (mine-moved! [\"tilt\" \"y\"] (api/clamp (/ (+ (api/clamp (.-beta e) -90 90) 90) 180) 0 1))))]\n (.addEventListener js/window \"deviceorientation\" on)\n (swap! mine-off conj (fn [] (.removeEventListener js/window \"deviceorientation\" on)))))\n (when (kinds \"osc\")\n (let [socks (when-let [all (.-kairoticOsc js/window)] (vec (js/Object.values all)))\n on (fn [f] (let [v (aget (or (.-args f) #js []) 0)] (when (and (.-address f) (number? v)) (mine-apply! [\"osc\" (.-address f)] v))))]\n (doseq [s socks] (.push (.-listeners s) on))\n (swap! mine-off conj (fn [] (doseq [s socks] (set! (.-listeners s) (.filter (.-listeners s) (fn [x & _] (not= x on)))))))))))\n\n(defn mine-add! [m]\n (swap! mine (fn [ms] (conj (vec (remove #(and (= (:spec %) (:spec m)) (= (:box %) (:box m))) ms)) m)))\n (mine-save!) (mine-listen!))\n\n(defn my-controls\n \"Your own controller mappings for this work (Learn · only for me), kept in this browser: [[n spec box] …].\"\n [] (vec (map-indexed (fn [i {:keys [spec box]}] [i (str/join \" \" spec) box]) @mine)))\n\n(defn forget-control\n \"Forgets one of your own controller mappings, by its number in (my-controls); (forget-control :all) all of them.\"\n [n]\n (swap! mine (fn [ms] (if (= n :all) [] (vec (keep-indexed (fn [i m] (when (not= i n) m)) ms)))))\n (mine-save!) (mine-listen!)\n (my-controls))\n\n;; another work has its own mappings\n(add-watch work :mine (fn [_ _ o n] (when (not= [(:kind o) (:id o)] [(:kind n) (:id n)]) (mine-load!) (mine-listen!))))\n\n;; ── the banner: the box, the scope, your mappings ──\n\n(defn learn-banner-html [id b]\n (let [me? (= :me (:scope @learn-state))]\n (str \"<p><b>Learn</b> · move a controller for <code>\" (esc (name id)) \" \" (esc (:text b)) \"</code>: a MIDI controller or key, a gamepad's stick or button, the phone's tilt, an OSC address.</p>\"\n \"<div class=\\\"learn-scope\\\" role=\\\"radiogroup\\\" aria-label=\\\"For whom\\\">\"\n \"<label><input type=\\\"radio\\\" name=\\\"learn-scope\\\" value=\\\"work\\\"\" (when-not me? \" checked\") \"> <b>for the work</b> — boxes in the patch, the same for everyone</label>\"\n \"<label><input type=\\\"radio\\\" name=\\\"learn-scope\\\" value=\\\"me\\\"\" (when me? \" checked\") \"> <b>only for me</b> — in this browser, played as my gesture</label>\"\n \"</div>\"\n (when (seq @mine)\n (str \"<p class=\\\"learn-mine\\\">Yours here: \"\n (str/join \" · \" (map-indexed (fn [i {:keys [spec box]}] (str (esc (str/join \" \" spec)) \" → \" (esc (name box)) \" <button class=\\\"act small\\\" data-mine-forget=\\\"\" i \"\\\" title=\\\"Forget it\\\">✕</button>\")) @mine))\n \"</p>\"))\n \"<div class=\\\"ask-bar\\\"><span class=\\\"spacer\\\"></span><button class=\\\"act\\\" data-learn-cancel=\\\"1\\\">Cancel · Esc</button></div>\")))\n\n(defn learn\n \"Wires the next controller that moves to a box: (learn :b5) for the work (boxes in the patch), (learn :b5 :me)\n only for you (kept in this browser, played as your gesture). (learn false) stops waiting.\"\n ([] (learn false))\n ([id] (learn id @learn-scope))\n ([id scope]\n (learn-stop!)\n (if (and id (not= id false))\n (let [b (or (get-in (current) [:boxes id]) (fail (str \"There is no box \" id)))\n scope (if (= scope :me) :me :work)]\n (reset! learn-state {:target id :scope scope})\n (swap! learn-state assoc :off [(learn-listen-midi!) (learn-listen-pads!) (learn-listen-motion!) (learn-listen-osc!)])\n (when-let [t ($ \"learn-toggle\")] (.add (.-classList t) \"on\"))\n (learn-banner! (learn-banner-html id b))\n id)\n nil)))\n\n(when ($ \"learn-toggle\")\n (.addEventListener ($ \"learn-toggle\") \"click\"\n (fn [_] (if @learn-state\n (learn false)\n (let [[kind v] (:sel @ui)]\n (if (= kind :box)\n (learn v)\n (repl-print! \"err\" \"Learn: select the box a controller should move (a knob, a number, any box), then Learn.\"))))))\n (.addEventListener js/document \"click\"\n (fn [e] (let [t (.-target e)]\n (when (.getAttribute t \"data-learn-cancel\") (learn false))\n (when-let [n (.getAttribute t \"data-mine-forget\")]\n (forget-control (js/parseInt n))\n (when-let [{:keys [target]} @learn-state] (learn-banner! (learn-banner-html target (get-in (current) [:boxes target]))))))))\n (.addEventListener js/document \"change\"\n (fn [e] (let [t (.-target e)]\n (when (and (= \"learn-scope\" (.-name t)) @learn-state)\n (let [sc (if (= \"me\" (.-value t)) :me :work)]\n (swap! learn-state assoc :scope sc)\n (reset! learn-scope sc)\n (try (.setItem js/localStorage \"kairotic-learn-scope\" (name sc)) (catch :default _ nil)))))))\n (mine-load!) (mine-listen!)\n (.addEventListener js/document \"keydown\" (fn [e] (when (and @learn-state (= \"Escape\" (.-key e))) (learn false)))))\n","page/23-ids.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · page · box ids (issue #163)\n;; Boxes are named by their ids everywhere ((connect :b1 0 :b2 0), (send! :b7 …), @b3 in the Room tab), so:\n;; - each box shows its id over its top right corner when it is hovered or selected; I shows them all\n;; (02-patch-view.cljs draws it, the page's CSS shows it);\n;; - ( on the patch opens a line of the REPL there, in the field of a new box (05-gestures.cljs);\n;; - while a line of code waits for a box — the REPL, the Code tab, the field opened with (, the Room tab's\n;; message — a click on a box writes its id there (:b7, or @b7 in a message), as a click on a cell does in\n;; a spreadsheet's formula. It waits for one when what is before the cursor ends with a space, ( [ {, or the\n;; : or @ that begins an id; otherwise a click on a box does what it always does.\n\n(defn cm-of\n \"The CodeMirror view of a wrapper made by 14-editor.cljs, if its text is where the focus is (asked of the\n document's active element: the view's own hasFocus is false while the window itself is not in front).\"\n [ed] (when-let [v (some-> ed .-view)] (when (identical? (.-activeElement js/document) (.-contentDOM v)) v)))\n\n(declare mark-picking!)\n\n;; ───── the line of the REPL on the patch, as an editor (the same as the REPL's) ─────\n;; The field of a new box becomes a line of the REPL when what is written in it starts with ( (05-gestures.cljs);\n;; once the code editor is loaded, that line is one, as the REPL at the bottom is: completion of Kairotic's\n;; commands and clojure.core, brackets closed and matched, Enter runs it once its brackets are balanced\n;; (Shift+Enter: a new line), ↑ ↓ the REPL's history, Esc closes it. What it gave shows below it.\n\n(defonce line-ed (atom nil)) ; {:ed editor :el the line :words what it completes} while the line is open\n\n(defn close-repl-line!\n \"Closes the line of the REPL on the patch, without running anything.\"\n []\n (when-let [{:keys [ed el]} @line-ed]\n (reset! line-ed nil)\n (try (.destroy ed) (catch :default _ nil))\n (.remove el)\n (mark-picking!)))\n\n(defn repl-line-text \"What is written in the line of the REPL on the patch (nil if it is not open).\" []\n (some-> @line-ed :ed .getValue))\n\n(defn open-repl-cm!\n \"Opens the line of the REPL on the patch as a code editor (cm, the editor's module), at x y, with text.\"\n [cm x y text]\n (close-repl-line!)\n (let [el (js/document.createElement \"div\") host (js/document.createElement \"div\")\n out (js/document.createElement \"div\")\n ed (atom nil) hidx (atom nil)\n free? (fn [] (not (.completing @ed)))\n start (if (= \"(\" (str/trim (str text))) \"()\" (str text))\n words (vec (concat (command-words) (ns-names 'clojure.core \"\")))\n [px py] (wrap-px x (- y 4))\n run (fn []\n (let [code (str/trim (.getValue @ed))]\n (if (str/blank? code)\n (close-repl-line!)\n (do (reset! hidx nil)\n (repl-line-run! code out)\n (.setValue @ed \"\")\n (.focus @ed)))\n true))\n recall (fn [up?]\n (let [h (:hist @ui) n (count h)]\n (when (pos? n)\n (let [i (if up? (max 0 (dec (or @hidx n))) (min n (inc (or @hidx n))))]\n (reset! hidx i)\n (.setValue @ed (if (< i n) (nth h i) \"\"))\n (.cursorToEnd @ed)\n true))))]\n (set! (.-id el) \"repl-line\")\n (set! (.-className el) \"edit as-repl repl-line\")\n (set! (.-className host) \"repl-line-host\")\n (set! (.-id out) \"box-edit-out\")\n (set! (.-className out) \"edit-out\")\n (set! (.. el -style -left) (str px \"px\"))\n (set! (.. el -style -top) (str py \"px\"))\n (.appendChild el host)\n (.appendChild el out)\n ;; keys typed in it are its own: a space is not ▶, Delete does not delete a box\n (.addEventListener el \"keydown\" (fn [e] (.stopPropagation e)))\n (.appendChild ($ \"canvas-wrap\") el)\n (reset! ed ((.-createEditor cm)\n #js {:parent host :doc start :language \"clojurescript\" :gutter false\n :placeholder \"(command) · Enter runs it · Esc closes\"\n :words (clj->js words)\n :onCancel (fn [] (close-repl-line!))\n :keys #js [#js {:key \"Enter\" :run (fn [] (when (and (free?) (balanced? (.getValue @ed))) (run)))}\n #js {:key \"Shift-Enter\" :run (fn [] (.newline @ed) true)}\n #js {:key \"ArrowUp\" :run (fn [] (boolean (and (free?) (= 1 (.cursorLine @ed)) (recall true))))}\n #js {:key \"ArrowDown\" :run (fn [] (boolean (and (free?) (= (.cursorLine @ed) (.lineCount @ed)) (recall false))))}]}))\n (.setAttribute (.-contentDOM (.-view @ed)) \"aria-label\" \"A line of the REPL\")\n (reset! line-ed {:ed @ed :el el :words words})\n ;; the cursor inside the brackets of a new line, or at the end of what was written\n (let [v (.-view @ed)]\n (.dispatch v #js {:selection #js {:anchor (if (= start \"()\") 1 (count start))}}))\n (.focus @ed)\n ;; leaving it closes it (a click on a box that writes its id keeps the focus here)\n (.addEventListener el \"focusout\"\n (fn [_] (js/setTimeout (fn [] (when (and (= el (:el @line-ed)) (not (.contains el (.-activeElement js/document))))\n (close-repl-line!)))\n 0)))\n @ed))\n\n(defn upgrade-repl-line!\n \"The field of a new box that became a line of the REPL (input inp, at x y), as a code editor once it is loaded;\n until then, or without it, the field itself is the line. close-field! removes the field without running it.\"\n [inp x y close-field!]\n (.then (load-cm)\n (fn [cm]\n (when (and cm (.-createEditor cm) (.-isConnected inp))\n (let [text (.-value inp)]\n (close-field!)\n (open-repl-cm! cm x y text))))))\n\n(defn id-target\n \"Where an id would be written now: {:cm view :mark \\\":\\\"}, {:el input :mark \\\":\\\" or \\\"@\\\"}, or nil.\"\n []\n (let [a (.-activeElement js/document) id (some-> a .-id)]\n (cond\n (cm-of (:ed @line-ed)) {:cm (cm-of (:ed @line-ed)) :mark \":\"}\n (cm-of @repl-ed) {:cm (cm-of @repl-ed) :mark \":\"}\n (cm-of @code-ed) {:cm (cm-of @code-ed) :mark \":\"}\n (#{\"repl-in\" \"code\"} id) {:el a :mark \":\"}\n (and (= id \"box-edit\") (.contains (.-classList a) \"as-repl\")) {:el a :mark \":\"}\n (= id \"talk-say\") {:el a :mark \"@\"}\n :else nil)))\n\n(defn before-cursor\n \"The text before the cursor of a target.\"\n [{:keys [cm el]}]\n (cond cm (let [h (.. cm -state -selection -main -from)] (.sliceDoc (.-state cm) 0 h))\n el (subs (str (.-value el)) 0 (or (.-selectionStart el) (count (.-value el))))\n :else \"\"))\n\n(defn waits-for-id?\n \"Does the text before the cursor wait for a box: not empty, and ending with a space, ( [ {, or the mark.\"\n [t before]\n (and (seq (str/trim before))\n (boolean (re-find (re-pattern (str \"[\\\\s(\\\\[{\" (if (= \"@\" (:mark t)) \"@\" \":\") \"]$\")) before))))\n\n(defn picking-target\n \"The target, when a click on a box would write its id there; nil otherwise.\"\n []\n (when-not (locked?)\n (when-let [t (id-target)]\n (when (waits-for-id? t (before-cursor t)) t))))\n\n(defn write-id!\n \"Writes the id of box id at the cursor of target t (after its mark, if it is already there), then a space.\"\n [t id]\n (let [before (before-cursor t)\n mark (:mark t)\n text (str (if (str/ends-with? before mark) \"\" mark) (name id) \" \")]\n (if-let [cm (:cm t)]\n ;; as typed (input.type): the Clojure editor keeps the space after it, before a closing bracket too\n (let [sel (.. cm -state -selection -main) from (.-from sel)]\n (.dispatch cm #js {:changes #js {:from from :to (.-to sel) :insert text}\n :selection #js {:anchor (+ from (count text))}\n :userEvent \"input.type\"}))\n (let [el (:el t) s (.-selectionStart el) e (.-selectionEnd el)]\n (.setRangeText el text s e \"end\")\n (.dispatchEvent el (js/Event. \"input\" #js {:bubbles true}))))))\n\n(defn mark-picking!\n \"The patch shows (a copy pointer, a box marked under it) whether a click on a box would write its id.\"\n []\n (.toggle (.-classList svg) \"picking\" (some? (picking-target))))\n\n(doseq [ev [\"selectionchange\" \"focusin\" \"focusout\" \"keyup\" \"input\"]]\n (.addEventListener js/document ev (fn [_] (mark-picking!)) true))\n\n;; the click: before the patch's own handler (capture), and without taking the focus from the line\n(defonce id-click (atom false))\n\n(.addEventListener svg \"pointerdown\"\n (fn [e]\n (reset! id-click false)\n (when-let [t (picking-target)]\n (when-let [el (when-not (closest e \".port\") (closest e \".box\"))]\n (let [id (keyword (.. el -dataset -box))]\n (when (get-in (current) [:boxes id])\n (reset! id-click true)\n (.preventDefault e)\n (.stopImmediatePropagation e)\n (write-id! t id)\n ;; the box named lights up a moment\n (.add (.-classList el) \"picked\")\n (js/setTimeout (fn [] (some-> (.querySelector ($ \"scene\") (str \"g.box[data-box=\\\"\" (name id) \"\\\"]\"))\n .-classList (.remove \"picked\")))\n 400)\n (mark-picking!))))))\n true)\n\n;; the press that wrote an id keeps the focus where it was\n(.addEventListener svg \"mousedown\" (fn [e] (when @id-click (.preventDefault e))) true)\n(.addEventListener svg \"click\" (fn [e] (when @id-click (.stopImmediatePropagation e) (reset! id-click false))) true)\n\n;; ───── keys on the patch: ( opens a line of the REPL, I shows every id ─────\n\n(defonce last-patch-pt (atom nil)) ; where the pointer last was over the patch, in patch coordinates\n(.addEventListener svg \"pointermove\" (fn [e] (reset! last-patch-pt (pt e))))\n(.addEventListener svg \"pointerleave\" (fn [_] (reset! last-patch-pt nil)))\n\n(defn patch-middle\n \"The middle of the part of the patch on screen, in patch coordinates.\"\n []\n (let [w ($ \"canvas-wrap\")]\n [(+ (.-scrollLeft w) (* 0.3 (.-clientWidth w))) (+ (.-scrollTop w) (* 0.4 (.-clientHeight w)))]))\n\n(defn open-repl-line!\n \"Opens a line of the REPL on the patch, where the pointer is (or in the middle of what is on screen).\"\n []\n (let [[x y] (or @last-patch-pt (patch-middle))]\n (open-editor! {:x x :y y :text \"(\"})))\n\n(defn show-ids!\n \"Shows the id of every box (true), only of the one hovered or selected (false), or switches.\"\n ([] (show-ids! (not (.contains (.-classList svg) \"show-ids\"))))\n ([on]\n (.toggle (.-classList svg) \"show-ids\" (boolean on))\n (try (.setItem js/localStorage \"kairotic.show-ids\" (if on \"1\" \"0\")) (catch :default _ nil))\n (boolean on)))\n\n(try (when (= \"1\" (.getItem js/localStorage \"kairotic.show-ids\")) (show-ids! true)) (catch :default _ nil))\n\n(.addEventListener js/document \"keydown\"\n (fn [e]\n (let [a (.-activeElement js/document)\n typing? (or (#{\"INPUT\" \"TEXTAREA\" \"SELECT\"} (some-> a .-tagName)) (some-> a .-isContentEditable))\n k (.-key e)]\n (when (and (not typing?) (not (.-ctrlKey e)) (not (.-metaKey e)) (not (.-altKey e))\n (.-hidden ($ \"manager\")) (not (locked?)) (not embed-mode))\n (cond\n (= k \"(\") (do (.preventDefault e) (open-repl-line!))\n (and (#{\"i\" \"I\"} k) (not (:tsel @ui)) (not (:nsel @ui))) (do (.preventDefault e) (show-ids!))\n :else nil)))))\n","page/24-clipboard.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · page · copy, cut, paste and duplicate boxes (issue #164)\n;; ⌘/Ctrl+C copies the selected boxes, ⌘/Ctrl+X cuts them, ⌘/Ctrl+V pastes them where the pointer is (keeping\n;; their layout), ⌘/Ctrl+D duplicates them a little below and to the right; (duplicate :b3 :b4) from code.\n;;\n;; What goes on the clipboard is the code of those boxes, as the Code tab writes it — (box …), (connect …), their\n;; data — so it can be read, pasted in a message, an issue or a document. Its last line holds the same boxes as\n;; data (;; kairotic-paste {…}): pasting reads that line as EDN, which evaluates nothing, so text copied from\n;; anywhere cannot run code here. What it holds goes through the same checks as anything that comes from a room.\n;;\n;; Pasted boxes get new ids, the next free numbers, and keep their lines among themselves; a line to a box that\n;; was not copied is kept when that box is in the patch where they are pasted (the same patch, usually). A paste\n;; is one event of the history.\n\n(def clip-mark \";; kairotic-paste \")\n\n(defn clip-of\n \"The boxes ids of patch p as a clipboard holds them: {:boxes {id box} :lines [lines that touch them]}.\"\n [p ids]\n (let [ids (set ids)]\n {:boxes (into (sorted-map) (select-keys (:boxes p) ids))\n :lines (vec (filter (fn [[a _ b _]] (or (ids a) (ids b))) (:lines p)))}))\n\n(defn clip-text\n \"The text a copy of boxes ids of patch p puts on the clipboard: their code, then the same as data.\"\n [p ids]\n (let [c (clip-of p ids) n (count (:boxes c))]\n (str \";; Kairotic · \" n (if (= 1 n) \" box\" \" boxes\") \" (\" (str/join \" \" (keys (:boxes c)))\n \") · paste on a patch with ⌘/Ctrl+V\\n\"\n (patch->code c) \"\\n\"\n clip-mark (pr-str c))))\n\n(defn read-clip\n \"The boxes and lines a clipboard text holds (made safe, as what comes from a room is), or nil if it holds none.\"\n [text]\n (when-let [line (some (fn [l] (when (str/starts-with? l clip-mark) l)) (str/split-lines (str text)))]\n (let [x (try (clojure.edn/read-string (subs line (count clip-mark))) (catch :default _ nil))]\n (when (and (map? x) (map? (:boxes x)))\n (let [p (sane-patch {:boxes (:boxes x) :lines (if (sequential? (:lines x)) (vec (:lines x)) [])})]\n (when (seq (:boxes p)) (select-keys p [:boxes :lines])))))))\n\n(defn clip-corner\n \"The top left corner of the boxes of a clipboard.\"\n [c]\n [(reduce min (map :x (vals (:boxes c)))) (reduce min (map :y (vals (:boxes c))))])\n\n(defn paste-patch!\n \"Adds the boxes and lines of clipboard c to the patch on screen, moved by dx dy, as one event of the history.\n They get the next free ids; a line to a box that was not copied is kept when that box is here. Selects them\n and returns their ids.\"\n [c [dx dy]]\n (let [p (current)\n start (inc (reduce max 0 (map id-z (keys (:boxes p)))))\n order (sort-by id-z (keys (:boxes c)))\n m (zipmap order (map (fn [i] (keyword (str \"b\" (+ start i)))) (range)))\n nb (into {} (for [[id b] (:boxes c)]\n [(m id) (-> b (update :x (fn [x] (max 0 (js/Math.round (+ x dx)))))\n (update :y (fn [y] (max 0 (js/Math.round (+ y dy)))))\n ;; placed in the patch, not in the presentation\n (dissoc :present))]))\n end-of (fn [x] (or (m x) (when (contains? (:boxes p) x) x)))\n nl (vec (distinct (for [[a o b i] (:lines c)\n :let [a2 (end-of a) b2 (end-of b) l [a2 o b2 i]]\n :when (and a2 b2 (not (some #{l} (:lines p))))]\n l)))\n q (-> p (update :boxes into nb) (update :lines into nl))\n ids (vec (sort-by id-z (vals m)))]\n (doseq [id ids] (forget-box! id))\n (dispatch-all! (rel/patch-diff p q))\n (doseq [[_ b] nb] (ensure-class! (:text b)))\n (swap! ui assoc :sel (sel-of ids) :insp nil :nsel nil :tsel nil)\n ids))\n\n(defn duplicate\n \"Duplicates boxes a little below and to the right, with their lines among themselves (and their lines to the\n others): (duplicate :b3 :b4). One event of the history; returns the new ids.\"\n [& ids]\n (when (empty? ids) (fail \"Which boxes? (duplicate :b3 :b4)\"))\n (doseq [id ids] (need-box id))\n (paste-patch! (clip-of (current) ids) [20 20]))\n\n;; ───── the keys: the clipboard's own events, and ⌘/Ctrl+D ─────\n\n(defn typing-somewhere?\n \"Is something being written or selected on the page: a field, an editor, text selected, a field of an html box?\"\n []\n (let [a (.-activeElement js/document)]\n (or (#{\"INPUT\" \"TEXTAREA\" \"SELECT\"} (some-> a .-tagName))\n (some-> a .-isContentEditable)\n (some? (some-> a .-shadowRoot .-activeElement))\n (not (str/blank? (str (.getSelection js/window)))))))\n\n(defn clip-ready?\n \"Do the clipboard's keys act on boxes now?\"\n []\n (and (not (typing-somewhere?)) (not (locked?)) (not embed-mode) (.-hidden ($ \"manager\"))))\n\n(defn copied! [ids verb]\n (repl-print! \"out\" (esc (str \";; \" verb \" \" (count ids) (if (= 1 (count ids)) \" box: \" \" boxes: \") (str/join \" \" ids)))))\n\n(.addEventListener js/document \"copy\"\n (fn [e]\n (let [ids (vec (sort-by id-z (sel-ids)))]\n (when (and (seq ids) (clip-ready?))\n (.preventDefault e)\n (.setData (.-clipboardData e) \"text/plain\" (clip-text (current) ids))\n (copied! ids \"copied\")))))\n\n(.addEventListener js/document \"cut\"\n (fn [e]\n (let [ids (vec (sort-by id-z (sel-ids)))]\n (when (and (seq ids) (clip-ready?))\n (.preventDefault e)\n (.setData (.-clipboardData e) \"text/plain\" (clip-text (current) ids))\n (swap! ui assoc :sel nil :insp nil)\n (gesture! (str \"(delete \" (str/join \" \" ids) \")\"))))))\n\n(.addEventListener js/document \"paste\"\n (fn [e]\n (when (clip-ready?)\n (when-let [c (read-clip (.getData (.-clipboardData e) \"text/plain\"))]\n (.preventDefault e)\n (let [[x0 y0] (clip-corner c)\n ;; where the pointer is over the patch, or a little below and to the right of where they were\n [tx ty] (or @last-patch-pt [(+ x0 20) (+ y0 20)])\n ids (paste-patch! c [(- tx x0) (- ty y0)])]\n (copied! ids \"pasted\"))))))\n\n(.addEventListener js/document \"keydown\"\n (fn [e]\n (when (and (or (.-ctrlKey e) (.-metaKey e)) (not (.-shiftKey e)) (not (.-altKey e))\n (= \"d\" (str/lower-case (.-key e))) (clip-ready?))\n (let [ids (vec (sort-by id-z (sel-ids)))]\n (when (seq ids)\n (.preventDefault e)\n (gesture! (str \"(duplicate \" (str/join \" \" ids) \")\")))))))\n","page/25-tidy.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · page · boxes that cover each other (issue #166, 2)\n;; Where a box is drawn is written in the work, but how big it is is only known once it is drawn: a faust~ grows\n;; with the sliders its code compiles to, a score with the notation Verovio draws. So boxes placed by hand (in a\n;; help patch, say) can end up under one another.\n;; (overlaps) the pairs of boxes on screen that cover each other, as they are drawn now\n;; (tidy) moves boxes down until none covers another, as one event; they keep their order and columns\n;; (layout-settled?) every box has its size: code boxes compiled, scores drawn (or failed)\n;; The help patches are checked in CI (tests/helplayout.mjs): none of their steps has boxes over one another.\n\n(defn box-rects\n \"The boxes on screen as {id [x y w h]}, at the size they are drawn.\"\n []\n (into {} (for [[id b] (:boxes (scene-of (current)))\n :let [[x y] (box-pos id b) [w h] (box-dims id b)]]\n [id [x y w h]])))\n\n(def overlap-margin\n \"How much two boxes may share before they cover each other (a line, a port, a pixel of rounding).\"\n 3)\n\n(defn covers?\n \"Do the rectangles [x y w h] a and b share more than a sliver?\"\n [[ax ay aw ah] [bx by bw bh]]\n (and (> (- (min (+ ax aw) (+ bx bw)) (max ax bx)) overlap-margin)\n (> (- (min (+ ay ah) (+ by bh)) (max ay by)) overlap-margin)))\n\n(defn overlaps\n \"The pairs of boxes on screen that cover each other: [[:b2 :b5] …], each pair in the order of its ids.\"\n ([] (overlaps (box-rects)))\n ([rects]\n (let [ids (vec (sort-by id-z (keys rects)))]\n (vec (for [i (range (count ids)) j (range (inc i) (count ids))\n :let [a (nth ids i) b (nth ids j)]\n :when (covers? (get rects a) (get rects b))]\n [a b])))))\n\n(defn layout-settled?\n \"Has every box on screen its size: its code compiled (or failed), its score drawn (or failed)?\"\n []\n (let [p (scene-of (current))]\n (every? (fn [[id b]]\n (case (display-of b)\n :code (let [d (box-def b) src (str (get-in b [:data :source]))]\n (or (str/blank? src) (not= :compiling (:status (cbox/compiled (:language d) src)))))\n :score (or (= :error @vrv-status) (some? (get @score-cache id)))\n true))\n (:boxes p))))\n\n(defn tidy-moves\n \"Where boxes go so that none covers another: from the top, each box that covers one placed before it goes\n down below it (and below anything it then meets), in its own column. {id [x y]} of the boxes that move.\"\n [rects]\n (let [gap 14\n order (sort-by (fn [id] (let [[x y] (get rects id)] [y x (id-z id)])) (keys rects))]\n (loop [[id & more] order placed {} moves {}]\n (if (nil? id)\n moves\n (let [[x y w h] (get rects id)\n y2 (loop [y y n 0]\n (let [hit (filter (fn [[_ r]] (covers? [x y w h] r)) placed)]\n (if (and (seq hit) (< n 200))\n (recur (+ gap (reduce max (map (fn [[_ [_ ry _ rh]]] (+ ry rh)) hit))) (inc n))\n y)))]\n (recur more (assoc placed id [x y2 w h]) (if (not= y2 y) (assoc moves id [x (js/Math.round y2)]) moves)))))))\n\n(defn tidy\n \"Moves boxes down until none covers another, as they are drawn now (a faust~ with its sliders, a score with its\n notation): (tidy). One event of the history; returns the boxes moved.\"\n []\n (when @pres-mode (fail \"In presentation the boxes are where the performer sees them: (tidy) works on the patch\"))\n (let [moves (tidy-moves (box-rects))]\n (dispatch-all! (for [[id [x y]] (sort-by key moves)] [:move id x y]))\n (vec (sort-by id-z (keys moves)))))\n","page/26-probes.cljs":";; SPDX-License-Identifier: MPL-2.0\n;; Kairotic · page · probes on wires (discussion #183)\n;; To see what travels along a wire, without wiring a print in: ⌥/Alt+click a wire puts a probe on it (again,\n;; takes it away), or (probe :b1 0 :b2 0). A probed wire is drawn dashed, and a label at its middle shows the last\n;; value that went along it, flashing when one passes, with how many a second when they come often (12/s).\n;; Probes are this tab's, as the selection is: they are not part of the work, its history or its code, and two\n;; people in a room watch their own. What is watched is the outlet a wire leaves from (every wire from it carries\n;; the same), so the engine keeps only what leaves the outlets watched (kairotic.engine/probe!).\n;; A wire out of a sub-patch box shows nothing yet (its messages leave from a box inside it); signal wires carry\n;; no messages.\n\n(defonce wire-probes (atom {})) ; [view-path [a o b i]] → [flat-id o], the wires probed here\n\n(defn probe-key [[a o _ _]] [(fid a) o])\n\n(defn probed? \"Is this wire of the patch on screen probed?\" [l]\n (contains? @wire-probes [(engine-path) l]))\n\n(defn sync-probes!\n \"The engine watches the outlets of the probed wires (and forgets what it saw of the others).\"\n []\n (let [ks (set (vals @wire-probes))]\n (reset! eng/probes ks)\n (swap! eng/probe-seen select-keys ks)))\n\n(defn probe\n \"Puts a probe on a wire, or takes it away: (probe :b1 0 :b2 0). The wire shows the last value that went along it,\n and how many a second. Only for this tab: nothing goes into the work. Returns :on or :off.\"\n [a o b i]\n (let [l [a o b i]]\n (when-not (some #{l} (:lines (current))) (fail (str \"There is no line \" (pr-str l) \" in the patch on screen\")))\n (let [k [(engine-path) l]\n on (not (contains? @wire-probes k))]\n (swap! wire-probes (fn [m] (if on (assoc m k (probe-key l)) (dissoc m k))))\n (sync-probes!)\n (render-scene (current))\n (if on :on :off))))\n\n(defn unprobe-all!\n \"Takes away every probe.\"\n []\n (reset! wire-probes {})\n (sync-probes!)\n (render-scene (current))\n :ok)\n\n(defn probe-summary\n \"A value as a probe shows it: short.\"\n [v]\n (let [cut (fn [s n] (if (> (count s) n) (str (subs s 0 (dec n)) \"…\") s))]\n (cond\n (nil? v) \"nil\"\n (number? v) (cv/fmt v)\n (keyword? v) (str v)\n (string? v) (pr-str (cut v 22))\n (mt/node? v) (str \"tree · \" (count (try (mt/pitches v) (catch :default _ []))) \" notes\")\n :else (cut (pr-str v) 30))))\n\n(defn probe-rate\n \"How many messages a second went out of a probed outlet, over the last second.\"\n [seen]\n (let [now (.now js/performance)]\n (count (filter (fn [t] (< (- now t) 1000)) (:times seen)))))\n\n(defn probes-svg\n \"The labels of the probes of the patch on screen p, at the middle of their wires.\"\n [p]\n (let [path (engine-path) lines (set (:lines p))\n mine (filter (fn [[[vp l] _]] (= vp path)) @wire-probes)]\n ;; the wires that are gone (deleted, or back in the history) lose their probe\n (let [gone (keep (fn [[[_ l :as k] _]] (when-not (contains? lines l) k)) mine)]\n (when (seq gone) (js/setTimeout (fn [] (swap! wire-probes (fn [m] (apply dissoc m gone))) (sync-probes!)) 0)))\n (apply str\n (for [[[_ [a o b i :as l]] k] mine :when (contains? lines l)\n :when (and (get-in p [:boxes a]) (get-in p [:boxes b]))]\n (let [[x1 y1] (out-xy p a o) [x2 y2] (in-xy p b i)\n mx (/ (+ x1 x2) 2) my (/ (+ y1 y2) 2)\n seen (get @eng/probe-seen k)\n rate (when seen (probe-rate seen))\n label (cond (nil? seen) \"—\"\n (and rate (> rate 1)) (str (probe-summary (:v seen)) \" · \" rate \"/s\")\n :else (probe-summary (:v seen)))\n hot (and seen (< (- (.now js/performance) (last (:times seen))) 180))\n w (+ 12 (* 6.4 (count label)))]\n (str \"<g class=\\\"probe\" (when hot \" hot\") \"\\\" transform=\\\"translate(\" (js/Math.round mx) \",\" (js/Math.round my) \")\\\">\"\n \"<rect x=\\\"\" (js/Math.round (- (/ w 2))) \"\\\" y=\\\"-9\\\" width=\\\"\" (js/Math.round w) \"\\\" height=\\\"18\\\" rx=\\\"4\\\"></rect>\"\n \"<text x=\\\"0\\\" y=\\\"4\\\" text-anchor=\\\"middle\\\">\" (esc label) \"</text></g>\"))))))\n\n;; a value seen by a probe is drawn on the next frame (also with the engine stopped)\n(defonce probe-frame (atom false))\n(defonce probe-watch\n (add-watch eng/probe-seen ::draw\n (fn [_ _ _ _]\n (when-not @probe-frame\n (reset! probe-frame true)\n (js/requestAnimationFrame (fn [_] (reset! probe-frame false) (render-overlay!)))))))\n\n;; ⌥/Alt+click on a wire: a probe on it, or away\n(.addEventListener svg \"pointerdown\"\n (fn [e]\n (when (and (.-altKey e) (not (locked?)) (not (:annot @ui)))\n (when-let [el (closest e \".wire-hit\")]\n (let [idx (js/parseInt (.. el -dataset -line) 10)\n l (nth (:lines (scene-of (current))) idx nil)]\n (when l\n (.preventDefault e)\n (.stopImmediatePropagation e)\n (gesture! (str \"(probe \" (str/join \" \" l) \")\")))))))\n true)\n\n(reset! probe-hooks {:probed? probed? :labels probes-svg})\n"}};
|