-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
622 lines (545 loc) · 19.8 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
<html>
<!--
ape-cljs-playground - Away from Preferred Editor ClojureScript Playground
This page allows you to simply try out Clojure forms on your mobile device in
moments when you don't have your laptop/desktop with preferred text editor at
hand. (You can also, for example, use it to write and run solutions for all of
the Advent of Code puzzles, https://adventofcode.com/, as I did for the 2023
edition.)
Therefore, this little project aims to provide mobile-friendly Clojure editing.
To me this means (at least):
- Parinfer!
- kept in (local) storage to allow for quick and easy incremental work;
- evaluate anything that's available in (the SCI subset of) ClojureScript,
including macros within the browser;
- all output (including errors) displayed on the page.
Quite a number of web-based/mobile-oriented Clojure editors exist, but I haven't
yet found any that support all of the above sub-goals 'out of the box',
particularly the storage part. So, that's the itch being scratched here.
Not particularly aiming for
- performance (just spoiled by SCI's out-of-the-box speed I guess);
- small download size.
The project's git repository can be found at
/~https://github.com/jurjanpaul/ape-cljs-playground.
The page is hosted at https://jurjanpaul.github.io/ape-cljs-playground.
Currently provides
- run ClojureScript (per SCI / Scittle, /~https://github.com/babashka/scittle)
- includes macro support out-of-the-box (might require an extra reload)
- Parinfer (per parinfer-codemirror)
- persistence (per browser's localStorage)
- Reagent (not essential, but did not require any extra effort per Scittle,
plus it definitely kickstarted some dogfeeding).
To render, simply invoke the convenience function `render-with-reagent`
with a reagent component function as parameter.
- maximum portability by being contained in a single HTML file
(not at all essential, but nice as long as it's feasible in light of the
remaining wishes)
=> Well, this is no longer really true anymore now that I'm depending on
a tweaked version of parinfer-codemirror.js to improve scrolling
behaviour.
- trivial, but very helpful: can be saved as an 'app' on phone's home screen,
each 'app' automagically getting its own localStorage!
- history / undo + redo
- Share feature that encodes code in URL, protecting the default/main buffer
by saving changes to a new localStorage buffer after opening such an URL.
Note: As was to be expected, large programs will result in a huge URL that
no (mobile) browser can actually open.
Current annoyances
- After (un)zooming&scrolling, the cursor position sometimes no longer
corresponds to the actual insertion point;
=> Unfortunately, I still haven't figured out how to deal with this,
other than:
- zooming out;
- selecting another page element;
- tilting the phone;
- reloading the entire page...
- Cursor position being scrolled out of focus when deleting/commenting code.
=> Improved the situation w.r.t. vertical scrolling somewhat by tweaking
parinfer-codemirror.js
Other wishes/TODOs (nothing planned):
- on-screen footer keyboard with opening braces + other useful special chars
- multiple buffers
(Hint: by saving the page multiple times to my iPhone's Home screen I
already get multiple buffers for free!)
- improved styling for mobile (just zoom and swipe/scroll a lot for now!);
- linting
- allow fetching existing code (gist) from url
- add deps (seems hard/hardly possible)
- separate Scittle script's namespace from user entered code's namespace
- save to gist or ... ?
- upgrade to CodeMirror 6 (support for Parinfer seems to be a challenge
still)
API
- everything that Scittle exposes, including:
- cljs.pprint as pprint
- clojure.string as string
- reagent.core as r
- reagent.dom as rdom
- render-with-reagent
- load-from-url (experimental)
All in all I feel this is a nice showcase of what is possible with Scittle!
Thanks to all library and tool builders who made it possible for me to throw
this together so lazily!
Feel free to customize and extend this file as desired. Of course, I would
like to hear if this turns out helpful to you in any way.
Jurjan-Paul Medema
Github: jurjanpaul
Twitter: @jurjanpaul
Clojurians Slack: @jurjanpaul
P.S. Some of the alternative mobile / in-browser Clojure(Script) 'playgrounds'
that I know of:
* http://app.klipse.tech/
* https://borkdude.github.io/sci.web/
* https://clojurescript.io/
* https://nextjournal.github.io/clojure-mode/#try-it
* https://oakes.github.io/paren-soup/
* https://squint-cljs.github.io/squint/
* Replete (iPhone app)
('Ape' also refers to the fact that this can indeed be considered a poor copy or
derivative of other people's hard work.)
-->
<head>
<title>Away from Preferred Editor ClojureScript Playground</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="url" content="https://jurjanpaul.github.io/ape-cljs-playground">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&family=Source+Code+Pro&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/codemirror@5.65.6/lib/codemirror.css">
<style type="text/css">
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
padding: 4px 4px 2em;
font-family: "Open Sans", sans-serif;
}
button {
border-radius: 4px;
padding: 2px 6px 2px 6px;
}
.parinfer-error {
background: #FFBEBE;
color: black !important;
}
.parinfer-paren-trail {
opacity: 0.4;
}
.CodeMirror {
box-sizing: border-box;
resize: both;
border: 1px solid #aaa;
padding: 1px;
padding-bottom: 1em;
margin-bottom: 2px;
}
.CodeMirror, .CodeMirror * {
font-family: "Source Code Pro", monospace;
font-size: 0.8rem;
}
.CodeMirror-matchingbracket {
color: orange !important;
font-weight: bold;
background-color: lightgray; ;
}
#output {
font-family: "Source Code Pro", monospace;
padding: 0.5em;
padding-bottom: 1em;
color: white;
background-color: #120754;
font-size: small;
overflow-y: scroll;
min-height: 10em;
border-style: inset;
border-width: 1px;
border-radius: 5px;
border-color: lightblue;
resize: both;
}
.page-source {
border-style: solid;
border-width: 1px;
padding: 0.5em;
margin-bottom: 0.5em;
}
.pointer {
cursor: pointer;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.js" type="application/javascript"></script>
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.reagent.js" type="application/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.re-frame.js"></script>
<script src="https://cdn.jsdelivr.net/npm/scittle@0.6.15/dist/scittle.pprint.js" type="application/javascript"></script>
<script type="application/x-scittle">
(require '[cljs.pprint :as pprint]
'[clojure.string :as string]
'[reagent.core :as r]
'[reagent.dom :as rdom]
'[sci.core :as sci])
(def preloaded-code
"(defn answer []
;; Better not obfuscate like this
(->> js/Math.PI int (nth (iterate #(* % (inc %)) 1))))
(defn the-answer []
[:div {:style {:font-family \"Georgia\"}}
[:p \"The answer turns out to 🐝 ... \" (answer)]])
(render-with-reagent the-answer)
(load-from-url \"https://raw.githubusercontent.com/weavejester/medley/1.5.0/src/medley/core.cljc\") ; master doesn't work (reader conditionals)
(pr (medley.core/index-by :id [{:id 1, :value :a} {:id 2, :value :b}]))
(answer)
")
;; end of preloaded-code
(def page-source (r/atom nil))
(def reagent-component (r/atom nil))
(def output (r/atom nil))
(defn print-to-output [s]
(swap! output str s "\n"))
;; Originally went with just `binding` `*print-fn*` and `*print-err-fn*`, but
;; that failed to be sufficient for functions invoked (again) from Reagent.
(alter-var-root (var *print-fn*)
(constantly print-to-output))
(alter-var-root (var *print-err-fn*)
(constantly print-to-output))
(defn load-page-source []
(-> (js/fetch js/window.location.href)
(.then #(.text %))
(.then #(reset! page-source %))))
(defn toggle-page-source []
(if @page-source
(reset! page-source nil)
(load-page-source)))
(def code-mirror
(atom nil))
(defn editor-contents []
(when-let [cm @code-mirror]
(.getValue cm)))
(defn history []
(when-let [cm @code-mirror]
(.getHistory (.getDoc cm))))
(defn copy-to-clipboard [s]
(let [temp-textarea (js/document.createElement "textarea")]
(.appendChild js/document.body temp-textarea)
(set! (.-value temp-textarea) s)
(.select temp-textarea)
(js/document.execCommand "copy")
(.removeChild js/document.body temp-textarea)
nil))
(defn encode [code]
;; Unfortunately the encoded URL takes quite a bit more bytes than
;; the code itself. I considered using Compression Streams API to
;; decrease URL size, but it seems relatively new and I'm not too keen
;; on dealing with the asynchronity.
(-> code
js/encodeURIComponent
js/unescape
js/btoa))
(defn decode [coded]
(-> coded
js/atob
js/escape
js/decodeURIComponent))
(defn location->url []
(js/URL. js/window.location.href))
(def code-url-parameter
"code")
(def checksum-url-parameter
"checksum")
(defn code-checksum-id [code]
(-> code hash js/btoa))
(defn share []
(let [code (editor-contents)
coded (encode code)
url (location->url)]
(.set (.-searchParams url)
code-url-parameter
coded)
(.set (.-searchParams url)
checksum-url-parameter
(code-checksum-id code))
(println "Sharing as" (str url))
(copy-to-clipboard (str url))
(js/alert "URL with code copied to clipboard.")))
(defn code-queryparam-value []
(.get (.-searchParams (location->url))
code-url-parameter))
(defn checksum-queryparam-value []
(.get (.-searchParams (location->url))
checksum-url-parameter))
(defn url-embedded-code []
(when-let [coded (code-queryparam-value)]
(let [code (decode coded)
checksum (checksum-queryparam-value)]
(if (or (string/blank? checksum)
(not= checksum (code-checksum-id code)))
(do
(js/alert "Unfortunately, the opened URL is incomplete.\nThe embedded code fragment will be ignored.\nYou might want to try that again!")
(.replace js/window.location (.-pathname (location->url)))
nil)
code))))
(def default-local-store-code-key
"buffer-1")
(def local-store-code-key
(atom default-local-store-code-key))
(defn local-store-history-key []
(str @local-store-code-key ".history"))
(defn local-storage []
(.-localStorage js/window))
(defn stored-code []
(.getItem (local-storage) @local-store-code-key))
(defn store-code [code]
(.setItem (local-storage)
@local-store-code-key
code))
(defn stored-history []
(js/JSON.parse (.getItem (local-storage)
(local-store-history-key))))
(defn store-history [history]
(.setItem (local-storage)
(local-store-history-key)
(js/JSON.stringify history)))
(def store-history-timeout-id
(atom nil))
(defn planned-store-history []
(when @store-history-timeout-id
(js/clearTimeout @store-history-timeout-id)
(reset! store-history-timeout-id nil))
(-> (history)
store-history))
(defn plan-store-history []
(when @store-history-timeout-id
(js/clearTimeout @store-history-timeout-id)
(reset! store-history-timeout-id nil))
(reset! store-history-timeout-id
(js/setTimeout planned-store-history 400)))
(defn code-input-changed [_event]
(-> (editor-contents) store-code)
(plan-store-history))
(defn determine-initial-code []
(if-let [url-embedded (url-embedded-code)]
(do
(reset! local-store-code-key
(str "buffer-" (code-checksum-id url-embedded)))
(let [locally-stored (stored-code)
keep-local?
(and locally-stored
(or (= locally-stored url-embedded)
(js/confirm "Keep previous changes for this URL?")))]
(if keep-local?
locally-stored
(do
(store-history "")
(store-code url-embedded)
url-embedded))))
(or (stored-code)
preloaded-code)))
(defn initialize-code-mirror []
(reset! code-mirror
(.fromTextArea js/CodeMirror
(.getElementById js/document "code-input")
#js {"mode" "clojure"
"lineNumbers" true
"matchBrackets" true}))
(.init js/parinferCodeMirror @code-mirror "smart" {})
(.on @code-mirror
"change"
(fn [_ change] (code-input-changed change)))
(.setValue @code-mirror
(determine-initial-code))
(when-let [history (stored-history)]
(.setHistory (.getDoc @code-mirror) history)))
(defn undo []
(.execCommand @code-mirror "undo"))
(defn redo []
(.execCommand @code-mirror "redo"))
(defn clear-code []
(when (js/confirm "Really clear code buffer?")
(.setValue @code-mirror "")
(store-code "")))
(defn -clear-output! []
(reset! output "")
(reset! reagent-component nil))
(defn scroll-output-into-focus! []
(let [dom-node (.getElementById js/document "output")]
(.scrollIntoView dom-node {"block" "end", "behavior" "smooth"})))
;; available to user (renders within div)
(defn render-with-reagent [component]
(reset! reagent-component component))
(defonce external-sources (atom {}))
(declare load-code)
(defn load-from-url [url]
"Experimental; necessarily asynchronous, so fetched code only becomes
available on reload, which is forced as soon as code is loaded (so, any code
before this invocation might be evaluated more than once).
E.g. (load-from-url \"https://raw.githubusercontent.com/weavejester/medley/master/src/medley/core.cljc\")"
(if-let [source (get @external-sources url)]
(load-string source)
(do
(println "Loading" url "...")
(-> (js/fetch url)
(.then #(.text %))
(.then (fn [source]
(swap! external-sources assoc url source)
(load-string source)
(println "Loaded" url)
(load-code)))) ; a bit crude; let's see
(throw (ex-info "loading" {:loading-url url})))))
(defn load-code []
(let [c (editor-contents)]
(-clear-output!)
(js/setTimeout
(fn []
(try
(let [value (load-string c)]
(print-to-output (pr-str value)))
(catch ^:sci/error js/Error e
(when-not (contains? (ex-data e) :loading-url)
(println "Error:" (.-message e))
(run! println (-> (sci/stacktrace e) (sci/format-stacktrace))))))
(js/setTimeout scroll-output-into-focus! 100))
200)))
(defn render-output []
(when-not (nil? @output)
[:div {:style {:margin-top "1em"}}
[:h3 "Output"]
[:div {:id "output"}
[:pre {:id "output-text"} @output]]
[:button
{:style {:margin "1px"}
:on-click #(do (copy-to-clipboard @output)
(js/alert "Output copied to clipboard."))}
"Copy to clipboard"]]))
(defn render-reagent-component []
(when-let [component @reagent-component]
[:div {:style {:margin-top "1em"
:margin-bottom "2em"}}
[:h3 "Render"]
[:div
(if (vector? component)
component
[component])]]))
(defn github-link []
[:a {:class "github-button"
:href "/~https://github.com/jurjanpaul/ape-cljs-playground"
:data-icon="octicon-repo"}
""])
(defn horizontal-separator []
[:span
{:style {:margin-left "0.2em"
:margin-right "0.2em"
:color "grey"}}
"|"])
(defn editor []
[:div
[:div
{:style {:display "flex"}}
[:div
[:h3
"🦧 ape-cljs-playground "]]
[:div
{:style {:display "flex"
:position "absolute"
:right "0px"
:top "0px"
:margin-top "0.5em"}}
[:button
{:style {:margin-left "4px"
:margin-right "4px"
:margin-bottom "0.5em"}
:on-click toggle-page-source}
"source with docs " (if @page-source "▽" "▷")]
[:span {:style {:padding-top "1px"
:margin-right "4px"}}
[github-link]]]]
[:p
{:style {:font-size "0.9em"}}
[:span [:i "Away from Preferred Editor"] " ClojureScript Playground"]]
(when @page-source
[:div
{:style {:font-family "Source Code Pro, monospace"
:font-size "0.6rem"
:margin-bottom "1em"}}
[:pre
{:style {:padding "0.5em"
:min-width "40em"
:overflow "auto"
:border-width "1px"
:border-style "solid"
:border-color "green"
:color "green"}}
@page-source]])
[:textarea
{:id "code-input"
:cols 120
:rows 20
:onChange code-input-changed}
(or (.getItem (.-localStorage js/window) "code")
preloaded-code)]
[:div
[:button
{:style {:margin "1px"}
:on-click load-code}
"Load"]
[horizontal-separator]
[:button
{:style {:margin "0 1px 0 1px"
:padding "0 4px 0 4px"
:font-size "1.2em"
:font-weight "bold"
:transform "translate(0,2px)"}
:on-click undo}
"⟲"]
[:button
{:style {:margin "0 1px 0 1px"
:padding "0 4px 0 4px"
:font-size "1.2em"
:font-weight "bold"
:transform "translate(0,2px)"}
:on-click redo}
"⟳"]
[horizontal-separator]
[:button
{:style {:margin "1px"}
:on-click #(do (copy-to-clipboard (editor-contents))
(js/alert "Code copied to clipboard."))}
"Copy"]
[:button
{:style {:margin "1px"}
:on-click share}
"Share"]
[:button
{:style {:margin "1px"}
:on-click clear-code}
"Clear"]
(when-not (string/blank? (.-search (location->url)))
[:<>
[horizontal-separator]
[:span
{:style {:font-size "0.8em"}}
[:a
{:href (.-pathname (location->url))}
"main buffer >"]]])]
[render-output]
[render-reagent-component]])
(rdom/render [editor] (.getElementById js/document "editor"))
(initialize-code-mirror)
</script>
</head>
<body>
<div id="editor"></div>
<script src="https://cdn.jsdelivr.net/npm/codemirror@5.65.6/lib/codemirror.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/codemirror@5.65.6/addon/edit/matchbrackets.js"></script>
<script src="https://cdn.jsdelivr.net/npm/codemirror@5.65.6/mode/clojure/clojure.js"></script>
<script src="https://cdn.jsdelivr.net/npm/parinfer@3.12.0/parinfer.min.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/parinfer-codemirror@1.4.2/parinfer-codemirror.min.js"></script> -->
<script src="lib/parinfer-codemirror.js" type="application/javascript"></script> <!-- tweaked version w.r.t. scrolling -->
<script async defer src="https://buttons.github.io/buttons.js"></script>
</body>
</html>