-
Notifications
You must be signed in to change notification settings - Fork 5
/
demo.html
931 lines (856 loc) · 63.8 KB
/
demo.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
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
<!DOCTYPE html>
<html lang="en"><head>
<link rel="icon" href="/logo.svg">
<title>VanJS - Learning by Example</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 400;
src: url(https://fonts.gstatic.com/s/poppins/v20/pxiEyp8kv8JHgFVrJJfedw.ttf) format('truetype');
}
</style>
<link rel="stylesheet" href="/code/w3-v1.css">
<link rel="stylesheet" href="/code/prism-v1.css">
<link rel="stylesheet" href="/vanjs.css">
</head>
<body class="line-numbers" data-prismjs-copy="📋">
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-Q0NB75RY7E"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-Q0NB75RY7E');
</script>
<script type="text/javascript" src="/code/prism-v1.js" defer></script><script type="text/javascript" src="/code/van-1.5.2.nomodule.min.js" defer></script><script type="text/javascript" src="/code/diff.min.js" defer></script><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js" defer></script><script type="text/javascript" src="/code/van-x-0.6.1.nomodule.min.js" defer></script><script type="text/javascript" src="demo.js" defer></script>
<!-- Sidebar/menu -->
<nav class="w3-sidebar w3-red w3-collapse w3-top w3-large w3-padding" style="z-index:3;width:280px;font-weight:bold;" id="mySidebar"><br>
<a href="javascript:void(0)" onclick="w3_close()" class="w3-button w3-hide-large w3-display-topleft" style="width:100%;font-size:22px">Close Menu</a>
<div class="w3-container">
<h1 class="w3-padding-16 w3-xxxlarge">
<img src="/logo.svg" alt="VanJS" width="192px" height="192px">
</h1>
</div>
<div id="nav" class="w3-bar-block"><a href="/" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Home</a><a href="/start" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Getting Started</a><a href="/tutorial" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Tutorial</a><a href="/demo" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white current">VanJS by Example</a><a href="/convert" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">HTML/MD to VanJS</a><a href="/vanui" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">VanUI</a><a href="/minivan" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Mini-Van</a><a href="/ssr" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">SSR & Hydration</a><a href="/x" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">X</a><a href="/advanced" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Advanced Topics</a><a href="/media" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">Media Coverage</a><a href="/about" onclick="w3_close()" class="w3-bar-item w3-button w3-hover-white">About</a></div>
</nav>
<!-- Top menu on small screens -->
<header class="w3-container w3-top w3-hide-large w3-red w3-xlarge w3-padding">
<a href="javascript:void(0)" class="w3-button w3-red w3-margin-right" onclick="w3_open()">☰</a>
<span id="title-bar">VanJS by Example</span>
</header>
<!-- Overlay effect when opening sidebar on small screens -->
<div class="w3-overlay w3-hide-large" onclick="w3_close()" style="cursor:pointer" title="close side menu" id="myOverlay"></div>
<!-- !PAGE CONTENT! -->
<div class="w3-main" style="margin-left:300px;">
<div id="page">
<div id="content"><h1 class="w3-xxlarge"><b>VanJS</b>: Learning by Example</h1><blockquote><i>Simplicity is the ultimate sophistication.<br><br>-- Apple Inc.</i></blockquote><p>Despite being an <b>ultra-lightweight</b> UI framework, <b>VanJS</b> allows you to write incredibly elegant and expressive code for comprehensive application logic. This page is a curated list of cool things you can do with just a few lines of JavaScript code, including several handy utilities built with <b>VanJS</b>.</p><p>See also <a href="#community-examples" class="w3-hover-opacity">Community Examples</a>.</p><p><button id="random-demo"><span id="dice">🎲 </span>Show Me a Random Demo</button></p><h2 class="w3-xxlarge w3-text-red" id="hello-world"><a class="self-link" href="#hello-world">Hello World!</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>This is the <code class="symbol">Hello World</code> program shown in the <a href="/" class="w3-hover-opacity">Home</a> page:</p><pre><code class="language-js">const Hello = () => div(
p("👋Hello"),
ul(
li("🗺️World"),
li(a({href: "https://vanjs.org/"}, "🍦VanJS")),
),
)
</code></pre><p><b>Demo:</b></p><p id="demo-hello"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/hello">Try on jsfiddle</a></p><p>This is the funnier <code class="symbol">Hello</code> program shown in <a href="/start" class="w3-hover-opacity">Getting Started</a> page:</p><pre><code class="language-js">const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const Run = ({sleepMs}) => {
const steps = van.state(0)
;(async () => { for (; steps.val < 40; ++steps.val) await sleep(sleepMs) })()
return pre(() => `${" ".repeat(40 - steps.val)}🚐💨Hello VanJS!${"_".repeat(steps.val)}`)
}
const Hello = () => {
const dom = div()
return div(
dom,
button({onclick: () => van.add(dom, Run({sleepMs: 2000}))}, "Hello 🐌"),
button({onclick: () => van.add(dom, Run({sleepMs: 500}))}, "Hello 🐢"),
button({onclick: () => van.add(dom, Run({sleepMs: 100}))}, "Hello 🚶♂️"),
button({onclick: () => van.add(dom, Run({sleepMs: 10}))}, "Hello 🏎️"),
button({onclick: () => van.add(dom, Run({sleepMs: 2}))}, "Hello 🚀"),
)
}
</code></pre><p><b>Demo:</b></p><p id="demo-hello-fun"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/hello-fun">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="dom-composition-and-manipulation"><a class="self-link" href="#dom-composition-and-manipulation">DOM Composition and Manipulation</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>Even without state and state binding, you can build interactive web pages thanks to <b>VanJS</b>'s flexible API for DOM composition and manipulation: <code class="symbol"><a href="/tutorial#api-tags" class="w3-hover-opacity">tag functions</a></code> and <code class="symbol"><a href="/tutorial#api-add" class="w3-hover-opacity">van.add</a></code>. Check out the example below:</p><pre><code class="language-js">const StaticDom = () => {
const dom = div(
div(
button("Dummy Button"),
button(
{onclick: () =>
van.add(dom,
div(button("New Button")),
div(a({href: "https://www.example.com/"}, "This is a link")),
)
},
"Button to Add More Elements"),
button({onclick: () => alert("Hello from 🍦VanJS")}, "Hello"),
),
)
return dom
}
</code></pre><p><b>Demo:</b></p><p id="demo-static"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/static">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="counter"><a class="self-link" href="#counter">Counter</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>The <code class="symbol">Counter App</code> is a good illustration on how to leverage <a href="/tutorial#states" class="w3-hover-opacity">States</a> to make your application reactive. This is the program shown in the <a href="/" class="w3-hover-opacity">Home</a> page:</p><pre><code class="language-js">const Counter = () => {
const counter = van.state(0)
return span(
"❤️ ", counter, " ",
button({onclick: () => ++counter.val}, "👍"),
button({onclick: () => --counter.val}, "👎"),
)
}
</code></pre><p><b>Demo:</b> <span id="demo-counter-simple"></span></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/counter-simple">Try on jsfiddle</a></p><p>This is a slightly advanced version of <code class="symbol">Counter App</code>:</p><pre><code class="language-js">const buttonStyleList = [
["👆", "👇"],
["👍", "👎"],
["🔼", "🔽"],
["⬆️", "⬇️"],
["⏫", "⏬"],
["📈", "📉"],
]
const Counter = ({buttons}) => {
const counter = van.state(0)
const dom = div(
"❤️ ", counter, " ",
button({onclick: () => ++counter.val}, buttons[0]),
button({onclick: () => --counter.val}, buttons[1]),
button({onclick: () => dom.remove()}, "❌"),
)
return dom
}
const CounterSet = () => {
const containerDom = div()
return div(
containerDom,
button({onclick: () => van.add(containerDom,
Counter({buttons: buttonStyleList[Math.floor(Math.random() * buttonStyleList.length)]}))},
"➕",
),
)
}
</code></pre><p><b>Demo:</b></p><p id="demo-counter-advanced"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/counter-advanced">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="stopwatch"><a class="self-link" href="#stopwatch">Stopwatch</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>This is a <code class="symbol">Stopwatch App</code>, similar to the <code class="symbol"><a href="/tutorial#state-typed-child" class="w3-hover-opacity">Timer App</a></code> shown in the tutorial:</p><pre><code class="language-js">const Stopwatch = () => {
const elapsed = van.state(0)
let id
const start = () => id = id || setInterval(() => elapsed.val += .01, 10)
return span(
pre({style: "display: inline;"}, () => elapsed.val.toFixed(2), "s "),
button({onclick: start}, "Start"),
button({onclick: () => (clearInterval(id), id = 0)}, "Stop"),
button({onclick: () => (clearInterval(id), id = 0, elapsed.val = 0)}, "Reset"),
)
}
</code></pre><p><b>Demo:</b> <span id="demo-stopwatch"></span></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/stopwatch">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="blog"><a class="self-link" href="#blog">Blog</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p><b>VanJS</b> doesn't have an equivalent to React's <code class="symbol"><a href="https://react.dev/reference/react/Fragment" class="w3-hover-opacity"><Fragment></a></code>. For most of the cases, returning an array of HTML elements from your custom component would serve the similar purpose. Here is the sample code equivalent to the <code class="symbol">Blog</code> example in React's official website:</p><pre><code class="language-js">const Blog = () => [
Post({title: "An update", body: "It's been a while since I posted..."}),
Post({title: "My new blog", body: "I am starting a new blog!"}),
]
const Post = ({title, body}) => [
PostTitle({title}),
PostBody({body}),
]
const PostTitle = ({title}) => h1(title)
const PostBody = ({body}) => article(p(body))
</code></pre><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/blog">Try on jsfiddle</a></p><p>The sample code in React is 29 lines. Thus <b>VanJS</b>'s equivalent code is ~3 times shorter by eliminating unnecessary boilerplate.</p><p>Note that: The result of the binding function of a <a href="/tutorial#state-derived-child" class="w3-hover-opacity">state-derived child node</a> can't be an array of elements. You can wrap the result into a pass-through container (<code class="language-html"><span></code> for inline elements and <code class="language-html"><div></code> for block elements) if multiple elements need to be returned.</p><h2 class="w3-xxlarge w3-text-red" id="list"><a class="self-link" href="#list">List</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>As an <b>unopinionated</b> framework, <b>VanJS</b> supports multiple programming paradigms. You can construct the DOM tree in an imperative way (modifying the DOM tree via <code class="symbol"><a href="/tutorial#api-add" class="w3-hover-opacity">van.add</a></code>), or in a functional/declarative way.</p><p>Below is an example of building a list even numbers in <code class="symbol">1..N</code>, using an imperative way:</p><pre><code class="language-js">const EvenNumbers = ({N}) => {
const listDom = ul()
for (let i = 1; i <= N; ++i)
if (i % 2 === 0)
van.add(listDom, li(i))
return div(
p("List of even numbers in 1.." + N + ":"),
listDom,
)
}</code></pre><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/list-imperative">Try on jsfiddle</a></p><p>Alternatively, you can build a list of even numbers in <code class="symbol">1..N</code>, using a functional/declarative way:</p><pre><code class="language-js">const EvenNumbers = ({N}) => div(
p("List of even numbers in 1.." + N + ":"),
ul(
Array.from({length: N}, (_, i) => i + 1)
.filter(i => i % 2 === 0)
.map(i => li(i)),
),
)
</code></pre><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/list-declarative">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="todo-list"><a class="self-link" href="#todo-list">TODO List</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>Similarly, to build reactive applications, you can build in a procedural way, which updates UI via the integration with native DOM API (it's easy to do with <b>VanJS</b> as it doesn't introduce an ad-hoc virtual-DOM layer), or in a functional/reactive way, which delegates UI changes to <a href="/tutorial#state-binding" class="w3-hover-opacity">State Binding</a>. You can also choose a hybrid approach between the 2 paradigms, depending on which approach fits well for a specific problem.</p><blockquote><i>道可道,非常道<br>(A rule that can be told by words, is not the rule that should universally apply)<br><br>-- 老子,道德经</i></blockquote><p>Below is an example of building a <code class="symbol">TODO List</code> in a completely procedural way:</p><pre><code class="language-js">const TodoItem = ({text}) => div(
input({type: "checkbox", onchange: e =>
e.target.closest("div").querySelector("span").style["text-decoration"] =
e.target.checked ? "line-through" : ""
}),
span(text),
a({onclick: e => e.target.closest("div").remove()}, "❌"),
)
const TodoList = () => {
const inputDom = input({type: "text"})
const dom = div(
inputDom,
button({onclick: () => van.add(dom, TodoItem({text: inputDom.value}))}, "Add"),
)
return dom
}
</code></pre><p><b>Demo:</b></p><p id="demo-todo-procedural"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/todo-procedural">Try on jsfiddle</a></p><p>Alternatively, you can use a functional/reactive way to build <code class="symbol">TODO Items</code>:</p><pre><code class="language-js">const TodoItem = ({text}) => {
const done = van.state(false), deleted = van.state(false)
return () => deleted.val ? null : div(
input({type: "checkbox", checked: done, onclick: e => done.val = e.target.checked}),
() => (done.val ? del : span)(text),
a({onclick: () => deleted.val = true}, "❌"),
)
}
const TodoList = () => {
const inputDom = input({type: "text"})
const dom = div(
inputDom,
button({onclick: () => van.add(dom, TodoItem({text: inputDom.value}))}, "Add"),
)
return dom
}
</code></pre><p><b>Demo:</b></p><p id="demo-todo-functional"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/todo-functional">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="todo-app"><a class="self-link" href="#todo-app">A Fully Reactive TODO App</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>You can also go fully reactive for the <code class="symbol">TODO App</code>. That is, the entire state of the app is captured by a global <code class="symbol">appState</code>. With the full reactivity it's easier to persist the <code class="symbol">appState</code> into <code class="symbol"><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage" class="w3-hover-opacity">localStorage</a></code> so that the state is kept across page reloads.</p><p>Note that even if the app is fully reactive, we don't need to re-render the whole DOM tree for state updates, thanks to the optimization with <a href="/tutorial#stateful-binding" class="w3-hover-opacity">stateful binding</a>.</p><p><i>The code was implemented in TypeScript.</i></p><pre><code class="language-ts">class TodoItemState {
constructor(public text: string, public done: State<boolean>, public deleted: State<boolean>) {}
serialize() { return {text: this.text, done: this.done.val} }
}
const TodoItem = ({text, done, deleted}: TodoItemState) => () => deleted.val ? null : div(
input({type: "checkbox", checked: done, onclick: e => done.val = e.target.checked}),
() => (done.val ? del : span)(text),
a({onclick: () => deleted.val = true}, "❌"),
)
class TodoListState {
private constructor(public todos: TodoItemState[]) {}
save() {
localStorage.setItem("appState", JSON.stringify(
(this.todos = this.todos.filter(t => !t.deleted.val)).map(t => t.serialize())))
}
static readonly load = () => new TodoListState(
JSON.parse(localStorage.getItem("appState") ?? "[]")
.map((t: any) => new TodoItemState(t.text, van.state(t.done), van.state(false)))
)
add(text: string) {
this.todos.push(new TodoItemState(text, van.state(false), van.state(false)))
return new TodoListState(this.todos)
}
}
const TodoList = () => {
const appState = van.state(TodoListState.load())
van.derive(() => appState.val.save())
const inputDom = input({type: "text"})
return div(
inputDom, button({onclick: () => appState.val = appState.val.add(inputDom.value)}, "Add"),
(dom?: Element) => dom ?
van.add(dom, TodoItem(appState.val.todos.at(-1)!)) :
div(appState.val.todos.map(TodoItem)),
)
}
</code></pre><p><b>Demo:</b></p><p id="demo-todo-fully-reactive"></p><p><a href="https://codesandbox.io/p/sandbox/github/vanjs-org/vanjs-org.github.io/tree/master/code/todo-app?file=/src/main.ts:1,1" class="w3-hover-opacity">Try on CodeSandbox</a></p><p>With the help of <a href="/x" class="w3-hover-opacity"><b>VanX</b></a>, the code above can be simplified to just 10+ lines:</p><pre><code class="language-js">const TodoList = () => {
const items = vanX.reactive(JSON.parse(localStorage.getItem("appState") ?? "[]"))
van.derive(() => localStorage.setItem("appState", JSON.stringify(vanX.compact(items))))
const inputDom = input({type: "text"})
return div(
inputDom, button({onclick: () => items.push({text: inputDom.value, done: false})}, "Add"),
vanX.list(div, items, ({val: v}, deleter) => div(
input({type: "checkbox", checked: () => v.done, onclick: e => v.done = e.target.checked}),
() => (v.done ? del : span)(v.text),
a({onclick: deleter}, "❌"),
)),
)
}
</code></pre><p><b>Demo:</b></p><p id="demo-todo-fully-reactive-vanx"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/todo-fully-reactive-vanx">Try on jsfiddle</a></p><p>You can refer to <code class="symbol"><a href="/x#reactive-list" class="w3-hover-opacity">vanX.list</a></code> for more details.</p><p><i>You can also check <a href="https://github.com/vanjs-org/van/discussions/316" class="w3-hover-opacity">the example</a> by <a href="https://github.com/ArcaneEngineer" class="w3-hover-opacity">@ArcaneEngineer</a>, which is a slight variation of this <code class="symbol">TODO App</code> to allow TODO items to be editable.</i></p><h2 class="w3-xxlarge w3-text-red" id="game"><a class="self-link" href="#game">Fun Game: Emojis Pops</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>We're able to implement a mini game engine with <b>VanJS</b> in just a few lines. Here is a fun game implemented under 60 lines with the help of <b>VanJS</b> and <a href="x" class="w3-hover-opacity"><b>VanX</b></a>:</p><pre><code class="language-js">const Game = () => {
const time = van.state(60), score = van.state(0), inGame = van.state(false), items = vanX.reactive([])
const fps = 60, height = 400, frameFns = Array(fps * time.val).fill().map(() => [])
let curFrame = 0
const Item = ({val: v}, deleter) => {
const x = Math.floor(Math.random() * (document.body.clientWidth - 42)), y = van.state(0)
let deleted = false
v.removing = false
van.derive(() => v.removing &&
nextFrames(Math.floor(0.3 * fps)).then(() => (deleted = true, deleter())))
;(async () => {
do { await nextFrames(1) } while (!deleted && (y.val += v.speed) <= height)
v.removing || deleter()
})()
return span({
class: "item",
style: () => `left: ${x}px; bottom: ${y.val}px; opacity: ${v.removing ? 0 : 1};`,
onclick: () => inGame.val && !v.removing &&
frameFns[curFrame].push(() => (v.removing = v.msg, v.action())),
}, v.icon, () => v.removing ? span({class: "msg " + (v.bad ? "bad": "good")}, v.removing) : "")
}
const itemTypes = [
{icon: "👍", speed: 5, n: 60, msg: "+1", action: () => ++score.val},
{icon: "🚀", speed: 10, n: 12, msg: "+10", action: () => score.val += 10},
{icon: "👎", speed: 3, n: 60, msg: "-5", bad: true, action: () => score.val -= 5},
{icon: "🐌", speed: 5, n: 6, msg: "Slowed", action: () => items.forEach(it => it.speed /= 2)},
{icon: "💣", speed: 3, n: 60, msg: "BOOM!", bad: true, action: () =>
items.forEach(it => it.removing = "BOOM!")},
]
const begin = () => {
setInterval(() => {
if (!inGame.val) return
for (const fn of frameFns[curFrame]) fn()
++curFrame % 60 === 0 && --time.val
curFrame === frameFns.length && end()
}, 1000 / fps)
inGame.val = true
for (const type of itemTypes)
for (let i = 0; i < type.n; ++i)
frameFns[Math.floor(Math.random() * frameFns.length)].push(() => items.push({...type}))
}
const end = () => (alert("Your score: " + score.val), location.reload())
const nextFrames = n => new Promise(r => frameFns[curFrame + n]?.push(r))
return div({class: "root"},
span({class: "time"}, "Time: ", time), span({class: "score"}, "Score: ", score),
vanX.list(() => div({class: "board"}), items, Item),
div({class: "panel"},
button({onclick: () => curFrame ? inGame.val = !inGame.val : begin()},
() => inGame.val ? "Pause" : "Start",
),
),
)
}
</code></pre><p><a href="/code/game" class="w3-hover-opacity">🎮 Let's play!</a> (you can share your score here: <a href="https://github.com/vanjs-org/van/discussions/174" class="w3-hover-opacity">#174</a>)</p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/game">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="code-browser"><a class="self-link" href="#code-browser">SPA w/ Client-Side Routing: Code Browser</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>With <b>VanJS</b>, you can built a single-page application with client-side routing support, thanks to <b>VanJS</b>'s powerful builtin state management and state derivation:</p><pre><code class="language-ts">const Browser = () => {
const file = van.state(location.hash.slice(1))
window.addEventListener("hashchange", () => file.val = location.hash.slice(1))
const text = van.derive(() => file.val ? (
fetch("https://api.github.com/repos/vanjs-org/van/contents/src/" + file.val)
.then(r => r.json())
.then(json => text.val = {lang: file.val.split(".").at(-1), str: atob(json.content)})
.catch(e => text.val = {str: e.toString()}),
{str: "Loading"}
) : {str: "Select a file to browse"})
const files = van.state([])
fetch("https://api.github.com/repos/vanjs-org/van/contents/src")
.then(r => r.json())
.then(json => files.val = json.map(f => f.name).filter(n => /\.(ts|js)$/.test(n)))
.catch(e => text.val = {str: e.toString()})
const browseFile = e => {
e.preventDefault()
history.pushState({}, "", new URL(e.target.href).hash)
dispatchEvent(new Event("hashchange"))
}
return div({class: "row"},
div({class: "left"}, ul(li({class: "folder"}, "src", () => ul(
files.val.map(f => li({class: "file"},
a({href: "#" + f, class: () => f === file.val ? "selected" : "", onclick: browseFile}, f),
)),
)))),
(dom = div({class: "right"}, pre(code()))) => {
const codeDom = dom.querySelector("code")
codeDom.textContent = text.val.str
codeDom.className = text.val.lang ? "language-" + text.val.lang : ""
if (text.val.lang) setTimeout(() => Prism.highlightAll(), 5)
return dom
},
)
}
</code></pre><p><a href="https://codesandbox.io/p/sandbox/github/vanjs-org/vanjs-org.github.io/tree/master/code/code-browser?file=/src/main.js:1,1" class="w3-hover-opacity">Try on CodeSandbox</a></p><h2 class="w3-xxlarge w3-text-red" id="stargazers"><a class="self-link" href="#stargazers">Stargazers</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>The following code can show the number of stars for a Github repo, and a list of most recent stargazers:</p><pre><code class="language-js">const Stars = async repo => {
const repoJson = await fetch(`https://api.github.com/repos/${repo}`).then(r => r.json())
const pageNum = Math.floor((repoJson.stargazers_count - 1) / 100) + 1
const starsJson = await fetch(
`https://api.github.com/repos/${repo}/stargazers?per_page=100&page=${pageNum}`)
.then(r => r.json())
return div(
p(repoJson.stargazers_count, " ⭐️:"),
ul(
starsJson.reverse().map(u => li(a({href: u.html_url}, u.login))),
),
)
}
</code></pre><p><a href="code/stars" class="w3-hover-opacity">Try it out here</a></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/starts">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="epoch-timestamp-converter"><a class="self-link" href="#epoch-timestamp-converter">Epoch Timestamp Converter</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>Below is an application which converts a Unix epoch timestamp into a human-readable datetime string:</p><pre><code class="language-js">const tsToDate = ts =>
ts < 1e10 ? new Date(ts * 1e3) :
ts < 1e13 ? new Date(ts) :
ts < 1e16 ? new Date(ts / 1e3) :
new Date(ts / 1e6)
const Converter = () => {
const nowTs = van.state(Math.floor(new Date().getTime() / 1e3)), date = van.state(null)
setInterval(() => ++nowTs.val, 1000)
const inputDom = input({type: "text", size: 25, value: nowTs.val})
return div(
div(b("Now: "), nowTs),
inputDom, " ",
button({onclick: () => date.val = tsToDate(Number(inputDom.value))}, "Convert"),
p(i("Supports Unix timestamps in seconds, milliseconds, microseconds and nanoseconds.")),
() => date.val ? p(
div(date.val.toString()),
div(b("GMT: "), date.val.toGMTString()),
) : p(),
)
}
</code></pre><p><b>Demo:</b></p><p id="demo-epoch-converter"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/epoch-converter">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="keyboard-event-inspector"><a class="self-link" href="#keyboard-event-inspector">Keyboard Event Inspector</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>Below is an application to inspect all relevant key codes in keyboard <code class="symbol"><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event" class="w3-hover-opacity">keydown</a></code> events:</p><pre><code class="language-js">const Label = text => span({class: "label"}, text)
const Value = text => span({class: "value"}, text)
const Inspector = () => {
const keyEvent = van.state(new KeyboardEvent("keydown"))
const Result = prop => span(Label(prop + ": "), Value(() => keyEvent.val[prop]))
return div(
div(input({placeholder: "Focus here and press keys…", style: "width: 260px",
onkeydown: e => (e.preventDefault(), keyEvent.val = e)})),
div(Result("key"), Result("code"), Result("which"), Result("keyCode")),
div(Result("ctrlKey"), Result("metaKey"), Result("altKey"), Result("shiftKey")),
)
}
</code></pre><p><b>Demo:</b></p><p id="demo-key-inspector"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/key-inspector">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="diff"><a class="self-link" href="#diff">Diff</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>Here is a <code class="symbol">Diff App</code> with the integration of <code class="symbol"><a href="https://github.com/kpdecker/jsdiff" class="w3-hover-opacity">jsdiff</a></code>. The app can compare 2 pieces of text (very handy tool to check how your text is revised by <code class="symbol">ChatGPT</code> 🙂):</p><pre><code class="language-js">const autoGrow = e => {
e.target.style.height = "5px"
e.target.style.height = (e.target.scrollHeight + 5) + "px"
}
const DiffApp = () => {
const oldTextDom = textarea({oninput: autoGrow, rows: 1})
const newTextDom = textarea({oninput: autoGrow, rows: 1})
const diff = van.state([])
return div(
div({class: "row"},
div({class: "column"}, oldTextDom), div({class: "column"}, newTextDom),
),
div({class: "row"},
button({onclick: () => diff.val = Diff.diffWords(oldTextDom.value, newTextDom.value)},
"Diff",
),
),
div({class: "row"}, () => div({class: "column", style: "white-space: pre-wrap;"},
diff.val.map(d => span({class: d.added ? "add" : (d.removed ? "remove" : "")}, d.value)),
)),
)
}</code></pre><p><b>Demo:</b></p><p id="demo-diff-simple"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/diff-simple">Try on jsfiddle</a></p><p>Here is a more advanced <code class="symbol">Diff App</code> that supports side-by-side and line-by-line comparison:</p><pre><code class="language-js">const autoGrow = e => {
e.target.style.height = "5px"
e.target.style.height = (e.target.scrollHeight + 5) + "px"
}
const Line = ({diff, skipAdd, skipRemove}) => div(
{class: "column", style: "white-space: pre-wrap;"},
diff.filter(d => !(skipAdd && d.added || skipRemove && d.removed)).map(d =>
span({class: d.added ? "add" : (d.removed ? "remove" : "")}, d.value)),
)
const DiffLine = (oldLine, newLine, showMerged) => {
const diff = Diff.diffWords(oldLine, newLine)
return div({class: "row" + (showMerged ? " merged" : "")},
showMerged ?
Line({diff}) : [Line({diff, skipAdd: true}), Line({diff, skipRemove: true})],
)
}
const DiffApp = () => {
const oldTextDom = textarea({oninput: autoGrow, rows: 1})
const newTextDom = textarea({oninput: autoGrow, rows: 1})
const diff = van.state([])
const showMerged = van.state(true)
return div(
div({class: "row"},
div({class: "column"}, oldTextDom), div({class: "column"}, newTextDom),
),
div({class: "row"},
button({onclick: () => diff.val = Diff.diffLines(oldTextDom.value, newTextDom.value)},
"Diff",
),
input({type: "checkbox", checked: showMerged,
oninput: e => showMerged.val = e.target.checked}),
"show merged result"
),
() => {
const diffVal = diff.val, showMergedVal = showMerged.val, resultDom = div()
for (let i = 0; i < diffVal.length; ) {
let line
if (diffVal[i].added && diffVal[i + 1]?.removed) {
line = DiffLine(diffVal[i + 1].value, diffVal[i].value, showMergedVal)
i += 2
} else if (diffVal[i].removed && diffVal[i + 1]?.added) {
line = DiffLine(diffVal[i].value, diffVal[i + 1].value, showMergedVal)
i += 2
} else if (diffVal[i].added) {
line = showMergedVal ? div({class: "merged add row"},
div({class: "column", style: "white-space: pre-wrap;"}, diffVal[i].value),
) : div({class: "row"},
div({class: "column"}),
div({class: "add column", style: "white-space: pre-wrap;"}, diffVal[i].value),
)
++i
} else if (diffVal[i].removed) {
line = showMergedVal ? div({class: "merged remove row"},
div({class: "column", style: "white-space: pre-wrap;"}, diffVal[i].value),
) : div({class: "row"},
div({class: "remove column", style: "white-space: pre-wrap;"}, diffVal[i].value),
)
++i
} else {
line = div({class: "row", style: "white-space: pre-wrap;"},
showMergedVal ? div({class: "merged column"}, diffVal[i].value) :
[
div({class: "column"}, diffVal[i].value),
div({class: "column"}, diffVal[i].value),
],
)
++i
}
van.add(resultDom, line)
}
return resultDom
},
)
}
</code></pre><p><b>Demo:</b></p><p id="demo-diff"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/diff">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="calculator"><a class="self-link" href="#calculator">Calculator</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>The code below implements a <code class="symbol">Calculator App</code> similar to the one that you are using on your smartphones:</p><pre><code class="language-js">const Calculator = () => {
let lhs = van.state(null), op = null, rhs = van.state(0)
const calc = (lhs, op, rhs) =>
!op || lhs === null ? rhs :
op === "+" ? lhs + rhs :
op === "-" ? lhs - rhs :
op === "x" ? lhs * rhs : lhs / rhs
const onclick = e => {
const str = e.target.innerText
if (str >= "0" && str <= "9")
typeof rhs.val === "string" ? rhs.val += str : rhs.val = rhs.val * 10 + Number(str)
else if (str === "AC") lhs.val = op = null, rhs.val = 0
else if (str === "+/-" && rhs.val) rhs.val = -rhs.val
else if (str === "%" && rhs.val) rhs.val *= 0.01
else if (str === "+" || str === "-" || str === "x" || str === "÷") {
if (rhs.val !== null) lhs.val = calc(lhs.val, op, Number(rhs.val)), rhs.val = null
op = str
} else if (str === "=" && op && rhs.val !== null)
lhs.val = calc(lhs.val, op, Number(rhs.val)), op = null, rhs.val = null
else if (str === ".")
rhs.val = rhs.val ? rhs.val + "." : "0."
}
const Button = str => div({class: "button"}, button(str))
return div({id: "root"},
div({id: "display"}, div(() => rhs.val ?? lhs.val)),
div({id: "panel", onclick},
div(Button("AC"), Button("+/-"), Button("%"), Button("÷")),
div(Button("7"), Button("8"), Button("9"), Button("x")),
div(Button("4"), Button("5"), Button("6"), Button("-")),
div(Button("1"), Button("2"), Button("3"), Button("+")),
div(div({class: "button wide"}, button("0")), Button("."), Button("=")),
),
)
}
</code></pre><p><b>Demo:</b></p><iframe id="demo-calculator" src="/code/calculator.html"></iframe><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/calculator">Try on jsfiddle</a></p><p>Notably, this <code class="symbol">Calculator App</code> is equivalent to the React-based implementation here: <a href="https://github.com/ahfarmer/calculator" class="w3-hover-opacity">github.com/ahfarmer/calculator</a>. Here is the size comparison of the total package between the 2 apps:</p><table style="text-align: right;"><thead><tr><th></th><th>VanJS-based App</th><th>React-based App</th></tr></thead><tbody><tr><td><b># of files:</b></td><td>2</td><td>16</td></tr><tr><td><b># of lines:</b></td><td>143</td><td>616</td></tr></tbody></table><p>As you can see, not only <b>VanJS</b> is <b>~50 times</b> smaller than React, apps built with <b>VanJS</b> also tends to be much slimmer.</p><h2 class="w3-xxlarge w3-text-red" id="table-viewer"><a class="self-link" href="#table-viewer">Table-View Example: JSON/CSV Table Viewer</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>The following code implements a <code class="symbol">Table Viewer</code> for JSON/CSV-based data by leveraging <a href="/tutorial#fun-dom" class="w3-hover-opacity">functional-style DOM tree building</a>:</p><pre><code class="language-js">const TableViewer = ({inputText, inputType}) => {
const jsonRadioDom = input({type: "radio", checked: inputType === "json",
name: "inputType", value: "json"})
const csvRadioDom = input({type: "radio", checked: inputType === "csv",
name: "inputType", value: "csv"})
const autoGrow = e => {
e.style.height = "5px"
e.style.height = (e.scrollHeight + 5) + "px"
}
const textareaDom = textarea({oninput: e => autoGrow(e.target)}, inputText)
setTimeout(() => autoGrow(textareaDom), 10)
const text = van.state("")
const tableFromJson = text => {
const json = JSON.parse(text), head = Object.keys(json[0])
return {
head,
data: json.map(row => head.map(h => row[h]))
}
}
const tableFromCsv = text => {
const lines = text.split("\n").filter(l => l.length > 0)
return {
head: lines[0].split(","),
data: lines.slice(1).map(l => l.split(",")),
}
}
return div(
div(jsonRadioDom, label("JSON"), csvRadioDom, label("CSV (Quoting not Supported)")),
div(textareaDom),
div(button({onclick: () => text.val = textareaDom.value}, "Show Table")),
p(() => {
if (!text.val) return div()
try {
const {head, data} = (jsonRadioDom.checked ? tableFromJson : tableFromCsv)(text.val)
return table(
thead(tr(head.map(h => th(h)))),
tbody(data.map(row => tr(row.map(col => td(col))))),
)
} catch (e) {
return pre({class: "err"}, e.toString())
}
}),
)
}
</code></pre><p><b>Demo:</b></p><p id="demo-table-viewer"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/table-viewer">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="package-lock-inspector"><a class="self-link" href="#package-lock-inspector"><code class="symbol">package-lock.json</code> Inspector</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>Below is an example which can extract and display all dependency packages and their versions from <code class="symbol">package-lock.json</code> file:</p><pre><code class="language-js">const PackageLockInspector = () => {
const json = van.state("")
return [
div("Paste the content of package-lock.json file here:"),
textarea({rows: 10, cols: 80, oninput: e => json.val = e.target.value}),
() => {
if (!json.val) return div()
try {
const packages = Object.entries(JSON.parse(json.val).packages).filter(([k]) => k)
return div(
h4("All Dependencies (", packages.length, ")"),
table(
thead(tr(th("Package"), th("Version"))),
tbody(packages.map(([k, {version}]) => {
const name = k.slice("node_modules/".length)
return tr(
td(a({href: "https://www.npmjs.com/package/" + name}, name)),
td(a({href: `https://www.npmjs.com/package/${name}/v/${version}`}, version)),
)
})),
),
)
} catch (e) {
return pre({style: "color: red;"}, "Parsing error: ", e.toString())
}
},
]
}
</code></pre><p><a href="code/package-lock-inspector" class="w3-hover-opacity">Try it out here</a></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/package-lock-inspector">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="json-inspector"><a class="self-link" href="#json-inspector">Tree-View Example: JSON Inspector</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>This is another example of leveraging <a href="/tutorial#fun-dom" class="w3-hover-opacity">functional-style DOM tree building</a> - to build a tree view for inspecting JSON data:</p><pre><code class="language-js">const ListItem = ({key, value, indent = 0}) => {
const hide = van.state(key !== "")
const valueDom = typeof value !== "object" ? value : div(
{style: () => hide.val ? "display: none;" : ""},
Object.entries(value).map(([k, v]) =>
ListItem({key: k, value: v, indent: indent + 2 * (key !== "")})),
)
return (key ? div : pre)(
" ".repeat(indent),
key ? (
typeof valueDom !== "object" ? ["🟰 ", b(`${key}: `)] :
a({onclick: () => hide.val = !hide.val, style: "cursor: pointer"},
() => hide.val ? "➕ " : "➖ ", b(`${key}: `), () => hide.val ? "…" : "",
)
) : [],
valueDom,
)
}
const JsonInspector = ({initInput}) => {
const autoGrow = e => {
e.style.height = "5px"
e.style.height = (e.scrollHeight + 5) + "px"
}
const textareaDom = textarea({oninput: e => autoGrow(e.target)}, initInput)
setTimeout(() => autoGrow(textareaDom), 10)
const errmsg = van.state(""), json = van.state(null)
const inspect = () => {
try {
json.val = JSON.parse(textareaDom.value)
errmsg.val = ""
} catch (e) {
errmsg.val = e.message
}
}
return div(
div(textareaDom),
div(button({onclick: inspect}, "Inspect")),
pre({style: "color: red"}, errmsg),
() => json.val ? ListItem({key: "", value: json.val}) : "",
)
}</code></pre><p><b>Demo:</b></p><p id="demo-json-inspector"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/json-inspector">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="auto-complete"><a class="self-link" href="#auto-complete">Textarea with Autocomplete</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>The code below implements a <code class="symbol"><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea" class="w3-hover-opacity">textarea</a></code> with autocomplete support. This implementation leverages <a href="/tutorial#stateful-binding" class="w3-hover-opacity">Stateful DOM binding</a> to optimize the performance of DOM tree rendering:</p><p><i>The code was implemented in TypeScript to validate <b>VanJS</b>'s TypeScript support.</i></p><pre><code class="language-ts">interface SuggestionListProps {
readonly candidates: readonly string[]
readonly selectedIndex: number
}
const SuggestionList = ({candidates, selectedIndex}: SuggestionListProps) =>
div({class: "suggestion"}, candidates.map((s, i) => pre({
"data-index": i,
class: i === selectedIndex ? "text-row selected" : "text-row",
}, s)))
const lastWord = (text: string) => text.match(/\w+$/)?.[0] ?? ""
const AutoComplete = ({words}: {readonly words: readonly string[]}) => {
const getCandidates = (prefix: string) => {
const maxTotal = 10, result: string[] = []
for (let word of words) {
if (word.startsWith(prefix.toLowerCase())) result.push(word)
if (result.length >= maxTotal) break
}
return result
}
const prefix = van.state("")
const candidates = van.derive(() => getCandidates(prefix.val))
// Resetting selectedIndex to 0 whenever candidates change
const selectedIndex = van.derive(() => (candidates.val, 0))
const onkeydown = (e: KeyboardEvent) => {
if (e.key === "ArrowDown") {
selectedIndex.val = selectedIndex.val + 1 < candidates.val.length ? selectedIndex.val + 1 : 0
e.preventDefault()
} else if (e.key === "ArrowUp") {
selectedIndex.val = selectedIndex.val > 0 ? selectedIndex.val - 1 : candidates.val.length - 1
e.preventDefault()
} else if (e.key === "Enter") {
const candidate = candidates.val[selectedIndex.val] ?? prefix.val
const target = <HTMLTextAreaElement>e.target
target.value += candidate.substring(prefix.val.length)
target.setSelectionRange(target.value.length, target.value.length)
prefix.val = lastWord(target.value)
e.preventDefault()
}
}
const oninput = (e: Event) => prefix.val = lastWord((<HTMLTextAreaElement>e.target).value)
return div({class: "root"}, textarea({onkeydown, oninput}), (dom?: Element) => {
if (dom && candidates.val === candidates.oldVal) {
// If the candidate list doesn't change, we don't need to re-render the
// suggestion list. Just need to change the selected candidate.
dom.querySelector(`[data-index="${selectedIndex.oldVal}"]`)
?.classList?.remove("selected")
dom.querySelector(`[data-index="${selectedIndex.val}"]`)
?.classList?.add("selected")
return dom
}
return SuggestionList({candidates: candidates.val, selectedIndex: selectedIndex.val})
})
}
</code></pre><p><b>Demo:</b></p><p id="demo-auto-complete-stateful-binding"></p><p id="jsfiddle-auto-complete-stateful-binding"><a href="https://jsfiddle.net/p5e71ryw/">Try on jsfiddle</a></p><p>Alternatively, we can implement the same app with <a href="/tutorial#state-derived-prop" class="w3-hover-opacity">State-derived properties</a>:</p><p><i>The code was implemented in TypeScript to validate <b>VanJS</b>'s TypeScript support.</i></p><pre><code class="language-ts">const lastWord = (text: string) => text.match(/\w+$/)?.[0] ?? ""
const AutoComplete = ({words}: {readonly words: readonly string[]}) => {
const maxTotalCandidates = 10
const getCandidates = (prefix: string) => {
const result: string[] = []
for (let word of words) {
if (word.startsWith(prefix.toLowerCase())) result.push(word)
if (result.length >= maxTotalCandidates) break
}
return result
}
const prefix = van.state("")
const candidates = van.derive(() => getCandidates(prefix.val))
// Resetting selectedIndex to 0 whenever candidates change
const selectedIndex = van.derive(() => (candidates.val, 0))
const SuggestionListItem = ({index}: {index: number}) => pre(
{class: () => index === selectedIndex.val ? "text-row selected" : "text-row"},
() => candidates.val[index] ?? "",
)
const suggestionList = div({class: "suggestion"},
Array.from({length: 10}).map((_, index) => SuggestionListItem({index})))
const onkeydown = (e: KeyboardEvent) => {
if (e.key === "ArrowDown") {
selectedIndex.val = selectedIndex.val + 1 < candidates.val.length ? selectedIndex.val + 1 : 0
e.preventDefault()
} else if (e.key === "ArrowUp") {
selectedIndex.val = selectedIndex.val > 0 ? selectedIndex.val - 1 : candidates.val.length - 1
e.preventDefault()
} else if (e.key === "Enter") {
const candidate = candidates.val[selectedIndex.val] ?? prefix.val
const target = <HTMLTextAreaElement>e.target
target.value += candidate.substring(prefix.val.length)
target.setSelectionRange(target.value.length, target.value.length)
prefix.val = lastWord(target.value)
e.preventDefault()
}
}
const oninput = (e: Event) => prefix.val = lastWord((<HTMLTextAreaElement>e.target).value)
return div({class: "root"}, textarea({onkeydown, oninput}), suggestionList)
}
</code></pre><p><b>Demo:</b></p><p id="demo-auto-complete-derived-props"></p><p id="jsfiddle-auto-complete-derived-props"><a href="https://jsfiddle.net/7ueod0pL/1/">Try on jsfiddle</a></p><h2 class="w3-xxlarge w3-text-red" id="html-md-to-vanjs-code-converter"><a class="self-link" href="#html-md-to-vanjs-code-converter">HTML/MD to VanJS Code Converter</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>The <a href="/convert" class="w3-hover-opacity">online UI</a> for the HTML/MD snippet to <b>VanJS</b> <a href="https://github.com/vanjs-org/converter" class="w3-hover-opacity">code converter</a>, is also implemented with <b>VanJS</b>.</p><p>Source code: <code class="symbol"><a href="https://github.com/vanjs-org/vanjs-org.github.io/tree/master/converter-ui/convert.ts" class="w3-hover-opacity">convert.ts</a></code></p><h2 class="w3-xxlarge w3-text-red" id="jupyter-like-javascript-console"><a class="self-link" href="#jupyter-like-javascript-console">Jupyter-like JavaScript Console</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>Next up, we're going to demonstrate a simplified Jupyter-like JavaScript console implemented in <b>~100 lines</b> of code with <b>VanJS</b>. The JavaScript console supports drawing tables (with the technique similar to <a href="#table-viewer" class="w3-hover-opacity">Table Viewer</a>), inspecting objects in a tree view (with the technique similar to <a href="#json-inspector" class="w3-hover-opacity">Json Inspector</a>) and plotting (with the integration of <a href="https://developers.google.com/chart" class="w3-hover-opacity">Google Charts</a>).</p><p>Here is the implementation:</p><pre><code class="language-js">const toDataArray = data => {
const hasPrimitive = !data.every(r => typeof r === "object")
const keys = [...new Set(
data.flatMap(r => typeof r === "object" ? Object.keys(r) : []))]
return [
(hasPrimitive ? ["Value"] : []).concat(keys),
...data.map(r =>
(typeof r === "object" ? (hasPrimitive ? [""] : []) : [r]).concat(
keys.map(k => r[k] ?? "")
)),
]
}
const table = data => {
const dataArray = toDataArray(data)
return van.tags.table(
thead(tr(th("(index)"), dataArray[0].map(k => th(k)))),
tbody(dataArray.slice(1).map((r, i) => tr(td(i), r.map(c => td(c))))),
)
}
const plot = (data, chartType, options) => {
if (data[0].constructor === Object) data = toDataArray(data)
else if (typeof data[0] === "number")
data = [["", "Value"], ...data.map((d, i) => [i + 1, d])]
const dom = div({class: "chart"})
setTimeout(() => new google.visualization[chartType](dom).draw(
google.visualization.arrayToDataTable(data), options))
return dom
}
const Tree = ({obj, indent = ""}) =>
(indent ? div : pre)(Object.entries(obj).map(([k, v]) => {
if (v?.constructor !== Object && !Array.isArray(v))
return div(indent + "🟰 ", van.tags.b(k + ": "), v)
const expanded = van.state(false)
let treeDom
const onclick = van.derive(() => expanded.val ?
() => (treeDom.remove(), expanded.val = !expanded.val) :
() => (treeDom = result.appendChild(Tree({obj: v, indent: indent + " "}),
expanded.val = !expanded.val)))
const result = div(
indent,
van.tags.a({onclick},
() => expanded.val ? "➖ " : "➕ ",
van.tags.b(k + ":"),
() => expanded.val ? "" : " {…}",
),
)
return result
}))
const ValueView = expr => {
try {
const value = eval(`(${expr})`)
if (value instanceof Element) return value
if (value?.constructor === Object || Array.isArray(value)) return Tree({obj: value})
return pre(String(value))
} catch (e) {
return pre({class: "err"}, e.message + "\n" + e.stack)
}
}
const Output = ({id, expr}) => div({class: "row"},
pre({class: "left"}, `Out[${id}]:`),
div({class: "break"}),
div({class: "right"}, ValueView(expr)),
)
const autoGrow = e => {
e.target.style.height = "5px"
e.target.style.height = (e.target.scrollHeight + 5) + "px"
}
const Input = ({id}) => {
const run = () => {
textareaDom.setAttribute("readonly", true)
runDom.disabled = true
const newTextDom = van.add(textareaDom.closest(".console"), Output({id, expr: textareaDom.value}))
.appendChild(Input({id: id + 1}))
.querySelector("textarea")
newTextDom.focus()
setTimeout(() => newTextDom.scrollIntoView(), 10)
}
const runDom = button({class: "run", onclick: run}, "Run")
const onkeydown = async e => {
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
e.preventDefault()
run()
}
}
const textareaDom = textarea({id, type: "text", onkeydown, oninput: autoGrow,
rows: 1, placeholder: 'Enter JS expression here:'})
return div({class: "row"},
pre({class: "left"}, `In[${id}]:`), runDom, div({class: "break"}),
div({class: "right"}, textareaDom),
)
}
const Console = () => div({class: "console"}, Input({id: 1}))
</code></pre><p><b>Demo:</b></p><p id="demo-js-console"></p><p><a href="https://jsfiddle.net/gh/get/library/pure/vanjs-org/vanjs-org.github.io/tree/master/jsfiddle/demo/js-console">Try on jsfiddle</a></p><p>You can also try out the JavaScript console in <a href="/code/console.html" class="w3-hover-opacity">this standalone page</a>.</p><h2 class="w3-xxlarge w3-text-red" id="an-improved-unix-terminal"><a class="self-link" href="#an-improved-unix-terminal">An Improved Unix Terminal</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>Next up is a web-based Unix terminal that connects to your local computer, with notable improvements, all under 300 lines of code. This is to demonstrate that, with <b>VanJS</b>, we can easily provide great extension to commandline utilities with fancy GUI by leveraging all available HTML elements. The program is heavily tested in macOS, and should in theory works in Linux, or in any environment that has <code class="symbol"><a href="https://en.wikipedia.org/wiki/Bourne_shell" class="w3-hover-opacity">/bin/sh</a></code>.</p><p>See <a href="https://github.com/vanjs-org/van/tree/main/demo/terminal" class="w3-hover-opacity">github.com/vanjs-org/van/tree/main/demo/terminal</a> for the app (<a href="https://codesandbox.io/p/sandbox/github/vanjs-org/van/tree/main/demo/terminal" class="w3-hover-opacity">preview</a>).</p><h2 class="w3-xxlarge w3-text-red" id="community-examples"><a class="self-link" href="#community-examples">Community Examples</a></h2><hr style="width:50px;border:5px solid red" class="w3-round"><p>Besides the official <b>VanJS</b> examples, there are also sample apps from the great <b>VanJS</b> community. Below is a curated list (contact <a href="mailto:tao@vanjs.org" class="w3-hover-opacity">tao@vanjs.org</a> to add yours):</p><table><thead><tr><th>Author</th><th>Project</th><th>Preview</th></tr></thead><tbody><tr><td><a href="https://github.com/yahia-berashish" class="w3-hover-opacity">Yahia Berashish</a></td><td><a href="https://github.com/vitejs/awesome-vite#vanjs" class="w3-hover-opacity"><b>VanJS</b> JavaScript and TypeScript Vite Template</a></td><td><a href="https://codesandbox.io/p/sandbox/github/yahia-berashish/vite-vanjs-ts/tree/main" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/artydev" class="w3-hover-opacity">artydev</a></td><td><a href="https://dev.to/artydev/series/23075" class="w3-hover-opacity"><b>VanJS</b> Series</a></td><td></td></tr><tr><td><a href="https://github.com/barrymun" class="w3-hover-opacity">barrymun</a></td><td><a href="https://github.com/barrymun/division-game" class="w3-hover-opacity">Division Game</a></td><td><a href="http://barrymun.vanjs-division-game.surge.sh/" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/enpitsuLin" class="w3-hover-opacity">enpitsuLin</a></td><td><a href="https://github.com/enpitsuLin/vanjs-todomvc" class="w3-hover-opacity">TODO App</a></td><td><a href="https://codesandbox.io/p/sandbox/github/enpitsuLin/vanjs-todomvc/tree/master?file=%2Fsrc%2Fmain.ts%3A8%2C1" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/kwameopareasiedu" class="w3-hover-opacity">Kwame Opare Asiedu</a></td><td><a href="https://github.com/kwameopareasiedu/vanjs-todo" class="w3-hover-opacity">TODO App</a> with routing and authentication</td><td><a href="https://kwameopareasiedu.github.io/vanjs-todo/" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/CodeByZack" class="w3-hover-opacity">董凯</a></td><td><a href="https://github.com/CodeByZack/local-share" class="w3-hover-opacity">Local Share</a> - A tool for transferring files over LAN, using the WebRTC tech</td><td><a href="https://share.zackdk.com/" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/csm-kb" class="w3-hover-opacity">Kane</a></td><td><a href="https://github.com/csm-kb/vanjs-chartjs-example" class="w3-hover-opacity"><b>VanJS</b> Chart.js graph render</a></td><td><a href="https://codesandbox.io/p/devbox/github/csm-kb/vanjs-chartjs-example/tree/main/?file=%2Fsrc%2Fmain.ts" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/ndrean" class="w3-hover-opacity">Neven DREAN</a></td><td><a href="https://github.com/ndrean/vanjs-dialog-modal" class="w3-hover-opacity">Modal Component & Routing with <b>VanJS</b></a></td><td><a href="https://githubbox.com/ndrean/vanjs-dialog-modal" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/b-rad-c" class="w3-hover-opacity">b rad c</a></td><td><a href="https://github.com/vanjs-org/van/tree/main/addons/van_cone/examples/spa-app" class="w3-hover-opacity"><b>VanJS</b> SPA Template</a></td><td><a href="https://codesandbox.io/p/devbox/github/vanjs-org/van/tree/main/addons/van_cone/examples/spa-app" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/SirenkoVladd" class="w3-hover-opacity">Vlad Sirenko</a></td><td><a href="https://github.com/sirenkovladd/vanjs-leaflet-example" class="w3-hover-opacity"><b>VanJS</b> with Leaflet</a></td><td><a href="https://codesandbox.io/p/devbox/github/sirenkovladd/vanjs-leaflet-example/tree/main/?file=%2Fsrc%2Fmain.js" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/kangaroolab" class="w3-hover-opacity">kangaroolab</a></td><td><a href="https://github.com/kangaroolab/tippy" class="w3-hover-opacity">tippy: a local first note app</a></td><td><a href="https://kangaroolab.github.io/tippy/" class="w3-hover-opacity">link</a></td></tr><tr><td><a href="https://github.com/FredericHeem" class="w3-hover-opacity">FredericHeem</a></td><td><a href="https://github.com/FredericHeem/van-kit" class="w3-hover-opacity">Multi-Page App Starter Kit under 5kB</a></td><td></td></tr><tr><td><a href="https://github.com/FredericHeem" class="w3-hover-opacity">FredericHeem</a></td><td><a href="https://github.com/FredericHeem/van-playground" class="w3-hover-opacity"><b>VanJS</b> Playground with Vite</a></td><td></td></tr></tbody></table></div>
<aside id="toc"><ul><li><a href="#hello-world" class="w3-hover-opacity">Hello World!</a></li><li><a href="#dom-composition-and-manipulation" class="w3-hover-opacity">DOM Composition and Manipulation</a></li><li><a href="#counter" class="w3-hover-opacity">Counter</a></li><li><a href="#stopwatch" class="w3-hover-opacity">Stopwatch</a></li><li><a href="#blog" class="w3-hover-opacity">Blog</a></li><li><a href="#list" class="w3-hover-opacity">List</a></li><li><a href="#todo-list" class="w3-hover-opacity">TODO List</a></li><li><a href="#todo-app" class="w3-hover-opacity">A Fully Reactive TODO App</a></li><li><a href="#game" class="w3-hover-opacity">Fun Game: Emojis Pops</a></li><li><a href="#code-browser" class="w3-hover-opacity">SPA w/ Client-Side Routing: Code Browser</a></li><li><a href="#stargazers" class="w3-hover-opacity">Stargazers</a></li><li><a href="#epoch-timestamp-converter" class="w3-hover-opacity">Epoch Timestamp Converter</a></li><li><a href="#keyboard-event-inspector" class="w3-hover-opacity">Keyboard Event Inspector</a></li><li><a href="#diff" class="w3-hover-opacity">Diff</a></li><li><a href="#calculator" class="w3-hover-opacity">Calculator</a></li><li><a href="#table-viewer" class="w3-hover-opacity">Table-View Example: JSON/CSV Table Viewer</a></li><li><a href="#package-lock-inspector" class="w3-hover-opacity">package-lock.json Inspector</a></li><li><a href="#json-inspector" class="w3-hover-opacity">Tree-View Example: JSON Inspector</a></li><li><a href="#auto-complete" class="w3-hover-opacity">Textarea with Autocomplete</a></li><li><a href="#html-md-to-vanjs-code-converter" class="w3-hover-opacity">HTML/MD to VanJS Code Converter</a></li><li><a href="#jupyter-like-javascript-console" class="w3-hover-opacity">Jupyter-like JavaScript Console</a></li><li><a href="#an-improved-unix-terminal" class="w3-hover-opacity">An Improved Unix Terminal</a></li><li><a href="#community-examples" class="w3-hover-opacity">Community Examples</a></li></ul></aside>
</div>
</div>
<script>
// Script to open and close sidebar
const w3_open = () => {
document.getElementById("mySidebar").style.display = "block"
document.getElementById("myOverlay").style.display = "block"
}
const w3_close = () => {
document.getElementById("mySidebar").style.display = "none"
document.getElementById("myOverlay").style.display = "none"
}
const tocDom = document.getElementById("toc")
// Tracks the current toc item
const trackToc = () => {
const allHeadings = [...document.querySelectorAll("h2,h3")]
const currentHeadingIndex = allHeadings.findIndex(h => h.getBoundingClientRect().top >= 0)
let currentHeading
if (currentHeadingIndex < 0) currentHeading = allHeadings[allHeadings.length - 1]; else {
currentHeading = allHeadings[currentHeadingIndex]
if (currentHeadingIndex > 0 && currentHeading.getBoundingClientRect().top > innerHeight)
currentHeading = allHeadings[currentHeadingIndex - 1]
}
for (const e of document.querySelectorAll("#toc li a"))
if (e.href.split("#")[1] === currentHeading?.id) {
e.classList.add("current-heading")
const {top: tocTop, bottom: tocBottom} = tocDom.getBoundingClientRect()
const {top: eTop, bottom: eBottom} = e.getBoundingClientRect()
if (eBottom > tocBottom) tocDom.scrollTop += eBottom - tocBottom
else if (eTop < tocTop) tocDom.scrollTop -= tocTop - eTop
} else
e.classList.remove("current-heading")
}
trackToc()
document.addEventListener("scroll", trackToc)
addEventListener("resize", trackToc)
const copy = e => {
const file = e.previousElementSibling.innerText
const importLine = file.includes("nomodule") ?
`<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/vanjs-org/van/public/${file}"><\/script>` :
`import van from "https://cdn.jsdelivr.net/gh/vanjs-org/van/public/${file}"`
navigator.clipboard.writeText(importLine)
.then(() => e.querySelector(".tooltip").innerText = "Copied")
.catch(() => e.querySelector(".tooltip").innerText = "Copy failed")
}
const resetTooltip = e => e.querySelector(".tooltip").innerText = "Copy import line"
</script>
<script src="https://guru-widget.pages.dev/guru_widget.latest.min.js" data-text="Ask AI" data-link="https://gurubase.io/g/vanjs" data-bg-color="rgba(244, 67, 54, 0.3)" data-icon-url="/ask_ai.svg" data-font-color="#ffffff" data-margins="{"bottom": "1rem", "left": "1430px", "right": "unset"}">
</script>
<!-- Place this tag in your head or just before your close body tag. -->
<script async defer src="https://buttons.github.io/buttons.js"></script>
<link rel="prefetch" href="/code/prism-v1.js" as="script"><link rel="prefetch" href="https://www.gstatic.com/charts/loader.js" as="script"><link rel="prefetch" href="/code/diff.min.js" as="script"><link rel="prefetch" href="/code/van-1.5.2.nomodule.min.js" as="script"><link rel="prefetch" href="/code/van-x-0.6.1.nomodule.min.js" as="script"></body></html>