@kairotic/app 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,1051 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · the page, part 3 of 12: patch-view
3
+ ;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).
4
+
5
+ (in-ns 'user)
6
+
7
+ ;; ───────────────────────── interface: patch ─────────────────────────
8
+
9
+ (defn $ [id] (js/document.getElementById id))
10
+
11
+ ;; ───── embedding (Study 22): the address says what to show and how ─────
12
+ ;; ?code=… a patch (its code, compressed) · ?tutorial=id&step=n · ?help=class · ?lang=es|en
13
+ ;; ?embed only the patch, to put inside another page (an iframe, a Notion /embed block)
14
+ ;; ?present only the presentation, filling the window (with a fullscreen button)
15
+
16
+ ;; the same after # (issue #55): #code=…&present. What is after # never reaches the server, so a long patch
17
+ ;; is not refused there (a request line too long is answered 414); after #, a parameter wins over ?.
18
+
19
+ (defn hash-part [] (subs (str (.-hash js/location)) 1))
20
+
21
+ (def url-params
22
+ (let [q (js/URLSearchParams. (.-search js/location))]
23
+ (.forEach (js/URLSearchParams. (hash-part)) (fn [v k] (.set q k v)))
24
+ q))
25
+ (defn url-param [k] (.get url-params k))
26
+ (defn raw-param
27
+ "A parameter as written in the address, where + stays + (code written by hand: ?src=… or #src=…)."
28
+ [k]
29
+ (some (fn [part]
30
+ (let [i (.indexOf part "=")]
31
+ (when (and (pos? i) (= k (subs part 0 i)))
32
+ (try (js/decodeURIComponent (subs part (inc i))) (catch :default _ nil)))))
33
+ (concat (str/split (hash-part) #"&")
34
+ (str/split (subs (str (.-search js/location)) 1) #"&"))))
35
+
36
+ (def link-keys
37
+ "The parameters that say what a link opens: a new one after # (pasted in the same tab) opens it."
38
+ #{"code" "src" "ask" "tutorial" "help" "embed" "present"})
39
+
40
+ (.addEventListener js/window "hashchange"
41
+ (fn [_]
42
+ (let [ks (set (map (fn [part] (first (str/split part #"=" 2))) (str/split (hash-part) #"&")))]
43
+ (when (some link-keys ks) (.reload js/location)))))
44
+ (def embed-mode (cond (.has url-params "present") :present (.has url-params "embed") :embed))
45
+
46
+ (defn wrap-px
47
+ "Where a point of the patch is inside the patch pane, in pixels (an embedded patch is shown scaled)."
48
+ [x y]
49
+ (let [cv ($ "canvas")]
50
+ (if-not (.hasAttribute cv "viewBox")
51
+ [x y]
52
+ (let [q (.createSVGPoint cv) wrap ($ "canvas-wrap") r (.getBoundingClientRect wrap)]
53
+ (set! (.-x q) x)
54
+ (set! (.-y q) y)
55
+ (let [s (.matrixTransform q (.getScreenCTM cv))]
56
+ [(+ (- (.-x s) (.-left r)) (.-scrollLeft wrap)) (+ (- (.-y s) (.-top r)) (.-scrollTop wrap))])))))
57
+
58
+ (def box-h 24)
59
+ (def pw 10)
60
+ (defn box-w [text] (max 56 (+ 20 (* 7.6 (count text)))))
61
+ (defn port-x [w n i] (if (<= n 1) 0 (* i (/ (- w pw) (dec n)))))
62
+
63
+ ;; ───── buffer boxes (canvas, score) and action boxes (number, msg, bang) ─────
64
+
65
+ (def hdr 20)
66
+ (def grip 8)
67
+ (defonce score-cache (atom {})) ; box → {:key data :node <g> :h height :pieces [...] :anchors [...]}
68
+ (defonce vrv (atom nil))
69
+ (defonce vrv-status (atom :loading))
70
+
71
+ (def code-w 260)
72
+ (def code-lh 13)
73
+ (def code-row 22) ; a code box shows its code as one row (issue #8): the editor opens with a double-click
74
+ (def param-h 18)
75
+
76
+ (defn code-lines [b] (str/split-lines (let [f (str (get-in b [:data :source]))] (if (str/blank? f) " " f))))
77
+
78
+ (defn code-params [b]
79
+ (when-let [f (:params (box-def b))] (f (comp/box-info b))))
80
+
81
+ (defn code-geom
82
+ "Parts of a code box: its code row, the status of its compilation, its parameters. The code itself is
83
+ written in the editor (a double-click on the row), not in the patch (issue #8)."
84
+ [b]
85
+ (let [ch code-row
86
+ y-st (+ hdr ch 13)
87
+ y-par (+ hdr ch 20)
88
+ ps (code-params b)]
89
+ {:ch ch :y-st y-st :y-par y-par :params ps :h (+ y-par (* (count ps) param-h) 4)}))
90
+
91
+ (defn code-gist
92
+ "What the code row of a box shows: its first line that says something (not a comment), and how long it is."
93
+ [b]
94
+ (let [ls (code-lines b)
95
+ first-line (or (first (remove (fn [l] (or (str/blank? l) (re-find #"^\s*(;|//)" l))) ls)) "")
96
+ n (count (remove str/blank? ls))]
97
+ [(str/trim first-line) n]))
98
+
99
+ (declare panel-layout)
100
+
101
+ (def html-size "The size an html box is drawn at until it is given one (issue #146)." [260 150])
102
+
103
+ (defn box-size
104
+ "The size a canvas, freqt, score or html box is drawn at: the one being dragged at its corner, its own
105
+ (:size, issue #40), or the default. For a score only the width counts: its height follows the notation."
106
+ [id b]
107
+ (let [r (:resize @ui)]
108
+ (if (and r (= (:id r) id)) [(:w r) (:h r)] (or (:size b) (if (= :html (display-of b)) html-size [cv/W cv/H])))))
109
+
110
+ (defn box-dims [id b]
111
+ (let [t (:text b)]
112
+ (cond
113
+ (= :code (display-of b)) [code-w (:h (code-geom b))]
114
+ (panel-layout b) (let [{:keys [w h]} (panel-layout b)] [w h])
115
+ (own-view? b) (let [[w h] (comp/size-of b)] [(+ grip w) h])
116
+ (#{:canvas :html} (display-of b)) (box-size id b)
117
+ (= :score (display-of b)) [(first (box-size id b)) (max 90 (+ hdr 8 (or (get-in @score-cache [id :h]) 70)))]
118
+ :else
119
+ (case (klass t)
120
+ "bang" [34 26]
121
+ "number" [76 box-h]
122
+ "msg" [(max 44 (+ grip 14 (* 7.6 (count (str/trim (subs (str/trim t) 3)))))) box-h]
123
+ "patch" (if (line-ref? b) [(+ (box-w t) 30) box-h] [(box-w t) box-h])
124
+ [(box-w t) box-h]))))
125
+
126
+ (defn box-pos [id b]
127
+ (let [d (:drag @ui)]
128
+ (cond
129
+ ;; several boxes moving together: each from where it started, by the same offset
130
+ (and d (:moved d) (:ids d) (contains? (:ids d) id))
131
+ (let [[x0 y0] (get (:ids d) id)] [(+ x0 (:gx d)) (+ y0 (:gy d))])
132
+ (and d (= (:id d) id) (:moved d)) [(:x d) (:y d)]
133
+ :else [(:x b) (:y b)])))
134
+
135
+ (defn out-xy [p id o]
136
+ (let [b (get-in p [:boxes id]) [x y] (box-pos id b) [w h] (box-dims id b) [_ n] (io b)]
137
+ [(+ x (port-x w n o) (/ pw 2)) (+ y h)]))
138
+
139
+ (defn in-xy [p id i]
140
+ (let [b (get-in p [:boxes id]) [x y] (box-pos id b) [w _] (box-dims id b) [n _] (io b)]
141
+ [(+ x (port-x w n i) (/ pw 2)) y]))
142
+
143
+ ;; ───── patching: the same feel in every patcher of Kairotic (the patch, and the patch of a faust~) ─────
144
+ ;; Wires are curves that leave an outlet downwards and reach an inlet from above; one that goes back up
145
+ ;; loops out below and above the boxes. An outlet within `reach` of the pointer can be grabbed (it lights
146
+ ;; up, and the pointer is a cross), and a wire is dropped on the nearest inlet of the box under the
147
+ ;; pointer, or of an inlet within reach above it. packages/faust-units/assets/view.mjs does the same.
148
+
149
+ (def reach 10)
150
+
151
+ (defn wire-d
152
+ "The curve of a wire from an outlet at (x1 y1) to an inlet at (x2 y2), as an SVG path."
153
+ [x1 y1 x2 y2]
154
+ (let [dy (- y2 y1)
155
+ k (if (>= dy 24) (max 16 (* 0.45 dy)) (+ 36 (min 70 (* 0.25 (js/Math.abs (- x2 x1))))))
156
+ r (fn [v] (/ (js/Math.round (* 10 v)) 10))]
157
+ (str "M" (r x1) "," (r y1) " C" (r x1) "," (r (+ y1 k)) " " (r x2) "," (r (- y2 k)) " " (r x2) "," (r y2))))
158
+
159
+ (defn port-near
160
+ "The outlet (:out) or inlet (:in) of a box in patch p nearest to (x y), within reach: [id k], or nil.
161
+ An outlet is reached from its edge of the box a little inside and a little more outside; an inlet
162
+ the same way from above."
163
+ [p kind x y]
164
+ (let [best (atom nil)]
165
+ (doseq [[id b] (:boxes p)]
166
+ (let [[bx by] (box-pos id b) [w h] (box-dims id b) [ins outs] (io b)
167
+ n (if (= kind :out) outs ins)
168
+ py (if (= kind :out) (+ by h) by)
169
+ dy (if (= kind :out) (- y py) (- py y))] ; positive: outside the box
170
+ (when (and (pos? n) (<= -4 dy (+ reach 2)) (<= (- bx reach) x (+ bx w reach)))
171
+ (dotimes [k n]
172
+ (let [px (+ bx (port-x w n k) (/ pw 2)) dx (js/Math.abs (- x px))]
173
+ (when (<= dx (+ (/ pw 2) reach))
174
+ (let [d (+ (* dx dx) (* dy dy))]
175
+ (when (or (nil? @best) (< d (first @best))) (reset! best [d [id k]])))))))))
176
+ (second @best)))
177
+
178
+ (defn canvas-geom
179
+ "Where a canvas draws its data (d), in the box b (its size: issue #40) or in one of the default size."
180
+ ([d] (cv/geom (or d cv/empty) hdr))
181
+ ([d id b] (cv/geom (or d cv/empty) hdr (box-size id b))))
182
+
183
+ ;; a tree box shown as a score (discussion #30): its own tree, expanded, remembering where each note is
184
+ ;; written, so its notes edit it directly
185
+ (defn own-tree [id b]
186
+ (when-let [t (mtb/tree-of (:data b))] (try (mt/expand-source t id) (catch :default _ nil))))
187
+
188
+ (defn kept-tree
189
+ "The tree a buffer was kept from, while the buffer has not changed since (its recipe is not stale)."
190
+ [b] (let [r (:recipe b)] (when (and r (not (:stale r))) (:tree r))))
191
+
192
+ ;; score: Verovio draws the buffer quantized into measures (kairotic.quantize); the SVG node is kept and put back on every repaint
193
+ (defn score-entry! [id b]
194
+ (let [tree-box? (= "tree" (klass (:text b)))
195
+ d0 (if tree-box? cv/empty (canvas-data b))
196
+ ;; a tree shown live, or the tree a buffer was kept from while it is unchanged (its recipe)
197
+ lt (if tree-box? (own-tree id b) (or (live-tree id) (kept-tree b)))
198
+ sw (first (box-size id b))
199
+ d [d0 lt sw] c (get @score-cache id)]
200
+ (cond
201
+ (and c (= (:key c) d)) c
202
+ (nil? @vrv) nil
203
+ :else
204
+ (try
205
+ (let [tk @vrv scale 30
206
+ ;; a measured tree as it is; a tree without measures, or the strokes of the buffer, quantized (#86)
207
+ {:keys [mei pieces]} (cond
208
+ lt (qz/->score lt (str (name id) "-"))
209
+ (cv/generic? d0) (sc/->mei-voice (cv/->voice d0) (str (name id) "-"))
210
+ :else (qz/->score d0 (str (name id) "-") (:quant d0)))
211
+ g (js/document.createElementNS "http://www.w3.org/2000/svg" "g")]
212
+ (.setOptions tk (clj->js {:pageWidth (js/Math.round (/ (* (- sw 8) 100) scale)) :pageHeight 60000
213
+ :adjustPageHeight true :breaks "auto" :scale scale
214
+ :header "none" :footer "none" :lyricSize 3.2
215
+ :pageMarginTop 24 :pageMarginBottom 12 :pageMarginLeft 20 :pageMarginRight 20}))
216
+ (.loadData tk mei)
217
+ (set! (.-innerHTML g) (.renderToSVG tk 1))
218
+ (let [sv (.querySelector g "svg")
219
+ h (if sv (js/parseFloat (.getAttribute sv "height")) 70)
220
+ e {:key d :node g :h (if (js/isNaN h) 70 h) :pieces pieces :anchors nil :from (:from (meta lt))}]
221
+ (swap! score-cache assoc id e)
222
+ e))
223
+ (catch :default ex
224
+ (let [e {:key d :node nil :h 40 :error (or (.-message ex) (str ex))}]
225
+ (swap! score-cache assoc id e)
226
+ e))))))
227
+
228
+ (defn local-box
229
+ "Box of an SVG element in the coordinates of `ref` (without going through screen pixels,
230
+ which change when the page is zoomed in or out)."
231
+ [el ref]
232
+ (let [b (.getBBox el)
233
+ m (.multiply (.inverse (.getScreenCTM ref)) (.getScreenCTM el))
234
+ tp (fn [x y] (let [q (.createSVGPoint ($ "canvas"))] (set! (.-x q) x) (set! (.-y q) y) (.matrixTransform q m)))
235
+ a (tp (.-x b) (.-y b))
236
+ c (tp (+ (.-x b) (.-width b)) (+ (.-y b) (.-height b)))]
237
+ {:left (.-x a) :top (.-y a) :right (.-x c) :bottom (.-y c) :w (- (.-x c) (.-x a))}))
238
+
239
+ (defn score-anchors
240
+ "Time ⇄ space anchors of a placed score, in the coordinates of its box."
241
+ [node pieces]
242
+ (when (and node (.querySelector node "svg") (.-isConnected node))
243
+ (->> pieces
244
+ (keep (fn [{:keys [id t]}]
245
+ (when-let [el (.querySelector node (str "#" id))]
246
+ (let [head (or (.querySelector el ".notehead") el)
247
+ r (local-box head node)
248
+ sys (or (.closest el ".system") el)
249
+ sr (local-box sys node)]
250
+ (when (pos? (:w r))
251
+ {:t t :x (:left r) :y0 (- (:top sr) 6) :y1 (+ (:bottom sr) 6) :right (:right sr)})))))
252
+ (group-by :t)
253
+ (map (fn [[_ as]] (apply min-key :x as)))
254
+ (sort-by :t)
255
+ vec)))
256
+
257
+ ;; ───── live layer: number values, flashes, reading cursors ─────
258
+
259
+ (defn shown-flat
260
+ "The last thing a box (by its engine id) showed: with the engine running, up to the instant sounding now."
261
+ [f]
262
+ (if (eng/running?)
263
+ (eng/shown-at f (eng/now))
264
+ (last (get-in @eng/rt [:shows f]))))
265
+
266
+ (defn last-shown "The same, for a box of the current view." [id] (shown-flat (fid id)))
267
+
268
+ (defn recent? [[at _]] (and at (eng/running?) (< (- (eng/now) at) 0.15)))
269
+
270
+ (defn cursor-at
271
+ "A vertical line at time t of box `bid` (canvas or score), with dots on what sounds."
272
+ ([p bid t cls dots?] (cursor-at p bid t cls dots? :x nil))
273
+ ([p bid t cls dots? axis] (cursor-at p bid t cls dots? axis nil))
274
+ ([p bid t cls dots? axis pt]
275
+ (when-let [b (get-in p [:boxes bid])]
276
+ (let [[x y] (box-pos bid b) d (canvas-data b)]
277
+ (case (display-of b)
278
+ :canvas
279
+ (cond
280
+ (= axis :path)
281
+ (when pt
282
+ (let [g (canvas-geom d bid b)]
283
+ (str "<circle class=\"sounding\" cx=\"" (+ x (cv/t->x g (first pt))) "\" cy=\"" (+ y (cv/f->y g (second pt))) "\" r=\"6\"></circle>")))
284
+ (= axis :y)
285
+ (let [g (canvas-geom d bid b) cy (+ y (cv/f->y g (max (:ya g) (min t (:yb g)))))]
286
+ (str "<line class=\"" cls "\" x1=\"" (+ x (:x0 g)) "\" x2=\"" (+ x (:x0 g) (:w g)) "\" y1=\"" cy "\" y2=\"" cy "\"></line>"
287
+ (when dots?
288
+ (apply str (for [[_ v] (cv/read-along d :y t)]
289
+ (str "<circle class=\"sounding\" cx=\"" (+ x (cv/t->x g v)) "\" cy=\"" cy "\" r=\"4\"></circle>"))))))
290
+ :else
291
+ (let [g (canvas-geom d bid b) cx (+ x (cv/t->x g (max (:xa g) (min t (:xb g)))))]
292
+ (str "<line class=\"" cls "\" x1=\"" cx "\" x2=\"" cx "\" y1=\"" (+ y (:y0 g)) "\" y2=\"" (+ y (:y0 g) (:h g)) "\"></line>"
293
+ (when dots?
294
+ (apply str (for [[_ f] (cv/read-at d t)]
295
+ (str "<circle class=\"sounding\" cx=\"" cx "\" cy=\"" (+ y (cv/f->y g f)) "\" r=\"4\"></circle>")))))))
296
+ :score (when-let [a (sc/t->pos (get-in @score-cache [bid :anchors]) t)]
297
+ (let [cx (+ x 4 (:x a)) oy (+ y hdr 4)]
298
+ (str "<line class=\"" cls "\" x1=\"" cx "\" x2=\"" cx "\" y1=\"" (+ oy (max 0 (:y0 a))) "\" y2=\"" (+ oy (:y1 a)) "\"></line>")))
299
+ nil)))))
300
+
301
+ (def param-x0 96)
302
+
303
+ ;; ───── own view of a component: its :view template filled by :derive (or what :draw returns),
304
+ ;; from the last thing it showed ─────
305
+
306
+ (defn ctl-shown [id] (second (last-shown id)))
307
+
308
+ (defn ctl-m*
309
+ "What :derive, :draw and :gesture receive, for box b known to the engine as f."
310
+ [f b]
311
+ (let [[w h] (comp/size-of b)]
312
+ {:id f :shown (second (shown-flat f)) :state (get-in @eng/rt [:states f]) :args (comp/args-for (box-def b) (:text b))
313
+ :text (:text b) :data (:data b) :w w :h h}))
314
+
315
+ (defn ctl-m [id b] (ctl-m* (fid id) b))
316
+
317
+ (defn ctl-shapes*
318
+ "The shapes of a component's own view: :view filled with its holes, or :draw."
319
+ [m b]
320
+ (let [d (box-def b)]
321
+ (cond
322
+ (some? (:view d))
323
+ (let [derived (if-let [f (:derive d)] (f m) {})]
324
+ (shp/fill (:view d) (merge (when (map? (:args m)) (:args m)) (select-keys m [:shown :w :h]) derived)))
325
+ (fn? (:draw d)) ((:draw d) m)
326
+ :else [])))
327
+
328
+ (defn shapes-at
329
+ "The SVG of the own view of box b (engine id f) with its top-left corner at x y."
330
+ [f b x y]
331
+ (let [shape-list (try (ctl-shapes* (ctl-m* f b) b)
332
+ (catch :default e [[:text {:x 4 :y 14 :fill :kairos :size 10} (str "✗ " (or (.-message e) e))]]))]
333
+ (str "<g class=\"shapes\" transform=\"translate(" x "," y ")\">" (shp/svg shape-list) "</g>")))
334
+
335
+ (defn ctl-overlay
336
+ "The own view of a component, and the part of it under (or near) the pointer, highlighted."
337
+ [id b x y]
338
+ (str (shapes-at (fid id) b (+ x grip) y)
339
+ (when-let [[hid k] (:hover-hit @ui)]
340
+ (when (= hid id)
341
+ (let [hs (try (shp/only-hit (ctl-shapes* (ctl-m id b) b) k) (catch :default _ nil))]
342
+ (when (seq hs)
343
+ (str "<g class=\"shapes hit-hover\" transform=\"translate(" (+ x grip) "," y ")\">" (shp/svg hs) "</g>")))))))
344
+
345
+ ;; ───── panels: a sub-patch seen from outside shows the boxes presented inside it ─────
346
+
347
+ (defn child-dims
348
+ "Size of a box in presentation: its own view, or a small chip with its text."
349
+ [b]
350
+ (if (own-view? b) (comp/size-of b) [(box-w (:text b)) box-h]))
351
+
352
+ (def panel-pad 4)
353
+
354
+ (defn panel-layout
355
+ "The presented boxes of a sub-patch box and the size of its panel, or nil if none is presented."
356
+ [b]
357
+ (when (comp/subpatch? b)
358
+ (let [inner (eng/inner-patch b)
359
+ kids (vec (for [[cid cb] (sort-by (fn [[k _]] (box-num k)) (:boxes inner))
360
+ :let [[px py] (:present cb)] :when px]
361
+ (let [[w h] (child-dims cb)] {:id cid :b cb :x px :y py :w w :h h})))]
362
+ (when (seq kids)
363
+ {:kids kids
364
+ :w (max (box-w (:text b)) (+ (* 2 panel-pad) (apply max (map (fn [k] (+ (:x k) (:w k))) kids))))
365
+ :h (+ hdr (* 2 panel-pad) (apply max (map (fn [k] (+ (:y k) (:h k))) kids)))}))))
366
+
367
+ (defn kid-origin [x y k] [(+ x panel-pad (:x k)) (+ y hdr panel-pad (:y k))])
368
+
369
+ (defn panel-svg
370
+ "The fixed part of a panel: its header and, for each presented box, a hit area or a chip."
371
+ [id b w]
372
+ (let [{:keys [kids]} (panel-layout b) idn (esc (name id))]
373
+ (str "<rect class=\"head\" x=\"0.5\" y=\"0.5\" width=\"" (- w 1) "\" height=\"" (- hdr 1) "\"></rect>"
374
+ "<text class=\"lbl\" x=\"8\" y=\"14\">" (esc (:text b)) "</text>"
375
+ (apply str
376
+ (for [k kids :let [[kx ky] (kid-origin 0 0 k)]]
377
+ (if (own-view? (:b k))
378
+ (str "<rect class=\"pres-area\" data-box=\"" idn "\" data-kid=\"" (esc (name (:id k))) "\" x=\"" kx "\" y=\"" ky
379
+ "\" width=\"" (:w k) "\" height=\"" (:h k) "\"><title>" (esc (:text (:b k))) "</title></rect>")
380
+ (str "<rect class=\"chip\" x=\"" kx "\" y=\"" ky "\" width=\"" (:w k) "\" height=\"" (:h k) "\" rx=\"3\"></rect>"
381
+ "<text x=\"" (+ kx 8) "\" y=\"" (+ ky 16) "\">" (esc (:text (:b k))) "</text>")))))))
382
+
383
+ (defn panel-overlay
384
+ "The live part of a panel: the own views of its presented boxes."
385
+ [id b x y]
386
+ (apply str (for [k (:kids (panel-layout b)) :when (own-view? (:b k)) :let [[kx ky] (kid-origin x y k)]]
387
+ (shapes-at (eng/flat-id (conj (engine-path) id) (:id k)) (:b k) kx ky))))
388
+
389
+ ;; ───── presentation mode: only the presented boxes, at their presentation places ─────
390
+
391
+ (defonce pres-mode (atom false))
392
+
393
+ (defn view-box
394
+ "A box as it is placed on screen: in presentation, at its presentation place."
395
+ [b]
396
+ (if (and @pres-mode (:present b)) (assoc b :x (first (:present b)) :y (second (:present b))) b))
397
+
398
+ (defn scene-of
399
+ "The patch that is drawn: in presentation, only its presented boxes, without lines; never the boxes
400
+ that define components (they are in the Components tab, issue #8)."
401
+ [p]
402
+ (if @pres-mode
403
+ {:boxes (into (sorted-map) (for [[id b] (:boxes p) :when (and (:present b) (not (definition? b)))] [id (view-box b)])) :lines []}
404
+ (update p :boxes without-definitions)))
405
+
406
+ (defn presentation
407
+ "Switches the patch between editing and presentation (only the presented boxes, where the performer sees them)."
408
+ ([] (presentation (not @pres-mode)))
409
+ ([on]
410
+ (reset! pres-mode (boolean on))
411
+ ;; in presentation nothing is selected (issue #57)
412
+ (when on (swap! ui assoc :sel nil :insp nil :nsel nil :tsel nil :marquee nil))
413
+ (.toggle (.-classList ($ "canvas-wrap")) "pres" @pres-mode)
414
+ (.toggle (.-classList ($ "pres-toggle")) "on" @pres-mode)
415
+ (set! (.-textContent ($ "pres-toggle")) (if @pres-mode "Edit" "Present"))
416
+ (swap! ui assoc :sel nil :nsel nil)
417
+ (render-all!)
418
+ @pres-mode))
419
+
420
+ (declare code-win-box)
421
+
422
+ (defn code-view
423
+ "SVG of a code box: the source text, the status of its compilation and its parameters."
424
+ [id b w]
425
+ (let [d (box-def b) idn (esc (name id))
426
+ {:keys [ch y-st y-par params]} (code-geom b)
427
+ [gist n] (code-gist b)
428
+ source (str (get-in b [:data :source]))
429
+ open? (= id (code-win-box))
430
+ r (cbox/compiled (:language d) source)
431
+ inf (:info r)
432
+ [st cls] (case (:status r)
433
+ :empty ["empty · double-click to write" "st-wait"]
434
+ :compiling ["compiling…" "st-wait"]
435
+ :ok [(str "✓ " (or (:summary inf) "ready")) "st-ok"]
436
+ :error [(str "✗ " (first (str/split-lines (str (:error r))))) "st-err"]
437
+ ["" "st-wait"])]
438
+ (str "<svg x=\"2\" y=\"" hdr "\" width=\"" (- w 4) "\" height=\"" ch "\" overflow=\"hidden\">"
439
+ "<rect class=\"code-area" (when open? " open") "\" data-box=\"" idn "\" x=\"0\" y=\"0\" width=\"" (- w 4) "\" height=\"" ch "\">"
440
+ "<title>Double-click to edit the code</title></rect>"
441
+ "<text class=\"code\" xml:space=\"preserve\" x=\"6\" y=\"15\">"
442
+ (esc (cond (str/blank? source) "{ } double-click to write"
443
+ (> (count gist) 30) (str (subs gist 0 30) "…")
444
+ :else gist))
445
+ "</text>"
446
+ (when (pos? n)
447
+ (str "<text class=\"code lines\" x=\"" (- w 10) "\" y=\"15\" text-anchor=\"end\">"
448
+ (if open? "✎ open" (str n (if (= 1 n) " line" " lines"))) "</text>"))
449
+ "</svg>"
450
+ "<text class=\"lbl " cls "\" x=\"8\" y=\"" y-st "\">" (esc (if (> (count st) 52) (str (subs st 0 52) "…") st))
451
+ (when (= :error (:status r)) (str "<title>" (esc (:error r)) "</title>")) "</text>"
452
+ (apply str (map-indexed
453
+ (fn [i p]
454
+ (let [y (+ y-par (* i param-h))]
455
+ (str "<text class=\"lbl pname\" x=\"8\" y=\"" (+ y 12) "\">" (esc (:label p)) "</text>"
456
+ "<rect class=\"param" (when (#{"button" "checkbox"} (:type p)) " button") "\" data-box=\"" idn "\" data-param=\"" (esc (:label p))
457
+ "\" x=\"" param-x0 "\" y=\"" (+ y 3) "\" width=\"" (- w param-x0 64) "\" height=\"11\" rx=\"2\"></rect>"
458
+ ;; its value (drawn on top, in the live layer): a double-click there types it (issue #32)
459
+ (when-not (#{"button" "checkbox"} (:type p))
460
+ (str "<rect class=\"pval-hit\" data-box=\"" idn "\" data-param=\"" (esc (:label p))
461
+ "\" x=\"" (- w 62) "\" y=\"" (+ y 1) "\" width=\"58\" height=\"15\">"
462
+ "<title>Double-click to type a value</title></rect>")))))
463
+ params)))))
464
+
465
+ (defn param-value [id b p]
466
+ (let [v (when-let [nd (eng/node (fid id))] (get @(:values nd) (:label p)))]
467
+ (if (number? v) v (:init p))))
468
+
469
+ (defn params-overlay
470
+ "Fill and value of the parameters of a code box (they change while it sounds)."
471
+ [id b x y w]
472
+ (let [{:keys [y-par params]} (code-geom b) tw (- w param-x0 64)]
473
+ (apply str (map-indexed
474
+ (fn [i p]
475
+ (let [v (param-value id b p)
476
+ u (if (> (:max p) (:min p)) (/ (- v (:min p)) (- (:max p) (:min p))) (if (pos? v) 1 0))
477
+ yy (+ y y-par (* i param-h))]
478
+ (str "<rect class=\"pfill\" x=\"" (+ x param-x0) "\" y=\"" (+ yy 3) "\" width=\"" (* tw (max 0 (min 1 u))) "\" height=\"11\" rx=\"2\"></rect>"
479
+ "<text class=\"pval\" x=\"" (+ x (- w 8)) "\" y=\"" (+ yy 12) "\" text-anchor=\"end\">" (cv/fmt v) "</text>")))
480
+ params))))
481
+
482
+ ;; ───── layers (Study 26): marks anchored to boxes or to the paper, and projections ─────
483
+
484
+ (defn view-name "Where the patch is seen now: :patch or :present (the presentation)." [] (if @pres-mode :present :patch))
485
+
486
+ (defn layer-shown? [p lid] (contains? (get-in p [:layers lid :show] #{:patch :present}) (view-name)))
487
+
488
+ (defn resolve-anchor
489
+ "Where an anchor is on screen now: [x y], or nil if its box is not drawn (not presented, or gone)."
490
+ [p [a x y]]
491
+ (if (= a :patch)
492
+ [x y]
493
+ (when-let [b (get-in p [:boxes a])]
494
+ ;; in the presentation a box is where it is presented, and one that is not presented is not there
495
+ (when-let [b (if @pres-mode (when (:present b) (view-box b)) b)]
496
+ (let [[bx by] (box-pos a b)] [(+ bx x) (+ by y)])))))
497
+
498
+ (defn mark-points
499
+ "The points of a mark on screen, or nil if one of them is not (then the mark is not drawn)."
500
+ [p m]
501
+ (let [ps (map (fn [a] (resolve-anchor p a)) (if (#{:text :image} (:kind m)) [(:at m)] (:pts m)))]
502
+ (when (every? some? ps) (vec ps))))
503
+
504
+ (defn mark-svg [p id m]
505
+ (when-let [ps (mark-points p m)]
506
+ (let [r (fn [v] (/ (js/Math.round (* 10 v)) 10)) pts (str/join " " (map (fn [[x y]] (str (r x) "," (r y))) ps))
507
+ idn (esc (name id))]
508
+ (case (:kind m)
509
+ :line (str "<polyline class=\"amark\" data-mark=\"" idn "\" points=\"" pts "\"></polyline>")
510
+ :arrow (let [[[x1 y1] [x2 y2]] ps a (js/Math.atan2 (- y2 y1) (- x2 x1)) L 11
511
+ h (fn [d] [(- x2 (* L (js/Math.cos (+ a d)))) (- y2 (* L (js/Math.sin (+ a d))))])]
512
+ (str "<line class=\"amark\" data-mark=\"" idn "\" x1=\"" (r x1) "\" y1=\"" (r y1) "\" x2=\"" (r x2) "\" y2=\"" (r y2) "\"></line>"
513
+ "<polygon class=\"ahead\" points=\"" (str/join " " (map (fn [[x y]] (str (r x) "," (r y))) [[x2 y2] (h 0.4) (h -0.4)])) "\"></polygon>"))
514
+ :text (let [[[x y]] ps] (str "<text class=\"atext\" data-mark=\"" idn "\" x=\"" (r x) "\" y=\"" (r y) "\">" (esc (:txt m)) "</text>"))
515
+ :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>"))
516
+ ""))))
517
+
518
+ (defn projection-svg
519
+ "The view of box id drawn again in rect, from what it shows now (its :draw or :view at that size)."
520
+ [p id {[x y w h] :rect}]
521
+ (when-let [b (get-in p [:boxes id])]
522
+ (when (own-view? b)
523
+ (let [sh (try (ctl-shapes* (assoc (ctl-m* (fid id) b) :w w :h h) b)
524
+ (catch :default e [[:text {:x 8 :y 18 :fill :kairos :size 11} (str "✗ " (or (.-message e) e))]]))]
525
+ (str "<g class=\"proj shapes\" transform=\"translate(" x "," y ")\">" (shp/svg sh) "</g>")))))
526
+
527
+ (defn as-dragged
528
+ "Mark id as it is while it is being moved with the Annotate bar (all of it, or one end), else m."
529
+ [id m]
530
+ (let [{:keys [kind x0 y0 x y end] did :id} (:adraw @ui)]
531
+ (if (and (= :move kind) (= did id) (number? x))
532
+ (let [dx (- x x0) dy (- y y0)]
533
+ (if (some? end)
534
+ (update-in m [:pts end] (fn [[a px py]] [a (+ px dx) (+ py dy)]))
535
+ (shift-mark m dx dy)))
536
+ m)))
537
+
538
+ (defn layers-svg
539
+ "The layers of patch p that go at z (:over or :under the boxes), as seen now."
540
+ [p z]
541
+ (let [ls (filter (fn [[lid l]] (and (= z (:z l)) (layer-shown? p lid))) (sort-by key (:layers p)))
542
+ on (set (map first ls))]
543
+ (str (apply str (for [[id pr] (:projections p) :when (on (:layer pr))] (projection-svg p id pr)))
544
+ (apply str (for [[id m] (:marks p) :when (on (:layer m))] (mark-svg p id (as-dragged id m)))))))
545
+
546
+ (declare annot-preview render-annot-bar!)
547
+ ;; html boxes (issue #146), in 19-html.cljs
548
+ (declare html-slot-svg html-save-focus! mount-html-slots! refresh-html-boxes!)
549
+
550
+ (defn render-layers! []
551
+ (let [p (current) under ($ "layers-under") over ($ "layers-over")]
552
+ (when under (set! (.-innerHTML under) (layers-svg p :under)))
553
+ (when over (set! (.-innerHTML over) (str (layers-svg p :over) (annot-preview))))
554
+ (render-annot-bar!)))
555
+
556
+ (defonce probe-hooks
557
+ ;; probes on wires (page 26-probes): is a wire probed, and the labels of the probes of a patch
558
+ (atom {:probed? (constantly false) :labels (constantly "")}))
559
+
560
+ (defn render-overlay! []
561
+ (let [p (scene-of (current))
562
+ on (eng/running?)
563
+ ;; what each box draws over itself, in its own slot (issue #166)
564
+ own (for [[id b] (:boxes p) :let [kc (klass (:text b)) [x y] (box-pos id b) [w h] (box-dims id b)]]
565
+ [id (str
566
+ (case kc
567
+ "number" (let [v (or (second (last-shown id)) (get-in @eng/rt [:states (fid id)])
568
+ (eng/num-of (first (eng/args-of (:text b)))) 0)]
569
+ (str "<text class=\"value\" x=\"" (+ x grip 8) "\" y=\"" (+ y 16) "\">▸ " (esc (if (number? v) (cv/fmt v) (pr-str v))) "</text>"))
570
+ ("msg" "bang") (when (recent? (last-shown id))
571
+ (str "<rect class=\"flash\" x=\"" (+ x grip) "\" y=\"" y "\" width=\"" (- w grip) "\" height=\"" h "\" rx=\"3\"></rect>"))
572
+ ("faust~") (params-overlay id b x y w)
573
+ ("reader" "canvas" "freqt") nil
574
+ (when (own-view? b) (ctl-overlay id b x y)))
575
+ (when (panel-layout b) (panel-overlay id b x y)))])
576
+ ;; reading cursors are drawn over everything: they belong to the canvas they read, not to the reader
577
+ parts (for [[id b] (:boxes p) :let [kc (klass (:text b))]]
578
+ (case kc
579
+ "reader" (when on
580
+ (when-let [[_ {:keys [t from axis pt]}] (last-shown id)]
581
+ (when-let [from (and from (number? t) (local-id from))] (cursor-at p from t "cur" true (or axis :x) pt))))
582
+ ("canvas" "freqt") (when on
583
+ (when-let [[at {:keys [t]}] (last-shown id)]
584
+ (when (and (number? t) (< (- (eng/now) at) 2)) (cursor-at p id t "cur2" false))))
585
+ nil))]
586
+ (render-layers!)
587
+ (refresh-html-boxes!)
588
+ (let [scene ($ "scene")]
589
+ (doseq [[id html] own]
590
+ (when-let [slot (.querySelector scene (str "g.live[data-live=\"" (esc (name id)) "\"]"))]
591
+ ;; only when it changed (a new scene makes new slots)
592
+ (when (not= html (aget slot "kairoticLive")) (aset slot "kairoticLive" html) (set! (.-innerHTML slot) html)))))
593
+ (set! (.-innerHTML ($ "cursors"))
594
+ (str (apply str parts)
595
+ (when-not @pres-mode ((:labels @probe-hooks) p))
596
+ ;; in presentation the readers are usually hidden, but their cursors still show on the canvases
597
+ (when (and @pres-mode on)
598
+ (apply str (for [[id b] (:boxes (current))
599
+ :when (and (= "reader" (klass (:text b))) (not (get-in p [:boxes id])))]
600
+ (when-let [[_ {:keys [t from axis pt]}] (last-shown id)]
601
+ (when-let [from (and from (number? t) (local-id from))]
602
+ (cursor-at p from t "cur" true (or axis :x) pt))))))))))
603
+
604
+ ;; ───── the header of a box with data: ⇄ shows it in its next view, { } opens its data as text in the
605
+ ;; code window (discussion #30) ─────
606
+
607
+ (defn next-view
608
+ "The view after the one a box shows now, if its class has more than one."
609
+ [b]
610
+ (let [vs (vec (comp/views-of b)) cur (view-of b)]
611
+ (when (> (count vs) 1)
612
+ (nth vs (mod (inc (or (first (keep-indexed (fn [i v] (when (= v cur) i)) vs)) 0)) (count vs))))))
613
+
614
+ (defn header-chips
615
+ "[[kind label title] …] for the header of a box: from right to left."
616
+ [id b]
617
+ (let [nv (next-view b)]
618
+ (cond-> []
619
+ (and (comp/source-of b) (not= :code (display-of b)))
620
+ (conj [:code "{ }" (str "Its data as text, in the code window: (source " id ")")])
621
+ nv (conj [:view (str "⇄ " (name nv)) (str "Show it as " (name nv) ": (view " id " " nv ")")]))))
622
+
623
+ (def chip-ch 6.4) ; width of a character of a chip (10.5px mono)
624
+
625
+ (defn chips-svg
626
+ "The chips drawn from the right edge `x1` of the header; returns [svg width]."
627
+ [id chips x1]
628
+ (reduce (fn [[acc right] [kind label title]]
629
+ (let [cw (+ 10 (* chip-ch (count label))) x (- right cw)]
630
+ [(str acc "<g class=\"hchip\" data-chip=\"" (name kind) "\" data-box=\"" (esc (name id)) "\">"
631
+ "<rect x=\"" x "\" y=\"3\" width=\"" cw "\" height=\"" (- hdr 6) "\" rx=\"3\"></rect>"
632
+ "<text x=\"" (+ x (/ cw 2)) "\" y=\"" (- hdr 6) "\" text-anchor=\"middle\">" (esc label) "</text>"
633
+ "<title>" (esc title) "</title></g>")
634
+ (- x 4)]))
635
+ ["" x1] chips))
636
+
637
+ (defn box-header [id b w]
638
+ (let [tree-box? (= "tree" (klass (:text b)))
639
+ [chips x1] (chips-svg id (header-chips id b) (- w 4))]
640
+ (str "<rect class=\"head\" x=\"0.5\" y=\"0.5\" width=\"" (- w 1) "\" height=\"" (- hdr 1) "\"></rect>"
641
+ "<text class=\"lbl\" x=\"8\" y=\"14\">" (esc (:text b)) "</text>"
642
+ "<text class=\"lbl info\" x=\"" (- x1 (if (seq chips) 2 4)) "\" y=\"14\" text-anchor=\"end\">"
643
+ (esc (cond
644
+ (= :code (display-of b)) (str (:language (box-def b)) " · ✎")
645
+ tree-box? (if-let [t (mtb/tree-of (:data b))] (mt/summary t) "empty")
646
+ (= :html (display-of b)) (let [n (hic/outlets (hic/view-of (:data b)))] (str n (if (= 1 n) " outlet" " outlets")))
647
+ :else (cond
648
+ (live-tree id) (str "tree · " (mt/summary (live-tree id)) " · (keep! " id ")")
649
+ (kept-tree b) (str "kept · " (mt/summary (kept-tree b))
650
+ (when-let [f (:from (:recipe b))] (str " · from " f)))
651
+ :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))
652
+ (when (:recipe b) (str " · changed since kept (remake! " id ")")))))) "</text>"
653
+ chips)))
654
+
655
+ (declare gesture!)
656
+
657
+ (defn render-crumbs!
658
+ "Where the patch on screen is: work › :b5 patch voice › …"
659
+ []
660
+ (let [path @view-path root (root-patch)]
661
+ (set! (.-innerHTML ($ "crumbs"))
662
+ (if (empty? path)
663
+ ""
664
+ (str "<button data-up=\"" (count path) "\">work</button>"
665
+ (apply str (map-indexed
666
+ (fn [i id]
667
+ (let [b (get-in (patch-in root (take i path)) [:boxes id])
668
+ label (esc (str id " " (:text b)))]
669
+ (str " › " (if (= i (dec (count path)))
670
+ (str "<span class=\"here\">" label "</span>")
671
+ (str "<button data-up=\"" (- (count path) i 1) "\">" label "</button>")))))
672
+ path)))))))
673
+
674
+ ;; ───── Present with boxes selected (issue #42): those not in the presentation yet can join it, where they are ─────
675
+
676
+ (defn pres-ask-el []
677
+ (or ($ "pres-ask")
678
+ (let [el (js/document.createElement "div")]
679
+ (set! (.-id el) "pres-ask")
680
+ (set! (.-className el) "perform-pop")
681
+ (set! (.-hidden el) true)
682
+ (.appendChild (.-body js/document) el)
683
+ (.addEventListener el "click"
684
+ (fn [e]
685
+ (when-let [a (.. e -target -dataset -pres)]
686
+ (set! (.-hidden el) true)
687
+ (case a
688
+ "cancel" nil
689
+ "all" (gesture! "(presentation true)")
690
+ (do (gesture! (str "(present-in-place " a ")"))
691
+ (gesture! "(presentation true)"))))))
692
+ el)))
693
+
694
+ (defn unpresented-selection
695
+ "The selected boxes that are not in the presentation yet."
696
+ []
697
+ (let [p (current)] (vec (sort (filter (fn [id] (and (get-in p [:boxes id]) (not (get-in p [:boxes id :present])))) (sel-ids))))))
698
+
699
+ (defn ask-present-selection!
700
+ "Asks whether the selected boxes `ids` should join the presentation, where they are in the patch."
701
+ [ids]
702
+ (let [el (pres-ask-el) n (count ids)]
703
+ (set! (.-innerHTML el)
704
+ (str "<p><b>Present</b> · " (if (= 1 n) "the selected box is" (str "the " n " selected boxes are"))
705
+ " not in the presentation yet. Present " (if (= 1 n) "it" "them") " where " (if (= 1 n) "it is" "they are") " in the patch?</p>"
706
+ "<div class=\"pp-actions\">"
707
+ "<button class=\"act primary\" data-pres=\"" (esc (str/join " " ids)) "\">Present the selection</button>"
708
+ "<button class=\"act\" data-pres=\"all\">Present without " (if (= 1 n) "it" "them") "</button>"
709
+ "<button class=\"act\" data-pres=\"cancel\">Cancel</button>"
710
+ "</div>"))
711
+ (set! (.-hidden el) false)))
712
+
713
+ (.addEventListener ($ "pres-toggle") "click"
714
+ (fn [_]
715
+ (let [ids (when-not @pres-mode (unpresented-selection))]
716
+ (if (seq ids)
717
+ (ask-present-selection! ids)
718
+ (do (set! (.-hidden (pres-ask-el)) true)
719
+ (gesture! (str "(presentation " (not @pres-mode) ")")))))))
720
+
721
+ (.addEventListener ($ "crumbs") "click"
722
+ (fn [e] (when-let [n (.. e -target -dataset -up)] (gesture! (str "(up " n ")")))))
723
+
724
+ (declare render-inspector!)
725
+
726
+ (defn render-scene [p]
727
+ (let [p (scene-of p)
728
+ {:keys [sel wire hover-in hover-out nsel ldrag]} @ui
729
+ chosen (sel-ids)
730
+ _ (doseq [[id b] (:boxes p) :when (= :score (display-of b))] (score-entry! id b))
731
+ lines (map-indexed
732
+ (fn [idx [a o b i :as l]]
733
+ (if (and (get-in p [:boxes a]) (get-in p [:boxes b]))
734
+ (let [[x1 y1] (out-xy p a o) [x2 y2] (in-xy p b i)
735
+ s (str (if (= sel [:line l]) " sel" "")
736
+ (when (and (= o 2) (= "freqt" (klass (get-in p [:boxes a :text])))) " edits")
737
+ (when (and (not @pres-mode) ((:probed? @probe-hooks) l)) " probed"))
738
+ buf (and (= i 1) (let [k (klass (get-in p [:boxes a :text]))] (or (music-classes k) (= "sample" k) (= "tree" k))))]
739
+ (let [d (wire-d x1 y1 x2 y2)]
740
+ (str "<path class=\"wire" s (when buf " buffer") "\" d=\"" d "\"></path>"
741
+ "<path class=\"wire-hit\" data-line=\"" idx "\" d=\"" d "\"></path>")))
742
+ ""))
743
+ (:lines p))
744
+ ;; from the bottom of the stack to the top (issue #166): the last one drawn is the one on top
745
+ bxs (for [[id b] (by-z (:boxes p))]
746
+ (let [[x y] (box-pos id b) t (:text b) [w h] (box-dims id b) [ins outs] (io b)
747
+ kc (klass t)
748
+ music-box? (contains? #{:canvas :score :html} (display-of b))
749
+ code-box? (= :code (display-of b))
750
+ ctl? (own-view? b)
751
+ action-box? (or ctl? (contains? action-classes kc))
752
+ 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")
753
+ (when action-box? (str " act " (if ctl? "ctl" kc)))
754
+ (when (contains? chosen id) " sel") (when (= id (first hover-in)) " drop")
755
+ (when (and (:present b) (not @pres-mode)) " presented") (when (panel-layout b) " panel"))
756
+ idn (esc (name id))
757
+ d (if (music? b) (shown-data id b) (canvas-data b))
758
+ content (case (if music-box? (display-of b) kc)
759
+ :canvas (let [dr (when (and ldrag (= (:box ldrag) id)) ldrag)
760
+ g (if dr (:g dr) (canvas-geom d id b))]
761
+ (cv/svg idn d g (when (= (first nsel) id) (second nsel))
762
+ (when (and dr (= :move (:kind dr)) (:moved dr)) {(:tid dr) (:pts dr)})
763
+ (when (and dr (= :draw (:kind dr))) (:pts dr))))
764
+ :score (let [c (get @score-cache id)]
765
+ (str "<rect class=\"paper mus-body\" data-box=\"" idn "\" x=\"2\" y=\"" hdr "\" width=\"" (- w 4) "\" height=\"" (- h hdr 2) "\"></rect>"
766
+ "<g class=\"score-slot\" data-box=\"" idn "\" transform=\"translate(4," (+ hdr 4) ")\"></g>"
767
+ (cond
768
+ (nil? c) (str "<text class=\"wait\" x=\"12\" y=\"" (+ hdr 26) "\">"
769
+ (if (= :error @vrv-status)
770
+ "Could not load Verovio (the notation): ⇄ shows it another way"
771
+ "Loading the notation (Verovio, about 8 MB)…")
772
+ "</text>")
773
+ (:error c) (str "<text class=\"wait\" x=\"12\" y=\"" (+ hdr 26) "\">"
774
+ (esc (str "Could not draw: " (:error c))) "</text>"))))
775
+ :html (html-slot-svg id b w h)
776
+ "bang" (str "<circle class=\"bangc\" cx=\"" (+ grip (/ (- w grip) 2)) "\" cy=\"" (/ h 2) "\" r=\"7\"></circle>")
777
+ "msg" (str "<text x=\"" (+ grip 6) "\" y=\"16\">" (esc (str/trim (subs (str/trim t) 3))) "</text>")
778
+ (when ctl?
779
+ (str "<rect class=\"ctl-area\" x=\"" grip "\" y=\"0\" width=\"" (- w grip) "\" height=\"" h "\"><title>"
780
+ (esc (str t (when-let [u (:doc (box-def b))] (str " — " u)))) "</title></rect>")))]
781
+ (str "<g class=\"" cls "\" data-box=\"" idn "\" transform=\"translate(" x "," y ")\">"
782
+ "<rect class=\"body\" width=\"" w "\" height=\"" h "\" rx=\"3\"></rect>"
783
+ (cond code-box? (str (box-header id b w) (code-view id b w))
784
+ music-box? (str (box-header id b w) content
785
+ (when-not @pres-mode
786
+ (str "<path class=\"resize-corner\" data-box=\"" idn "\" d=\"M" (- w 14) " " (- h 3) " L" (- w 3) " " (- h 14)
787
+ " L" (- w 3) " " (- h 3) " Z\"><title>Drag to resize"
788
+ (when (= :score (display-of b)) " (its width; the height follows the notation)")
789
+ " · double-click: default size</title></path>")))
790
+ (panel-layout b) (panel-svg id b w)
791
+ action-box? (str "<rect class=\"grip\" x=\"0\" y=\"0\" width=\"" grip "\" height=\"" h "\" rx=\"2\"></rect>" content)
792
+ ;; a patch @name: its line, followed (↻) or pinned (⌖ moment), ⚠ when something is wrong (#117)
793
+ (line-ref? b) (str "<text x=\"10\" y=\"16\">" (esc t) "</text>"
794
+ "<text class=\"ref-badge\" x=\"" (- w 8) "\" y=\"16\" text-anchor=\"end\">" (esc (ref-badge b)) "</text>"
795
+ "<title>" (esc (or (ref-warning b)
796
+ (let [r (resolve-ref b)]
797
+ (str "the line " (line-name (:line r)) (if (:pinned r) ", pinned to a point of its history" ", at its newest point")
798
+ " · double-click opens it"))))
799
+ "</title>")
800
+ :else (str "<text x=\"10\" y=\"16\">" (esc t) "</text>"))
801
+ (apply str (for [i (range ins)]
802
+ (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>")))
803
+ (apply str (for [o (range outs)]
804
+ (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>")))
805
+ ;; its id, over its top right corner: shown when it is hovered or selected, or for all with I
806
+ ;; (issue #163)
807
+ (when-not @pres-mode
808
+ (str "<text class=\"idtag\" x=\"" w "\" y=\"-5\" text-anchor=\"end\">" idn "</text>"))
809
+ ;; what changes while it plays (a value, a flash, its own view) is drawn here, in the box,
810
+ ;; so that a box over it covers it too (issue #166); in patch coordinates
811
+ "<g class=\"live\" data-live=\"" idn "\" transform=\"translate(" (- x) "," (- y) ")\"></g>"
812
+ "</g>")))
813
+ temp (when (and wire (get-in p [:boxes (:from wire)]))
814
+ (let [[x1 y1] (out-xy p (:from wire) (:out wire))]
815
+ (str "<path class=\"wire temp\" d=\"" (wire-d x1 y1 (:x wire) (:y wire)) "\"></path>")))]
816
+ ;; html boxes keep their own elements (issue #146): taken out before the scene is written, put back after
817
+ (html-save-focus!)
818
+ (set! (.-innerHTML ($ "scene")) (str (apply str lines) (apply str bxs) temp))
819
+ (mount-html-slots!)
820
+ ;; the paper grows with what is on it (with room to keep going), so nothing at the edge is cut off
821
+ (let [[mx my] (reduce (fn [[mx my] [id b]]
822
+ (let [[x y] (box-pos id b) [w h] (box-dims id b)]
823
+ [(max mx (+ x w)) (max my (+ y h))]))
824
+ [0 0] (:boxes p))
825
+ cv ($ "canvas") st (.-style cv)]
826
+ (if (and embed-mode (seq (:boxes p)))
827
+ ;; embedded: the whole patch in the frame, scaled (a patch only shrinks; a presentation fills it)
828
+ (let [[x0 y0] (reduce (fn [[ax ay] [id b]] (let [[x y] (box-pos id b)] [(min ax x) (min ay y)]))
829
+ [js/Infinity js/Infinity] (:boxes p))
830
+ pad 14 x0 (- x0 pad) y0 (- y0 pad)
831
+ bw (- (+ mx pad) x0) bh (- (+ my pad) y0)
832
+ wrap ($ "canvas-wrap") cw (max 1 (.-clientWidth wrap)) ch (max 1 (.-clientHeight wrap))
833
+ fill? (= embed-mode :present)
834
+ [vw vh] (if fill? [bw bh] [(max bw cw) (max bh ch)])]
835
+ (.setAttribute cv "viewBox" (str x0 " " y0 " " vw " " vh))
836
+ (.setAttribute cv "preserveAspectRatio" (if fill? "xMidYMid meet" "xMinYMin meet"))
837
+ (set! (.-width st) "100%")
838
+ (set! (.-height st) "100%"))
839
+ (do (.removeAttribute cv "viewBox")
840
+ ;; at least as wide as the pane (wider with the panel on the right hidden: issue #40)
841
+ (set! (.-width st) (str (max 900 (or (some-> ($ "canvas-wrap") .-clientWidth) 0) (+ mx 160)) "px"))
842
+ (set! (.-height st) (str (max 680 (+ my 200)) "px")))))
843
+ (render-crumbs!)
844
+ ;; scores already drawn are put back in their box, with the chosen stroke marked
845
+ (doseq [slot (array-seq (.querySelectorAll ($ "scene") ".score-slot"))]
846
+ (let [id (keyword (.. slot -dataset -box)) c (get @score-cache id)]
847
+ (when-let [node (:node c)]
848
+ (.appendChild slot node)
849
+ ;; the note selected for editing (Study 20)
850
+ (doseq [el (array-seq (.querySelectorAll node ".tsel"))] (.remove (.-classList el) "tsel"))
851
+ (when-let [ts (:tsel @ui)]
852
+ (when (= (:score ts) id)
853
+ (when-let [pid (tsel-piece-id ts (:pieces c))]
854
+ (when-let [el (.querySelector node (str "#" pid))] (.add (.-classList el) "tsel")))))
855
+ (when (empty? (:anchors c))
856
+ (swap! score-cache assoc-in [id :anchors] (score-anchors node (:pieces c))))
857
+ (doseq [el (array-seq (.querySelectorAll node "g.note.sel"))] (.remove (.-classList el) "sel"))
858
+ (when (= (first nsel) id)
859
+ (doseq [el (array-seq (.querySelectorAll node (str "[id^=\"n-" (name id) "-" (name (second nsel)) "-\"]")))]
860
+ (.add (.-classList el) "sel"))))))
861
+ (render-overlay!)
862
+ (render-inspector!)))
863
+
864
+ ;; ───── inspector: the selected box, editable from the patch ─────
865
+ ;; Under a box opened with ⌘/Ctrl+click (a plain click only selects and moves it): its class and usage,
866
+ ;; one field per declared argument (:args) and its whole text. Changing a field rewrites the box with
867
+ ;; (text! …), as if it had been typed.
868
+
869
+ (defonce insp-key (atom nil))
870
+
871
+ (defn arg-kind [v] (cond (boolean? v) :flag (or (number? v) (keyword? v)) :num :else :word))
872
+
873
+ (defn spec-of [d]
874
+ (let [sp (:args d)] (when (and (sequential? sp) (seq sp) (every? (fn [x] (and (vector? x) (keyword? (first x)))) sp)) sp)))
875
+
876
+ (defn insp-field [a v cur]
877
+ (case (arg-kind v)
878
+ :flag (str "<label><input type=\"checkbox\" data-arg=\"" (name a) "\"" (when cur " checked") "> " (name a) "</label>")
879
+ :num (str "<label>" (name a) " <input data-arg=\"" (name a) "\" value=\"" (if (number? cur) (cv/fmt cur) "") "\" size=\"6\" inputmode=\"decimal\"></label>")
880
+ (str "<label>" (name a) " <input data-arg=\"" (name a) "\" value=\"" (esc (if (keyword? cur) (name cur) (str (or cur "")))) "\" size=\"8\"></label>")))
881
+
882
+ (defonce insp-busy (atom false))
883
+
884
+ (defn insp-commit! [input]
885
+ (let [id (first @insp-key) b (when id (get-in (current) [:boxes id]))]
886
+ (when b
887
+ (let [d (box-def b) role (.. input -dataset -role) arg (.. input -dataset -arg)]
888
+ (reset! insp-busy true)
889
+ (try (cond
890
+ (= role "text")
891
+ (let [v (str/trim (.-value input))]
892
+ (when (and (seq v) (not= v (:text b))) (gesture! (str "(text! " id " " (pr-str v) ")"))))
893
+ arg
894
+ (let [a (keyword arg) sv (some (fn [[k v]] (when (= k a) v)) (spec-of d))
895
+ vals (comp/args-for d (:text b)) raw (str/trim (.-value input))
896
+ nv (case (arg-kind sv)
897
+ :flag (.-checked input)
898
+ :num (let [n (js/parseFloat raw)] (if (js/isNaN n) (get vals a) n))
899
+ (when (seq raw) (keyword raw)))
900
+ t (comp/args-text d (klass (:text b)) (assoc vals a nv))]
901
+ (when (not= t (:text b)) (gesture! (str "(text! " id " " (pr-str t) ")")))))
902
+ (finally (reset! insp-busy false)))))))
903
+
904
+ (defn render-inspector! []
905
+ (let [old ($ "inspector") [kind id] (:sel @ui)
906
+ moving? (let [d (:drag @ui)] (and d (:moved d))) ; hidden while a box is being moved
907
+ b (when (and (= kind :box) (= id (:insp @ui)) (not @pres-mode) (not moving?)) (get-in (current) [:boxes id]))
908
+ k (when b [id (:text b) (:x b) (:y b) (cmd-path)])
909
+ focused (.-activeElement js/document)]
910
+ ;; a field being edited is applied before the inspector goes away or is redrawn
911
+ (when (and old (not @insp-busy) (not= k @insp-key) (.contains old focused) (= "INPUT" (.-tagName focused)))
912
+ (insp-commit! focused))
913
+ (cond
914
+ (nil? b) (do (reset! insp-key nil) (when old (.remove old)))
915
+ (= k @insp-key) nil
916
+ :else
917
+ (let [d (box-def b) spec (spec-of d) vals (when spec (comp/args-for d (:text b)))
918
+ [_ h] (box-dims id b)
919
+ el (or old (let [el (js/document.createElement "div")]
920
+ (set! (.-id el) "inspector")
921
+ (.addEventListener el "change" (fn [e] (insp-commit! (.-target e))))
922
+ ;; what a patch box can do with lines (#117): extract it to one, or pin, follow, inline the one it uses
923
+ (.addEventListener el "click"
924
+ (fn [e]
925
+ (when-let [a (some-> (.closest (.-target e) "[data-insp-act]") (.getAttribute "data-insp-act"))]
926
+ (let [id (first @insp-key)]
927
+ (if (= a "extract-line")
928
+ (let [nm (str/trim (.-value (.querySelector el "[data-role=line-name]")))]
929
+ (when (seq nm) (gesture! (str "(extract-line " id " " (pr-str nm) ")"))))
930
+ (gesture! (str "(" a " " id ")")))))))
931
+ (.addEventListener el "keydown"
932
+ (fn [e] (case (.-key e)
933
+ "Enter" (.blur (.-target e))
934
+ "Escape" (do (reset! insp-key nil) (swap! ui assoc :insp nil) (render-inspector!))
935
+ nil)))
936
+ (.appendChild ($ "canvas-wrap") el)
937
+ el))]
938
+ (reset! insp-key k)
939
+ (set! (.-title el) (or (:doc d) ""))
940
+ (let [[px py] (wrap-px (:x b) (+ (:y b) h 8))]
941
+ (set! (.. el -style -left) (str px "px"))
942
+ (set! (.. el -style -top) (str py "px")))
943
+ (set! (.-innerHTML el)
944
+ (str "<div class=\"insp-head\"><b>" (esc (klass (:text b))) "</b> <span>" (esc (or (:usage d) "")) "</span></div>"
945
+ (when spec (str "<div class=\"insp-args\">" (apply str (for [[a v] spec] (insp-field a v (get vals a)))) "</div>"))
946
+ "<input class=\"insp-text\" data-role=\"text\" spellcheck=\"false\" value=\"" (esc (:text b)) "\">"
947
+ (cond
948
+ (line-ref? b)
949
+ (str "<div class=\"insp-acts\">"
950
+ (if (:pin b)
951
+ "<button class=\"act\" data-insp-act=\"follow-ref\" title=\"Follow its line again (its newest point)\">Follow</button>"
952
+ "<button class=\"act\" data-insp-act=\"pin-ref\" title=\"Keep it at the point of its line it reads now\">Pin</button>")
953
+ "<button class=\"act\" data-insp-act=\"inline-ref\" title=\"A copy of the line inside this box, detached from it\">Inline</button>"
954
+ "<button class=\"act\" data-insp-act=\"open-ref\" title=\"Open its line, in its tab\">Open line</button></div>")
955
+ (and (embedded? b) (not @perf) (not @scratch))
956
+ (str "<div class=\"insp-acts\"><input data-role=\"line-name\" placeholder=\"line name\" size=\"12\" spellcheck=\"false\" aria-label=\"Name of the new line\">"
957
+ "<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>")
958
+ :else "")))))))
959
+
960
+ ;; ───── engine: start, stop and messages ─────
961
+
962
+ (defn transport-info! []
963
+ (let [on (eng/running?)]
964
+ (set! (.-textContent ($ "transport-info"))
965
+ (cond (not on) "engine stopped"
966
+ ;; it plays another line than the one on screen (#117): which
967
+ (playing-elsewhere?) (let [n (count (view-instances))]
968
+ (str "playing " (line-name (playing-line))
969
+ (case n 0 "" 1 (str " · " (line-name (active-line)) " inside it")
970
+ (str " · " (line-name (active-line)) " ×" n ": what you play goes to all"))))
971
+ :else "engine running"))
972
+ (.toggle (.-classList ($ "play")) "on" on)))
973
+
974
+ (declare sync-live-trees!)
975
+
976
+ (defn live! []
977
+ (when (eng/running?)
978
+ (when (sync-live-trees!) (render-scene (current)))
979
+ (render-overlay!)
980
+ (let [ps (eng/take-prints!)]
981
+ (doseq [[_ v label] (take 12 ps)] (repl-print! "out" (esc (print-line v label))))
982
+ (when (> (count ps) 12) (repl-print! "out" (esc (str "print: … and " (- (count ps) 12) " more")))))
983
+ (js/requestAnimationFrame (fn [_] (live!)))))
984
+
985
+ (defn play
986
+ "Starts the engine and fires the loadbang boxes. Everything else acts when messages reach it."
987
+ []
988
+ (let [was-on (eng/running?)]
989
+ ;; the line on screen is the one that plays from now on (#117, decision 6)
990
+ (swap! line-state assoc :playing (active-line))
991
+ (eng/start! engine-patch true)
992
+ (transport-info!)
993
+ (when-not was-on (js/requestAnimationFrame (fn [_] (live!))))
994
+ :running))
995
+
996
+ (defn stop
997
+ "Stops the engine: silence, and ramps, metros and counters go back to their initial state."
998
+ []
999
+ (eng/stop!)
1000
+ (transport-info!)
1001
+ (render-overlay!)
1002
+ ;; back to the initial state: the data boxes send what they hold again, so what depends on them has it
1003
+ (refill-data!)
1004
+ :stopped)
1005
+
1006
+ (defn send!
1007
+ "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)."
1008
+ ([id v] (send! id 0 v))
1009
+ ([id inlet v]
1010
+ (need-box id)
1011
+ (let [was-on (eng/running?)]
1012
+ (let [[tid ti] (target id inlet)] (inject-local! tid ti v))
1013
+ (when-not was-on (transport-info!) (js/requestAnimationFrame (fn [_] (live!))))
1014
+ v)))
1015
+
1016
+ ;; ───── the Code tab and the REPL line: CodeMirror once it is loaded (14-editor.cljs), a textarea and an
1017
+ ;; input until then (or if it cannot be loaded). Everything reads and writes them through these.
1018
+
1019
+ (defonce code-ed (atom nil)) ; the editor of the Code tab
1020
+ (defonce repl-ed (atom nil)) ; the editor of the REPL line
1021
+
1022
+ (defn code-text [] (if-let [e @code-ed] (.getValue e) (.-value ($ "code"))))
1023
+ (declare code-tab-refresh!)
1024
+ (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)))
1025
+ (defn repl-text [] (if-let [e @repl-ed] (.getValue e) (.-value ($ "repl-in"))))
1026
+ (defn set-repl-text! [v] (if-let [e @repl-ed] (do (.setValue e v) (.cursorToEnd e)) (set! (.-value ($ "repl-in")) v)))
1027
+ (defn focus-repl! [] (if-let [e @repl-ed] (.focus e) (.focus ($ "repl-in"))))
1028
+
1029
+ (defonce data-ed (atom nil)) ; the read-only editor of the Data view of the Code tab
1030
+
1031
+ (defn data-view? [] (= :data (:code-view @ui)))
1032
+
1033
+ (defn set-data-text! [v]
1034
+ (if-let [e @data-ed]
1035
+ (when (not= v (.getValue e)) (.setValue e v))
1036
+ (when (not= v (.-textContent ($ "edn"))) (set! (.-textContent ($ "edn")) v))))
1037
+
1038
+ (defn render-code [p]
1039
+ (let [{:keys [dirty]} @ui data (data-view?)]
1040
+ (when-not dirty (set-code-text! (patch->code p)))
1041
+ ;; the data is written only while it is shown: it is the whole state, pretty-printed
1042
+ (when data (set-data-text! (patch->edn p)))
1043
+ (let [st ($ "code-state")]
1044
+ (set! (.-textContent st) (cond data "read-only: the state the history produces"
1045
+ dirty "edited: run it to apply it to the patch"
1046
+ :else "in sync with the patch"))
1047
+ (set! (.-className st) (if (and dirty (not data)) "state dirty" "state")))
1048
+ (set! (.-hidden ($ "code-run")) data)
1049
+ (set! (.-hidden ($ "code-revert")) data)
1050
+ (set! (.-disabled ($ "code-run")) (not dirty))
1051
+ (set! (.-disabled ($ "code-revert")) (not dirty))))