-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha-html-file-is-all-you-need.html
More file actions
1035 lines (828 loc) · 30 KB
/
Copy patha-html-file-is-all-you-need.html
File metadata and controls
1035 lines (828 loc) · 30 KB
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="img/cursor-dino.png">
<meta charset="UTF-8">
<meta name="description" content="Can we build a reactive notebook in a single HTML file? Yes (by standing on the shoulders of Observable)">
<meta property="og:description" content="Can we build a reactive notebook in a single HTML file? Yes (by standing on the shoulders of Observable)">
<meta name="twitter:description" content="Can we build a reactive notebook in a single HTML file? Yes (by standing on the shoulders of Observable)">
<meta name="author" content="Max Bo">
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "https://maxbo.me/a-html-file-is-all-you-need"
},
"headline": "Reactive HTML notebooks",
"image": "https://maxbo.me/img/document.webp",
"datePublished": "2024-05-06T00:00:00Z",
"dateModified": "2024-08-21T00:00:00Z",
"author": {
"@type": "Person",
"name": "Max Bo",
"url": "https://maxbo.me"
},
"publisher": {
"@type": "Organization",
"name": "Max Bo",
"logo": {
"@type": "ImageObject",
"url": "https://maxbo.me/kirby.png"
}
},
"description": "Can we build a reactive notebook in a single HTML file? Yes (by standing on the shoulders of Observable)"
}
</script>
<!-- OG meta tags -->
<meta property="og:title" content="Reactive HTML notebooks">
<meta property="og:image" content="https://maxbo.me/img/document.webp">
<meta property="og:url" content="https://maxbo.me/a-html-file-is-all-you-need">
<meta property="og:type" content="article">
<meta property="og:site_name" content="Max Bo">
<meta property="og:locale" content="en_GB">
<meta property="article:published_time" content="2024-05-06T00:00:00Z">
<meta property="article:modified_time" content="2024-08-21T00:00:00Z">
<meta property="article:author" content="Max Bo">
<meta property="article:section" content="Technology">
<meta property="article:tag" content="HTML">
<meta property="article:tag" content="Observable">
<!-- Twitter meta tags -->
<meta name="twitter:site" content="maxbo.me">
<meta name="twitter:creator" content="@_max_bo_">
<meta name="twitter:title" content="Reactive HTML notebooks">
<!-- <meta name="twitter:image" content="https://maxbo.me/img/document.png"> -->
<meta name="twitter:url" content="https://maxbo.me/a-html-file-is-all-you-need">
<title>Reactive HTML notebooks ⋅ Max Bo</title>
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Playfair+Display+SC:wght@400;700&display=swap" as="style">
<style>
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display+SC:wght@400;700&display=swap');
html {
cursor: url('img/cursor-dino.png'), auto;
}
body {
background-color: #e4e4e4;
font-family: Georgia, 'Times New Roman', Times, serif;
font-smooth: never;
-webkit-font-smoothing: none;
text-rendering: optimizeSpeed;
}
main {
max-width: min(90vw, 80ch);
margin: 2em auto;
padding-bottom: 2em;
}
section {
padding-top: 2rem;
}
marquee {
border: 3px ridge;
}
button {
border: 2px outset;
}
button:active {
border: 2px inset
}
h1, h2 {
font-family: 'Playfair Display SC', Georgia, 'Times New Roman', Times, serif;
}
h1 {
font-size: 2.5rem;
}
h2 {
font-style: italic;
font-size: 2rem;
padding-bottom: .5rem;
}
h3 {
font-size: 1.1rem;
}
a {
text-decoration: underline;
text-decoration-thickness: 1px;
text-underline-offset: 0.2em;
}
img {
image-rendering: pixelated;
}
img.badge {
display: inline-block;
}
.time {
padding-bottom: 1em;
font-size: 0.9rem;
font-style: italic;
}
code {
border: 1px solid #CCC;
background-color: #EEE;
padding: .125rem .25rem;
}
kbd {
background-color: #EEE;
border-radius: 3px;
border: 1px solid #b4b4b4;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
0 2px 0 0 rgba(255, 255, 255, 0.7) inset;
color: #333;
display: inline-block;
font-size: 0.85em;
font-weight: 700;
line-height: 1;
padding: 2px 4px;
white-space: nowrap;
}
.center-contents {
display: flex;
align-items: center;
justify-content: center;
}
aside {
width: 40%;
padding-left: 0.5rem;
margin-left: 0.5rem;
float: right;
margin-left: 5px;
border-left: darkslategray 1px solid;
color: darkslategray;
}
aside > p {
margin: 0.5rem;
}
/*
Josh's Custom CSS Reset
https://www.joshwcomeau.com/css/custom-css-reset/
*/
*, *::before, *::after {
box-sizing: border-box;
}
* {
margin: 0;
}
html, body {
height: 100%;
}
body {
-webkit-font-smoothing: antialiased;
}
img, picture, video, canvas, svg {
display: block;
max-width: 100%;
}
input, button, textarea, select {
font: inherit;
}
#root, #__next {
isolation: isolate;
}
</style>
</head>
<body>
<div style="background-color: black; color: white; text-align: center; padding: 1rem; font-family: monospace; font-size: 1.1em">
I've packaged this article up and released a library, <a href="https://maxbo.me/celine" style="color: white;">@celine/celine</a>. It has a nicer API too. Check it out! (o˘◡˘o)
</div>
<main>
<div class="slide">
<header style="padding-bottom: 1rem">
<nav>
<h2>
<marquee>
<a href="index.html">← Max Bo</a>
</marquee>
</h2>
</nav>
Published <time datetime="2024-05-06">May 6, 2024</time>
<br />
Modified <time datetime="2024-05-06">September 9, 2024</time>
<br />
<a href="https://news.ycombinator.com/item?id=42170740">Hacker News discussion</a>
<br />
<a href="https://www.youtube.com/watch?v=oMUt0PnKuyc">SydJS talk</a>
<h1 style="margin-bottom: 1rem">Reactive HTML notebooks</h1>
</header>
</div>
<div class="slide">
Before I start, why am I doing this?
<br />
<br />
<b>I don't think HTML is being used enough as a platform for scientific publishing.</b>
<br />
<br />
Instead, people will:
<ol>
<li>Use an interactive notebook like <a href="https://jupyter.org/">Jupyter</a>, <a href="https://rmarkdown.rstudio.com/lesson-10.html">RStudio</a>, <a href="https://plutojl.org/">Pluto.jl</a> or <a href="https://observablehq.com/">Observable</a> to do data exploration, analysis and visualisation,</li>
<li>Move to a publishing platform like <a href="https://typst.app/">Typst</a>, <a href="https://overleaf.com">Overleaf</a>, pure <a href="https://www.latex-project.org/">LaTeX</a>, or a <a href="https://en.wikipedia.org/wiki/WYSIWYG">WYSIWYG</a> editor to typeset their work,</li>
<li>Export to <code>.pdf</code> for distribution.</li>
</ol>
<br />
I think a HTML file can be used for all 3 of these stages, and prevent a lot of faffing around with manual processes, CLI tooling, CI steps and 3rd-party platforms.
<br />
<br />
HTML's typesetting capabilities are well documented, but its capabilities as a platform for data exploration, analysis and visualisation are not.
<br />
<aside>
<p>
This article takes heavy inspiration from Anton Zhiyanov's <a href="https://antonz.org/in-browser-code-playgrounds/"><cite>In-browser code playgrounds</cite></a>, Cristóbal Sciutto</a>'s <a href="https://cristobal.space/note"><cite>Self-modifying HTML notes</cite></a>, <a href="https://quarto.org/">Quarto</a>, and <a href="https://observablehq.com/framework/">Observable Framework</a>
</p>
</aside>
<br />
I'll try and demonstrate these capabilities, literate programming style.
<br />
<div class="center-contents">
<img src="img/document.webp" alt="A computer displays an open book" style="max-width: 125px; margin: 1rem" />
</div>
</div>
<div class="slide">
<h2>Cells</h2>
First, we'll steal a trick from <a href="https://secretgeek.github.io/html_wysiwyg/html.html"><cite>This page is a truly naked, brutalist html quine</cite></a>, and create a CSS class called <code>echo</code> that will display/reflect <code>style</code> and <code>script</code> elements inline.
<br />
<br />
Add in a <a href="https://blog.glyphdrawing.club/font-with-built-in-syntax-highlighting/">font with built-in syntax highlighting</a> and a <code>contenteditable</code> attribute and we have a basic code editor!
<br />
<br />
I stress that <b>this <code>style</code> element is styling itself to be visible.</b>
<br />
<br />
<i>Try changing <code>.echo</code>'s <code>background-color</code>!</i>
<br />
<style class="echo" contenteditable="true">
@font-face {
font-family: 'FontWithASyntaxHighlighter';
src:
url('fonts/FontWithASyntaxHighlighter-Regular.woff2')
format('woff2')
;
}
.echo {
display: block;
margin-bottom: 1rem;
margin-top: 0.2rem;
padding: 0.5rem 1rem 1rem 1rem;
overflow: auto;
font-family: "FontWithASyntaxHighlighter", monospace;
white-space: pre;
font-feature-settings: "colr", "calt";
font-size: 0.9rem;
color: ivory;
background-color: rgb(49, 49, 49); /* change me! */
}
script.echo::before {
content: "<script id=\"" attr(id) "\" type=\"" attr(type) "\" class=\"" attr(class) "\" contenteditable=\"" attr(contenteditable) "\">";
}
script.echo::after {
content: "<\/script>";
}
style.echo::before {
content: "<style class=\"" attr(class) "\" contenteditable=\"" attr(contenteditable) "\">";
}
style.echo::after {
content: "<\/style>";
}
[contenteditable] {
border: 3px inset;
}
</style>
</div>
<div class="slide">
We also want <code>contenteditable</code> <code>script</code>s to be re-evaluated on blur by building a clone of the <code>script</code> and then removing the original.
<br />
(Why can't we just use <code>eval</code>? For one, <code>eval</code> doesn't work with code with <code>import</code> statements in it.)
<br />
<script type="module" class="echo">
function reevaluate(event) {
const old = event.target;
const neww = document.createElement('script');
neww.textContent = old.textContent;
for (let i = 0; i < old.attributes.length; i++) {
neww.setAttribute(old.attributes[i].name, old.attributes[i].value || '');
}
// register the blur listener again (given we've made a new script element)
neww.addEventListener('blur', reevaluate);
old.parentNode.insertBefore(neww, old);
old.parentNode.removeChild(old);
}
// we want to redeclare scripts onblur
document.querySelectorAll('script.echo').forEach((script) => {
script.addEventListener('blur', reevaluate);
});
</script>
</div>
<div class="slide">
Now we'll import the <a href="https://github.com/observablehq/stdlib">Observable standard library</a> and the <a href="https://github.com/observablehq/runtime">Observable runtime</a>, and bind them to <code>window</code>.
We'll export only 2 symbols to <code>window</code>, <code>library</code> and <code>cell</code>.
<script type="module" class="echo">
import * as stdlib from 'https://esm.run/@observablehq/stdlib@5.8.8'
import { Runtime, Inspector } from "https://esm.run/@observablehq/runtime@5.9.9";
const library = new stdlib.Library();
const runtime = new Runtime();
const module = runtime.module();
function cell(name, inputs, definition, observerVisibility = "visible") {
// should we show the variable state above the cell?
const observer = observerVisibility === "visible" ? makeInspector(name) : undefined;
// if the variable already is in scope, get it, otherwise create a fresh one.
// (this is why re-evaluated contenteditable propogate new definitions)
const variable = module._scope.get(name) || module.variable(observer);
variable.define(name, inputs, definition);
}
// use the Observable inspector to display the cell's output above the script block
function makeInspector(name) {
const div = document.createElement("div");
// can't use document.currentScript as it's null in module scripts
const currentScript = document.getElementById(name);
currentScript.parentNode.insertBefore(div, currentScript);
return new Inspector(div);
}
window.library = library;
window.cell = cell;
</script>
</div>
<div class="slide">
Now we'll declare a cell called <code>counter</code> that emits a number every second.
<b>The <code>script</code>'s <code>id</code> attribute is the same as the <code>name</code> parameter passed to <code>cell</code></b>.
<br />
<br />
<i>Try changing the initial counter value <code>i</code> above to a much bigger number, and then defocus the <code>script</code>.</i>
<script type="module" class="echo" id="counter" contenteditable="true">
cell("counter", [], async function* () {
let i = 0;
while (true) {
await library.Promises.delay(1000);
yield i++;
}
});
</script>
</div>
<div class="slide">
Now that we've created a our <code>counter</code> cell, we can create other cells that depend on it.
<br />
We'll import <a href="https://observablehq.com/@observablehq/htl">Hypertext Literal</a> and use it to format the
<code>counter</code> value. <code>htl</code> implements a full-blown HTML5 parser that performs automatic escaping and
interpolation of non-serializable values, such as event listeners, style objects, and other DOM nodes.
<script type="module" class="echo" id="fizzbuzz" contenteditable="true">
import * as htl from 'https://esm.run/htl@0.3.1';
window.htl = htl;
cell("fizzbuzz", ["counter"], (counter) => {
if (counter % 3 === 0 && counter % 5 === 0) {
return htl.html`<b style="color: purple">FizzBuzz</b>`;
} else if (counter % 3 === 0) {
return htl.html`<b style="color: red">Fizz</b>`;
} else if (counter % 5 === 0) {
return htl.html`<b style="color: blue">Buzz</b>`;
} else {
return htl.html`<b>${counter}</b>`;
}
});
</script>
</div>
<div class="slide">
We can still observe the output of a cell without needing to show its definition. Just don't add the <code>echo</code> class.
This makes them useful as a rendering primitive.
<script type="module" id="hidden">
import * as htl from 'https://esm.run/htl@0.3.1';
window.htl = htl;
cell("hidden", ["counter"], (counter) => {
return htl.html`<p>${counter}</p>`;
});
</script>
<i>(There's a hidden cell above ^)</i>
</div>
<br />
<br />
<div class="slide">
Alternatively, we can create a cell type that doesn't display its output at all.
<br />
We can use these cells to store intermediate values or datastructures.
<script type="module" class="echo">
function silent(name, inputs, definition) {
cell(name, inputs, definition, "hidden");
}
window.silent = silent;
</script>
Also note that cells can be declared out of order.
<script type="module" id="reallyNegative" class="echo">
cell("reallyNegative", ["negative"], (n) => {
return n * 10
});
</script>
<script type="module" id="negative" class="echo" contenteditable="true">
silent("negative", ["counter"], (n) => {
return -n;
});
</script>
</div>
<br />
<div class="slide">
We can use cell values in more complex outputs. We'll import <a href="https://observablehq.com/plot/what-is-plot">Observable Plot</a> and use the <code>counter</code> value in a plot.
<script type="module" class="echo" id="plot" contenteditable="true">
import * as Plot from 'https://esm.run/@observablehq/plot@0.6.16';
window.Plot = Plot;
const numbers = [
170.16, 172.53, 172.54, 173.44, 174.35, 174.55, 173.16, 174.59, 176.18, 177.90,
176.15, 179.37, 178.61, 177.30, 177.30, 177.25, 174.51, 172.00, 170.16, 165.53,
166.87, 167.17, 166.00, 159.10, 154.83, 163.09, 160.29, 157.07, 158.50, 161.95,
163.04, 169.79, 172.36, 172.05, 172.83, 171.80, 173.67, 176.35, 179.10, 179.26
];
cell("plot", ["counter"], (counter) => {
return Plot.plot({
marks: [
Plot.lineY(numbers, { x: (d, i) => i, y: d => d }),
Plot.ruleX([counter % 40])
]
});
});
</script>
</div>
<div class="center-contents">
<img src="img/up.png" alt="A computer displays a graph in the upward direction" style="max-width: 125px" />
</div>
<div class="slide">
<h2>TeX, Markdown, Graphviz</h2>
We can return any type of DOM element from a cell.
<br />
In this case, the <code>tex</code>, <code>md</code>, and <code>dot</code> cells return <code>span</code>, <code>table</code> and <code>svg</code> elements respectively.
<br />
<br />
<i>Try editing any of the following cells.</i>
<br />
<script type="module" class="echo" id="tex" contenteditable="true">
cell("tex", [], async () => {
const tex = await library.tex()
return tex`
\def\f#1#2{#1f(#2)}
\f\relax{x} = \int_{-\infty}^\infty
\f\hat\xi\,e^{2 \pi i \xi x}
\,d\xi`
});
</script>
</div>
<div class="slide">
<script type="module" class="echo" id="markdown" contenteditable="true">
cell("markdown", [], async () => {
const elements = [
{ "symbol": "Co", "name": "Cobalt", "number": 27 },
{ "symbol": "Cu", "name": "Copper", "number": 29 },
{ "symbol": "Sn", "name": "Tin", "number": 50 },
{ "symbol": "Pb", "name": "Lead", "number": 82 }
];
const md = await library.md();
return md`
| Name | Symbol | Atomic number |
|-----------|-------------|---------------|${elements.map(e => `
| ${e.name} | ${e.symbol} | ${e.number} |`)}
`;
});
</script>
</div>
<div class="slide">
<script type="module" class="echo" id="dot" contenteditable="true">
cell("dot", [], async () => {
const dot = await library.dot();
return dot`
digraph G {
rankdir = LR
a -> b -> c
}`;
});
</script>
</div>
<!-- <div class="slide">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.13.18/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/wypst@0.0.8/dist/wypst.min.js" crossorigin="anonymous"></script>
<script type="module" class="echo" id="typst" contenteditable="true">
cell("typst", [], async () => {
const div = document.createElement("div");
await wypst.initialize()
wypst.render("sum_(k=1)^n k = (n(n+1)) / 2", div);
return div
});
</script> -->
<div class="center-contents">
<img src="img/data.webp" alt="A computer with an open CD tray is surrounded by data" style="max-width: 125px; margin: 1rem" />
</div>
<div class="slide">
<h2>Cell status</h2>
We can also return a <code>Promise</code>, or throw an <code>Error</code>, from a cell.
Observable's <code>Inspector</code> will apply an <code>observablehq--running</code> or
<code>observablehq--error</code> class to the cell's outer <code>div</code> element respectively.
We'll style them appropriately:
<style class="echo">
@keyframes blink {
67% {
opacity: 0;
}
}
.observablehq {
margin-top: 1rem;
}
.observablehq--running::before {
content: 'LOADING';
animation: blink 1s step-end infinite;
}
.observablehq--error {
color: #d00;
}
</style>
</div>
<div class="slide">
<script type="module" class="echo" id="running">
cell("running", [], () => {
// this cell will run forever
return new Promise(() => { });
});
</script>
<script type="module" class="echo" id="error">
cell("error", [], () => {
throw new Error("This cell has thrown an error");
});
</script>
</div>
<div class="slide">
<h2>SQLite</h2>
I've hosted the <a href="https://github.com/lerocha/chinook-database">Chinook sample database</a> on my website at <a href="https://maxbo.me/chinook.db">https://maxbo.me/chinook.db</a>.
Now we'll use a <a href="https://observablehq.com/framework/lib/sqlite">WASM-backed SQLite client</a> to query it.
<br />
<br />
<i>Try adding <code>WHERE Milliseconds < 1000000</code> to the SQL query!</i>
<script type="module" class="echo" id="sqlite" contenteditable="true">
cell("sqlite", [], async () => {
const url = "https://maxbo.me/chinook.db";
const db = await library.SQLiteDatabaseClient().open(url);
const tracks = await db.query("SELECT * FROM tracks");
return Plot.plot({
title: htl.html`<h3>Track length distribution</h3>`,
marks: [
Plot.rectY(
tracks,
Plot.binX({ y: "count" }, { x: "Milliseconds", tip: true })
),
Plot.ruleY([0])
]
});
});
</script>
</div>
<div class="slide">
<h2>Python</h2>
The <a href="http://pyodide.org/">Pyodide</a> CPython WASM distribution includes <a href="https://numpy.org/">NumPy</a>, <a href="https://pandas.pydata.org/">Pandas</a>, <a href="https://matplotlib.org/">Matplotlib</a>, <a href="https://scikit-learn.org/">scikit-learn</a>, and <a href="https://scipy.org/">Scipy</a>.
We'll rebuild the plot seen above, but using Matplotlib and Python's <code>sqlite3</code> module instead.
<br />
<br />
<i>Try editing one of the plot labels!</i>
<script type="module" class="echo" id="python" contenteditable="true">
import { loadPyodide } from 'https://cdn.jsdelivr.net/pyodide/v0.25.1/full/pyodide.mjs'
cell("python", [], async () => {
const pyodide = await loadPyodide();
const response = await fetch('https://maxbo.me/chinook.db');
pyodide.FS.writeFile('/chinook.db', new Uint8Array(await response.arrayBuffer()));
await pyodide.loadPackage(['sqlite3', 'matplotlib', 'pandas']);
const code = `
import sqlite3
import pandas as pd
import matplotlib.pyplot as plt
with sqlite3.connect("/chinook.db") as conn:
tracks_df = pd.read_sql_query("SELECT * FROM tracks", conn)
plt.title('Track length distribution')
plt.hist(tracks_df['Milliseconds'], bins='auto')
plt.xlabel('Milliseconds')
plt.ylabel('Frequency')
import io, base64
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
'data:image/png;base64,' + base64.b64encode(buf.read()).decode()
`;
const imageDataUrl = await pyodide.runPythonAsync(code);
const imageElement = document.createElement('img');
imageElement.src = imageDataUrl;
return imageElement;
});
</script>
</div>
<div class="slide">
<h2>R</h2>
You know the drill. It's R, using <a href="https://docs.r-wasm.org/webr/latest/">WebR</a>.
I didn't figure out how to get <a href="https://ggplot2.tidyverse.org/">ggplot2</a> <a href="https://docs.r-wasm.org/webr/latest/plotting.html">rendering</a> working, but I assume it's possible.
<i>I must disclose that this cell seems to be a bit flaky on iOS. I have not had a chance to investigate further, nor will I.</i>
<script type="module" class="echo" id="r" contenteditable="true">
import { WebR } from 'https://webr.r-wasm.org/latest/webr.mjs';
cell("r", [], async () => {
const webR = new WebR();
await webR.init();
const response = await fetch('https://maxbo.me/chinook.db');
webR.FS.writeFile('/chinook.db', new Uint8Array(await response.arrayBuffer()));
await webR.installPackages(['RSQLite'])
const shelter = await new webR.Shelter();
const code = `
library(RSQLite)
conn <- dbConnect(SQLite(), "/chinook.db")
track_data <- dbGetQuery(conn, "SELECT Milliseconds FROM tracks")
dbDisconnect(conn)
hist(track_data$Milliseconds,
breaks = 50,
main = "Track length distribution",
xlab = "Duration (Milliseconds)")`;
const output = document.createElement('div');
const capture = await shelter.captureR(code);
capture.images.forEach((img) => {
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
output.appendChild(canvas);
});
shelter.purge();
return output;
});
</script>
</div>
<div class="slide">
<h2>Inputs</h2>
We'll create a new cell type <code>viewof</code> that works specifically with <a href="https://github.com/observablehq/inputs">Observable Inputs</a>.
It declares 2 reactive cells: <code>NAME</code> and <code>viewof NAME</code> - one for the value, and one for the DOM element itself.
<script type="module" class="echo">
import * as Inputs from 'https://esm.run/@observablehq/inputs@0.12.0'
window.Inputs = Inputs
function viewof(name, inputs, definition) {
cell(`viewof ${name}`, inputs, definition);
cell(name, [`viewof ${name}`], (inpt) => library.Generators.input(inpt), "hidden");
}
window.viewof = viewof;
</script>
</div>
<div class="slide">
To display the input above the cell, we set the cell <code>id</code> to <code>viewof NAME</code>.
<br />
<br />
<i>Wiggle the range input and see another dependent cell update.</i>
<div id="range"></div>
<script type="module" class="echo" id="viewof range" contenteditable="true">
viewof("range", [], () => {
return Inputs.range([0, 100], { step: 1 });
});
</script>
<script type="module" class="echo" id="rangePlot" contenteditable="true">
cell("rangePlot", ["range"], (range) => {
return Plot.tickX([range]).plot({ x: { domain: [0, 100] } });
});
</script>
<i>NB: The way Observable Inputs work is a bit arcane. This demo of <a href="https://observablehq.com/@observablehq/synchronized-inputs">Synchronized Inputs</a> may shed some light.</i>
</div>
<div class="slide">
<h2>Mutability</h2>
Purely functional dataflow is great, but sometimes you just need to mutate state.
We'll create a new helper function <code>mutable</code>. It registers a <code>Mutable</code> - an object that yields new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator"><code>Generator</code></a> values when the value is mutated - in the runtime.
<script type="module" class="echo" id="mutable">
/** Hijacked from https://github.com/observablehq/stdlib/blob/main/src/mutable.js */
function Mutable(value) {
let change;
return Object.defineProperty(
library.Generators.observe((_) => {
change = _;
if (value !== undefined) change(value);
}),
"value",
{
get: () => value,
set: (x) => void change((value = x))
}
);
}
function mutable(name, value) {
const m = Mutable(value);
cell(name, [], m);
return m;
}
window.mutable = mutable;
</script>
</div>
<div class="slide">
<i>Try editing the initial state of the <code>mutable</code>.</i>
<script type="module" class="echo" id="ref" contenteditable="true">
window.ref = mutable("ref", 3)
</script>
<i>Try editing the button labels.</i>
<script type="module" class="echo" id="viewof increment" contenteditable="true">
viewof("increment", [], () => {
const increment = () => ++ref.value;
const reset = () => ref.value = 0;
return Inputs.button([["Increment", increment], ["Reset", reset]]);
});
</script>
<script type="module" class="echo" id="sword" contenteditable="true">
cell("sword", ["ref"], (ref) => {
return htl.html`↜(╰ •ω•)╯ |${'═'.repeat(ref)}═ﺤ`
});
</script>
</div>
<!-- <h2>3D models</h2>
We can use Google's <a href="https://modelviewer.dev/"><code><model-viewer></code></a> <a href="https://www.webcomponents.org/introduction">Web Component</a> to display 3D models.
<script type="module" class="echo" id="model">
import 'https://ajax.googleapis.com/ajax/libs/model-viewer/3.5.0/model-viewer.min.js';
cell("model", async () => {
return htl.html`
<model-viewer
style="width: 100%; height: 400px"
src="/models/NeilArmstrong.glb"
poster="/models/NeilArmstrong.webp"
alt="Neil Armstrong's Spacesuit from the Smithsonian Digitization Programs Office and National Air and Space Museum"
ar
auto-rotate
shadow-intensity="1"
camera-controls
touch-action="pan-y">
</model-viewer>
`;
});
</script> -->
<!-- <div class="slide"> -->
<!-- <h2>Saving contenteditable changes</h2>
Taking a note out of <a href="https://cristobal.space/">Cristóbal Sciutto</a>'s <a href="https://cristobal.space/note">Self-modifying HTML notes</a>,
it's very easy to save a modified version of our document to disk. -->
<!-- <script type="module" class="echo" id="download">
function download (html) {
// Write data into self-contained html file
const data = new Blob([html], {type: 'text/plain'});
// Download the file
const url = window.URL.createObjectURL(data);
const a = document.createElement("a");
a.href = url;
a.download = "a-html-file-is-all-you-need.html";
a.click();
}
cell("download", () => {
return Inputs.button([["Download", () => download(document.documentElement.outerHTML)]]);
});
</script> -->
<!-- </div> -->
<div class="slide">
<h2>What's next?</h2>
<s>I will try and cram all of this into a library with some proper documentation.</s>
<br />
<s>I initially thought it should be called <code>incel</code> (short for <i>inline cell</i>), but I'll probably call it <code>celine</code> instead.</s>
<br />
<br />
I've released a library! It's called <a href="https://maxbo.me/celine">@celine/celine</a>!
<div class="center-contents">
<img src="img/typing.gif" alt="A computer terminal receives text" style="margin: 1rem" />
</div>
</div>
<div class="slide">
<h2>Slide infrastructure</h2>
I demo'd this article at <a href="https://www.youtube.com/@SydJSMeetup">SydJS</a>. This is the code I used to turn the article into a slideshow.
<ul>
<li><kbd>Shift</kbd> + <kbd>N</kbd> - Start slideshow / next slide</li>
<li><kbd>Shift</kbd> + <kbd>B</kbd> - Previous slide</li>
<li><kbd>Shift</kbd> + <kbd>E</kbd> - End slideshow</li>
</ul>
<br />
<style class="echo">
.slide {
scroll-margin-top: 3rem;
}
</style>
<script type="module" class="echo">
let slide = -1;
window.addEventListener('keydown', (event) => {
if (event.shiftKey && event.key === 'N') {
slide++;
paint();
}
if (event.shiftKey && event.key === 'B') {
slide--;
paint();
}
if (event.shiftKey && event.key === 'E') {
slide = -1;