forked from RecoLabs/gnata
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayground.html
More file actions
1733 lines (1580 loc) · 80.3 KB
/
playground.html
File metadata and controls
1733 lines (1580 loc) · 80.3 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 lang="en" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>gnata-sqlite</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><text y='28' font-size='28'>G</text></svg>">
<link rel="preload" href="gnata.wasm" as="fetch" type="application/wasm">
<link href="https://fonts.googleapis.com/css2?family=Onest:wght@400;500;600;700&family=Poppins:wght@600;700&display=swap" rel="stylesheet">
<style>
:root { --font-mono: 'SF Mono', 'Fira Code', 'JetBrains Mono', 'Cascadia Code', monospace; }
/* -- TokyoNight Night -- */
[data-theme="dark"] {
--bg: #1a1b26; --surface: #1f2335; --surface-hover: rgba(255,255,255,0.04);
--text: #a9b1d6; --text-strong: #c0caf5;
--accent: #7aa2f7; --accent-dim: rgba(122,162,247,0.12); --accent-hover: #89b4fa; --accent-text: #1a1b26;
--green: #9ece6a; --green-dim: rgba(158,206,106,0.12);
--vista: #bb9af7; --orange: #ff9e64; --teal: #73daca;
--error: #f7768e; --muted: #565f89;
--border: #292e42; --border-light: #3b4261;
--cm-bg: #1a1b26; color-scheme: dark;
}
/* -- TokyoNight Day -- */
[data-theme="light"] {
--bg: #d5d6db; --surface: #e1e2e7; --surface-hover: rgba(0,0,0,0.04);
--text: #3760bf; --text-strong: #343b58;
--accent: #2e7de9; --accent-dim: rgba(46,125,233,0.10); --accent-hover: #1d4ed0; --accent-text: #ffffff;
--green: #587539; --green-dim: rgba(88,117,57,0.12);
--vista: #7847bd; --orange: #b15c00; --teal: #118c74;
--error: #c64343; --muted: #848cb5;
--border: #c4c8da; --border-light: #b6bfe2;
--cm-bg: #e1e2e7; color-scheme: light;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; overflow: hidden; }
body { font-family: 'Onest', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: var(--bg); color: var(--text); display: flex; flex-direction: column; transition: background 0.25s, color 0.25s; }
/* Header */
header { display: flex; align-items: center; gap: 12px; padding: 14px 24px; border-bottom: 1px solid var(--border); background: var(--surface); transition: background 0.25s; flex-shrink: 0; }
header h1 { font-size: 20px; font-weight: 700; letter-spacing: -0.3px; color: var(--text-strong); }
header h1 span { color: var(--green); font-family: 'Poppins', sans-serif; font-weight: 600; }
.header-links { margin-left: auto; display: flex; align-items: center; gap: 6px; }
.header-links a { font-size: 12px; font-weight: 500; color: var(--muted); text-decoration: none; padding: 5px 10px; border-radius: 6px; transition: all 0.15s; display: flex; align-items: center; gap: 5px; }
.header-links a:hover { color: var(--text-strong); background: var(--surface-hover); }
.header-links .sep { width: 1px; height: 16px; background: var(--border-light); margin: 0 2px; }
.theme-toggle { background: none; border: 1px solid var(--border-light); color: var(--muted); padding: 5px 8px; border-radius: 6px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.15s; line-height: 1; }
.theme-toggle:hover { color: var(--text-strong); border-color: var(--muted); background: var(--surface-hover); }
.theme-icon { display: flex; align-items: center; }
.status { font-size: 12px; display: flex; align-items: center; gap: 6px; color: var(--muted); padding-left: 8px; }
.status .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); transition: background 0.3s; }
.status.ready .dot { background: var(--green); }
.status.ready { color: var(--green); }
.progress-bar { position: fixed; top: 0; left: 0; height: 2px; background: var(--accent); width: 0%; transition: width 0.2s ease; z-index: 999; }
/* Mode tabs in header */
.mode-tabs { display: flex; gap: 0; margin-left: 4px; }
.mode-tab { font-family: 'Onest', sans-serif; font-size: 12px; font-weight: 600; padding: 6px 16px; background: none; border: 1px solid var(--border-light); color: var(--muted); cursor: pointer; transition: all 0.15s; border-radius: 0; }
.mode-tab:first-child { border-radius: 6px 0 0 6px; }
.mode-tab:last-child { border-radius: 0 6px 6px 0; border-left: none; }
.mode-tab.active { background: var(--accent-dim); color: var(--accent); border-color: var(--accent); }
.mode-tab:hover:not(.active) { color: var(--text); border-color: var(--muted); background: var(--surface-hover); }
/* Buttons */
button { font-family: 'Onest', inherit; font-size: 13px; font-weight: 600; padding: 8px 20px; border: none; border-radius: 6px; cursor: pointer; transition: all 0.15s; }
.btn-primary { background: var(--accent); color: var(--accent-text); }
.btn-primary:hover { background: var(--accent-hover); }
.btn-primary:disabled { opacity: 0.4; cursor: not-allowed; }
.btn-ghost { background: transparent; color: var(--muted); border: 1px solid var(--border-light); }
.btn-ghost:hover { color: var(--text); border-color: var(--muted); }
.btn-ghost.active { background: var(--accent-dim); color: var(--accent); border-color: var(--accent); }
kbd { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 12px; padding: 3px 7px; border-radius: 4px; margin-left: 8px; letter-spacing: 1px; }
.btn-primary kbd { background: rgba(255,255,255,0.2); color: var(--accent-text); }
.timing { font-size: 12px; font-family: var(--font-mono); color: var(--accent); }
.btn-generate { padding: 8px 18px; font-size: 12px; }
/* Layout */
.app { display: flex; flex-direction: column; flex: 1; overflow: hidden; min-height: 0; }
.mode-content { display: none; flex-direction: column; flex: 1; overflow: hidden; min-height: 0; }
.mode-content.active { display: flex; }
.toolbar { display: flex; align-items: center; gap: 10px; padding: 10px 16px; background: var(--surface); border-bottom: 1px solid var(--border); transition: background 0.25s; flex-wrap: wrap; flex-shrink: 0; }
.toolbar-label { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.8px; color: var(--muted); }
.toolbar-right { margin-left: auto; display: flex; align-items: center; gap: 10px; }
.toolbar .sep { width: 1px; height: 20px; background: var(--border-light); }
.gen-group { display: flex; gap: 0; }
.gen-group button { border-radius: 0; border: 1px solid var(--border-light); border-left: none; padding: 6px 14px; font-size: 12px; }
.gen-group button:first-child { border-radius: 6px 0 0 6px; border-left: 1px solid var(--border-light); }
.gen-group button:last-child { border-radius: 0 6px 6px 0; }
/* Query example bar */
.query-bar { display: flex; align-items: center; gap: 10px; padding: 7px 16px; background: var(--bg); border-bottom: 1px solid var(--border); overflow: hidden; flex-shrink: 0; }
.query-bar-label { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.8px; color: var(--muted); white-space: nowrap; flex-shrink: 0; }
.query-pills { display: flex; gap: 6px; overflow-x: auto; scrollbar-width: none; padding: 2px 0; }
.query-pills::-webkit-scrollbar { display: none; }
.query-pill { font-family: 'Onest', sans-serif; font-size: 12px; font-weight: 500; padding: 4px 14px; border-radius: 14px; border: 1px solid var(--border-light); background: transparent; color: var(--muted); cursor: pointer; transition: all 0.15s; white-space: nowrap; }
.query-pill:hover { color: var(--text); border-color: var(--muted); background: var(--surface-hover); }
.query-pill.active { background: var(--accent-dim); color: var(--accent); border-color: var(--accent); }
.panels { display: grid; grid-template-columns: 3fr 2fr; flex: 1; overflow: hidden; min-height: 0; position: relative; }
.panel-divider { width: 5px; cursor: col-resize; background: transparent; position: absolute; top: 0; bottom: 0; z-index: 10; transition: background 0.15s; }
.panel-divider:hover, .panel-divider.dragging { background: var(--accent); }
.panel-header { padding: 10px 16px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.8px; color: var(--muted); background: var(--surface); border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; }
/* SQL Editor */
.editor-panel { display: flex; flex-direction: column; border-right: 1px solid var(--border); overflow: hidden; min-height: 0; }
#sqlEditor { flex: 1; overflow: hidden; background: var(--cm-bg); }
#sqlEditor .cm-editor { height: 100%; background: transparent; }
#sqlEditor .cm-editor.cm-focused { outline: none; }
#sqlEditor .cm-scroller { font-family: var(--font-mono); font-size: 13px; overflow: auto !important; }
#sqlEditor .cm-gutters { background: var(--cm-bg); color: var(--muted); border-right: 1px solid var(--border); }
#sqlEditor .cm-activeLineGutter { background: transparent; }
#sqlEditor .cm-activeLine { background: var(--surface-hover) !important; }
/* Right panel with tabs */
.right-panel { display: flex; flex-direction: column; overflow: hidden; min-height: 0; }
.tab-bar { display: flex; background: var(--surface); border-bottom: 1px solid var(--border); padding: 0 8px; gap: 0; }
.tab { font-family: 'Onest', sans-serif; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.8px; padding: 10px 16px; background: none; border: none; border-bottom: 2px solid transparent; color: var(--muted); cursor: pointer; transition: all 0.15s; border-radius: 0; }
.tab:hover { color: var(--text); }
.tab.active { color: var(--accent); border-bottom-color: var(--accent); }
.tab-content { display: none; flex: 1; overflow: hidden; flex-direction: column; min-height: 0; }
.tab-content.active { display: flex; }
/* Schema */
.schema-content { padding: 16px; font-size: 13px; flex: 1; overflow: auto; }
.schema-content h3 { color: var(--accent); font-size: 13px; font-weight: 600; margin: 12px 0 6px 0; font-family: var(--font-mono); }
.schema-content h3:first-child { margin-top: 0; }
.schema-table { width: 100%; border-collapse: collapse; margin-bottom: 4px; }
.schema-table td { padding: 2px 8px; font-family: var(--font-mono); font-size: 12px; border-bottom: 1px solid var(--border); }
.schema-table td:first-child { color: var(--text-strong); font-weight: 500; }
.schema-table td:last-child { color: var(--muted); }
.schema-content .row-count { font-size: 11px; color: var(--muted); }
.schema-content pre { font-family: var(--font-mono); font-size: 12px; color: var(--text); background: var(--surface-hover); padding: 8px 12px; border-radius: 6px; overflow-x: auto; white-space: pre; }
.schema-content .muted { color: var(--muted); font-style: italic; }
/* Getting started */
.getting-started { padding: 24px 4px; }
.getting-started h3 { color: var(--text-strong); font-size: 14px; font-weight: 700; margin-bottom: 16px; font-family: 'Onest', sans-serif; }
.getting-started ol { font-size: 13px; color: var(--muted); padding-left: 20px; line-height: 1.8; }
.getting-started li { margin-bottom: 4px; }
.getting-started strong { color: var(--text-strong); font-weight: 600; }
/* Results */
.results-body { flex: 1; overflow: auto; min-height: 0; }
.results-table-wrap { overflow: auto; flex: 1; }
.results-table { width: 100%; border-collapse: collapse; font-family: var(--font-mono); font-size: 13px; }
.results-table thead { position: sticky; top: 0; z-index: 1; }
.results-table th { padding: 8px 12px; text-align: left; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; color: var(--accent); background: var(--surface); border-bottom: 1px solid var(--border); white-space: nowrap; }
.results-table td { padding: 6px 12px; border-bottom: 1px solid var(--border); color: var(--text); white-space: nowrap; max-width: 400px; overflow: hidden; text-overflow: ellipsis; }
.results-table tbody tr { cursor: pointer; }
.results-table tbody tr:hover { background: var(--surface-hover); }
.results-table tbody tr.focused { background: var(--accent-dim); }
.results-table tbody tr.focused:hover { background: var(--accent-dim); }
/* Row detail */
.row-detail { padding: 12px 16px; background: var(--surface); border-top: 1px solid var(--border); overflow: auto; min-height: 80px; max-height: 50vh; }
.row-detail-header { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.8px; color: var(--muted); margin-bottom: 8px; display: flex; align-items: center; justify-content: space-between; }
.row-detail-close { background: none; border: none; color: var(--muted); cursor: pointer; font-size: 16px; padding: 0 4px; line-height: 1; border-radius: 4px; }
.row-detail-close:hover { color: var(--text-strong); background: var(--surface-hover); }
.row-detail pre { font-family: var(--font-mono); font-size: 12px; color: var(--text); background: var(--bg); padding: 10px 14px; border-radius: 6px; overflow-x: auto; white-space: pre-wrap; word-break: break-all; }
.results-table .null-val { color: var(--muted); font-style: italic; }
.results-table .json-val { color: var(--vista); }
.results-table .num-val { color: var(--orange); }
.results-footer { padding: 8px 16px; font-size: 12px; color: var(--muted); background: var(--surface); border-top: 1px solid var(--border); display: flex; justify-content: space-between; flex-shrink: 0; }
.results-message { padding: 24px; text-align: center; color: var(--muted); font-size: 13px; }
.results-message.error { color: var(--error); text-align: left; padding: 16px; font-family: var(--font-mono); white-space: pre-wrap; }
/* Benchmark banner */
.bench-banner { padding: 14px 20px; background: var(--surface); border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 16px; flex-shrink: 0; }
.bench-title { font-size: 13px; font-weight: 600; color: var(--text-strong); }
.bench-title span { color: var(--muted); font-weight: 400; }
.bench-bar-track { flex: 1; max-width: 320px; height: 28px; background: var(--border); border-radius: 6px; overflow: hidden; position: relative; }
.bench-bar { height: 100%; border-radius: 6px; background: var(--green); display: flex; align-items: center; justify-content: flex-end; padding-right: 10px; font-size: 12px; font-weight: 700; color: var(--bg); min-width: 60px; transition: width 0.5s ease; }
.bench-tag { font-size: 11px; font-weight: 600; color: var(--green); background: var(--green-dim); padding: 3px 10px; border-radius: 10px; white-space: nowrap; }
/* Autocomplete */
.cm-tooltip-autocomplete { background: var(--surface) !important; border: 1px solid var(--border-light) !important; border-radius: 6px; }
.cm-tooltip-autocomplete ul li { color: var(--text); font-family: var(--font-mono); font-size: 13px; padding: 4px 10px; }
.cm-tooltip-autocomplete ul li[aria-selected] { background: var(--accent-dim) !important; color: var(--accent) !important; }
.cm-tooltip-autocomplete .cm-completionLabel { color: inherit; }
.cm-tooltip-autocomplete .cm-completionDetail { color: var(--muted); font-style: normal; margin-left: 8px; }
.cm-completionIcon { display: none; }
/* Spinner */
.spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid var(--border-light); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.6s linear infinite; vertical-align: middle; margin-right: 8px; }
@keyframes spin { to { transform: rotate(360deg); } }
/* ========== gnata (JSONata) mode ========== */
/* Expression bar */
.g-expr-bar { display: flex; align-items: stretch; border-bottom: 1px solid var(--border); background: var(--surface); flex-shrink: 0; }
.g-expr-bar .panel-header { border-bottom: none; border-right: 1px solid var(--border); min-width: 120px; }
#g-expression { flex: 1; overflow: hidden; background: var(--cm-bg); }
#g-expression .cm-editor { height: 100%; background: transparent; }
#g-expression .cm-editor.cm-focused { outline: none; }
#g-expression .cm-scroller { font-family: var(--font-mono); font-size: 14px; padding: 6px 12px; overflow-x: auto !important; }
#g-expression .cm-content { padding: 0; }
#g-expression .cm-line { padding: 0; }
#g-expression .cm-gutters { display: none; }
#g-expression .cm-activeLine { background: transparent !important; }
#g-expression .cm-selectionBackground { background: rgba(130,170,255,0.2) !important; }
.cm-focused .cm-selectionBackground { background: rgba(130,170,255,0.3) !important; }
/* Squiggly error underlines */
.cm-diagnostic-error { border-bottom: none; }
.cm-lintRange-error {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='6' height='3'%3E%3Cpath d='m0 3 l2 -2 l1 0 l2 2 l1 0' fill='none' stroke='%23f7768e' stroke-width='.7'/%3E%3C/svg%3E");
background-repeat: repeat-x;
background-position: bottom;
background-size: 6px 3px;
padding-bottom: 1px;
}
.cm-tooltip-lint { background: var(--surface); border: 1px solid var(--border-light); border-radius: 6px; color: var(--text); font-family: var(--font-mono); font-size: 12px; }
.cm-lint-marker { display: none; }
/* Hover tooltip */
.cm-tooltip-hover { background: var(--surface) !important; border: 1px solid var(--border-light) !important; border-radius: 6px; max-width: 480px; }
.cm-hover-tooltip { padding: 10px 14px; font-size: 13px; color: var(--text); line-height: 1.5; }
.cm-hover-tooltip strong { color: var(--accent); font-weight: 700; }
.cm-hover-tooltip code { font-family: var(--font-mono); font-size: 12px; background: var(--bg); padding: 1px 5px; border-radius: 3px; color: var(--green); }
.cm-hover-tooltip pre { font-family: var(--font-mono); font-size: 12px; background: var(--bg); padding: 8px 10px; border-radius: 4px; margin: 6px 0; color: var(--text); overflow-x: auto; }
.cm-hover-tooltip pre code { background: none; padding: 0; }
/* gnata panels */
.g-panels { display: grid; grid-template-columns: 1fr 1fr; flex: 1; overflow: hidden; min-height: 0; }
.g-panel { display: flex; flex-direction: column; overflow: hidden; min-height: 0; }
.g-panel:first-child { border-right: 1px solid var(--border); }
#g-input, #g-result { flex: 1; overflow: hidden; background: var(--cm-bg); }
#g-input .cm-editor, #g-result .cm-editor { height: 100%; background: transparent; }
#g-input .cm-editor.cm-focused, #g-result .cm-editor.cm-focused { outline: none; }
#g-input .cm-scroller, #g-result .cm-scroller { font-family: var(--font-mono); font-size: 13px; overflow: auto !important; }
#g-input .cm-gutters, #g-result .cm-gutters { display: none; }
#g-input .cm-activeLine, #g-result .cm-activeLine { background: transparent !important; }
#g-result .cm-cursor { display: none !important; }
#g-result .cm-content { cursor: default; }
#g-result.result-error .cm-editor .cm-content { color: var(--error); }
#g-result.result-success .cm-editor .cm-content { color: var(--green); }
@media (max-width: 768px) {
.panels { grid-template-columns: 1fr; }
.editor-panel { border-right: none; border-bottom: 1px solid var(--border); min-height: 200px; }
.toolbar { gap: 6px; }
.g-panels { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="progress-bar" id="progressBar"></div>
<header>
<h1><span>gnata-sqlite</span></h1>
<div class="mode-tabs">
<button class="mode-tab active" data-mode="sqlite">SQLite</button>
<button class="mode-tab" data-mode="gnata">gnata</button>
</div>
<div class="header-links">
<div class="status" id="status"><span class="dot"></span><span>Loading…</span></div>
<div class="sep"></div>
<a href="https://docs.jsonata.org/overview" target="_blank" rel="noopener">Docs</a>
<a href="https://docs.jsonata.org/string-functions" target="_blank" rel="noopener">Functions</a>
<div class="sep"></div>
<button class="theme-toggle" id="themeToggle" title="Toggle light/dark mode"><span class="theme-icon"></span></button>
</div>
</header>
<div class="app">
<!-- ========== SQLite Mode ========== -->
<div class="mode-content active" id="sqliteMode">
<div class="toolbar">
<button class="btn-primary" id="runBtn" disabled>Run<kbd>⌘↩</kbd></button>
<button class="btn-ghost" id="clearBtn">Clear</button>
<div class="sep"></div>
<span class="toolbar-label">Rows</span>
<div class="gen-group">
<button class="btn-ghost" data-count="1000">1K</button>
<button class="btn-ghost active" data-count="10000">10K</button>
<button class="btn-ghost" data-count="100000">100K</button>
<button class="btn-ghost" data-count="1000000">1M</button>
</div>
<button class="btn-primary btn-generate" id="generateBtn" disabled>Generate</button>
<span id="genHint" style="font-size:11px;color:var(--muted)">Generate fixture data</span>
<div class="toolbar-right">
<span id="timing" class="timing"></span>
</div>
</div>
<div class="query-bar">
<span class="query-bar-label">Examples</span>
<div class="query-pills" id="queryPills"></div>
</div>
<div class="panels" id="panels">
<div class="editor-panel">
<div class="panel-header">SQL Query</div>
<div id="sqlEditor"><div class="results-message"><span class="spinner"></span> Loading editor...</div></div>
</div>
<div class="panel-divider" id="panelDivider"></div>
<div class="right-panel">
<div class="tab-bar">
<button class="tab active" data-tab="results">Results</button>
<button class="tab" data-tab="schema">Schema</button>
</div>
<div class="tab-content active" id="resultsTab">
<div class="results-body" id="resultsBody">
<div class="results-message">Run a query to see results.</div>
</div>
<div id="rowDetail"></div>
<div class="results-footer" id="resultsFooter" style="display:none"></div>
</div>
<div class="tab-content" id="schemaTab">
<div class="schema-content" id="schemaInfo">
<div class="getting-started">
<h3>Getting Started</h3>
<ol>
<li>Select a dataset size (1K – 1M)</li>
<li>Click <strong>Generate</strong> to create test data</li>
<li>Choose an example query above</li>
<li>Press <strong>Run</strong> (⌘↩) to execute</li>
</ol>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ========== gnata (JSONata) Mode ========== -->
<div class="mode-content" id="gnataMode">
<div id="g-content" style="display:flex;flex-direction:column;flex:1;overflow:hidden;min-height:0;">
<div id="g-loading" class="results-message"><span class="spinner"></span> Loading gnata playground...</div>
<div id="g-loaded" style="display:none;flex-direction:column;flex:1;overflow:hidden;min-height:0;">
<div class="toolbar">
<button class="btn-primary" id="g-runBtn" disabled>Run<kbd>⌘↩</kbd></button>
<button class="btn-ghost" id="g-clearBtn">Clear</button>
<div class="toolbar-right">
<span id="g-timing" class="timing"></span>
</div>
</div>
<div class="query-bar">
<span class="query-bar-label">Examples</span>
<div class="query-pills" id="g-queryPills"></div>
</div>
<div class="g-expr-bar">
<div class="panel-header">Expression</div>
<div id="g-expression"></div>
</div>
<div class="g-panels">
<div class="g-panel">
<div class="panel-header">Input JSON</div>
<div id="g-input"></div>
</div>
<div class="g-panel">
<div class="panel-header">Result</div>
<div id="g-result"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ======== Web Worker source (not executed by browser) ======== -->
<script type="text/worker" id="workerSrc">
let db = null;
let gnataEval = null;
let _jqSampled = null;
let ready = false;
const pending = [];
self.onmessage = function(e) {
if (!ready && e.data.type !== 'init') { pending.push(e.data); return; }
handle(e.data);
};
async function handle(msg) {
try {
switch (msg.type) {
case 'init': await doInit(msg); break;
case 'generate': await doGenerate(msg); break;
case 'query': doQuery(msg); break;
}
} catch (err) {
postMessage({ type: 'error', msg: err.message });
}
}
async function doInit(msg) {
(new Function(msg.wasmExecText))();
const go = new Go();
const result = await WebAssembly.instantiate(msg.wasmBytes, go.importObject);
go.run(result.instance);
gnataEval = function() {
const r = self._gnataEval.apply(null, arguments);
if (r instanceof Error) throw r;
return r;
};
importScripts('https://cdn.jsdelivr.net/npm/sql.js@1/dist/sql-wasm.js');
const SQL = await initSqlJs({
locateFile: function(f) { return 'https://cdn.jsdelivr.net/npm/sql.js@1/dist/' + f; }
});
db = new SQL.Database();
db.create_function("jsonata", function(expr, jsonData) {
if (expr == null || jsonData == null) return null;
try {
const raw = gnataEval(String(expr), String(jsonData));
try {
const parsed = JSON.parse(raw);
if (typeof parsed === 'number') return parsed;
if (typeof parsed === 'boolean') return parsed ? 1 : 0;
if (parsed === null) return null;
if (typeof parsed === 'string') return parsed;
return raw;
} catch(e) { return raw; }
} catch(e) { return null; }
});
const JQ_CAP = 5000;
db.create_aggregate("jsonata_query", {
init: function() { return { expr: null, rows: [], total: 0 }; },
step: function(state, expr, data) {
if (expr == null || data == null) return state;
if (!state.expr) state.expr = String(expr);
state.total++;
if (state.rows.length < JQ_CAP) state.rows.push(String(data));
return state;
},
finalize: function(state) {
if (!state.expr || !state.rows.length) return null;
if (state.total > state.rows.length) {
_jqSampled = { sampled: state.rows.length, total: state.total };
}
try {
const arr = '[' + state.rows.join(',') + ']';
state.rows = null;
const raw = gnataEval(state.expr, arr);
try { const p = JSON.parse(raw); return typeof p === 'number' ? p : typeof p === 'string' ? p : raw; }
catch(e) { return raw; }
} catch(e) { return 'Error: ' + e.message; }
}
});
ready = true;
postMessage({ type: 'ready' });
while (pending.length) await handle(pending.shift());
}
async function doGenerate(msg) {
const count = msg.count;
const pools = msg.pools;
const statuses = ['pending','shipped','delivered','cancelled','returned'];
const cats = ['Electronics','Books','Clothing','Home','Sports','Food'];
const methods = ['standard','express','overnight','economy'];
let _seed = 12345;
const rng = function() { _seed = (_seed * 1664525 + 1013904223) & 0x7fffffff; return _seed / 0x7fffffff; };
const pick = function(a) { return a[Math.floor(rng() * a.length)]; };
const dateStart = new Date('2023-01-01').getTime();
const datePool = [];
for (let d = 0; d < 730; d++) datePool.push(new Date(dateStart + d * 86400000).toISOString().split('T')[0]);
postMessage({ type: 'progress', pct: 8, msg: 'Building data templates...' });
const POOL_SIZE = Math.min(count, 5000);
const dataPool = new Array(POOL_SIZE);
for (let p = 0; p < POOL_SIZE; p++) {
const ni = 1 + Math.floor(rng() * 4);
const items = [];
let sub = 0;
for (let j = 0; j < ni; j++) {
const price = Math.round((5 + rng() * 495) * 100) / 100;
const qty = 1 + Math.floor(rng() * 4);
items.push({ product: pick(pools.products), price: price, quantity: qty, category: pick(cats) });
sub += price * qty;
}
const sc = Math.round((3 + rng() * 22) * 100) / 100;
dataPool[p] = JSON.stringify({ items: items, shipping: { method: pick(methods), cost: sc, address: pick(pools.addresses) }, total: Math.round((sub + sc) * 100) / 100 });
}
db.run("DROP TABLE IF EXISTS orders");
db.run("DROP TABLE IF EXISTS customers");
db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT, city TEXT, country TEXT)");
db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, status TEXT, data JSON)");
const custCount = Math.min(count, 200);
db.run("BEGIN");
for (let i = 1; i <= custCount; i++) {
db.run("INSERT INTO customers VALUES (?,?,?,?,?)", [i, pools.names[i % pools.names.length], pools.emails[i % pools.emails.length], pools.cities[i % pools.cities.length], pools.countries[i % pools.countries.length]]);
}
db.run("COMMIT");
const BATCH = 25000;
const t0 = performance.now();
postMessage({ type: 'progress', pct: 10, msg: 'Inserting rows...' });
for (let batch = 0; batch < count; batch += BATCH) {
db.run("BEGIN");
const stmt = db.prepare("INSERT INTO orders VALUES (?,?,?,?,?)");
const end = Math.min(batch + BATCH, count);
for (let i = batch + 1; i <= end; i++) {
stmt.run([i, 1 + Math.floor(rng() * custCount), datePool[Math.floor(rng() * 730)], statuses[Math.floor(rng() * 5)], dataPool[i % POOL_SIZE]]);
}
stmt.free();
db.run("COMMIT");
postMessage({ type: 'progress', pct: Math.round((end / count) * 90) + 10, msg: 'Generated ' + end.toLocaleString() + ' of ' + count.toLocaleString() + ' rows...' });
}
const elapsed = ((performance.now() - t0) / 1000).toFixed(1);
postMessage({ type: 'generated', count: count, custCount: custCount, elapsed: elapsed });
}
function doQuery(msg) {
_jqSampled = null;
try {
const t0 = performance.now();
const res = db.exec(msg.sql);
const elapsed = performance.now() - t0;
const sampled = _jqSampled;
_jqSampled = null;
if (res.length) {
const last = res[res.length - 1];
postMessage({ type: 'queryResult', columns: last.columns, values: last.values.slice(0, 200), totalRows: last.values.length, time: elapsed, sampled: sampled });
} else {
postMessage({ type: 'queryResult', columns: [], values: [], totalRows: 0, time: elapsed, sampled: sampled, noRows: true });
}
} catch(e) {
const m = e.message || String(e);
postMessage({ type: 'queryError', msg: m });
}
}
</script>
<script>
// -- Theme --
const THEME_KEY = 'gnata-playground-theme';
const SUN_SVG = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>';
const MOON_SVG = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>';
function getPreferredTheme() {
const s = localStorage.getItem(THEME_KEY);
if (s) return s;
return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
}
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem(THEME_KEY, theme);
document.querySelector('.theme-icon').innerHTML = theme === 'dark' ? SUN_SVG : MOON_SVG;
}
applyTheme(getPreferredTheme());
document.getElementById('themeToggle').addEventListener('click', () => {
applyTheme(document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark');
if (window.switchCMTheme) window.switchCMTheme();
});
// -- Mode switching --
let currentMode = 'sqlite';
document.querySelectorAll('.mode-tab').forEach(tab => {
tab.addEventListener('click', () => {
const mode = tab.dataset.mode;
if (mode === currentMode) return;
currentMode = mode;
document.querySelectorAll('.mode-tab').forEach(t => t.classList.toggle('active', t.dataset.mode === mode));
document.querySelectorAll('.mode-content').forEach(c => c.classList.remove('active'));
document.getElementById(mode === 'sqlite' ? 'sqliteMode' : 'gnataMode').classList.add('active');
if (mode === 'gnata' && !window._gnataModeLaunched) {
window._gnataModeLaunched = true;
if (window._launchGnataMode) window._launchGnataMode();
}
});
});
// -- SQLite Tabs --
document.querySelectorAll('.tab-bar .tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.tab-bar .tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
tab.classList.add('active');
document.getElementById(tab.dataset.tab + 'Tab').classList.add('active');
});
});
function switchToTab(name) {
document.querySelectorAll('.tab-bar .tab').forEach(t => t.classList.toggle('active', t.dataset.tab === name));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
document.getElementById(name + 'Tab').classList.add('active');
}
// -- State --
const statusEl = document.getElementById('status');
const progressBar = document.getElementById('progressBar');
const runBtn = document.getElementById('runBtn');
const generateBtn = document.getElementById('generateBtn');
const timingEl = document.getElementById('timing');
window.getSql = () => '';
window.workerReady = false;
window.rowCount = 0;
let selectedCount = 10000;
function updateStatus(cls, text) {
statusEl.className = 'status' + (cls === 'ready' ? ' ready' : '');
statusEl.querySelector('span:last-child').textContent = text;
}
function escapeHtml(s) { return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
function fmtMs(ms) { return ms < 1 ? (ms * 1000).toFixed(0) + ' \u00b5s' : ms < 1000 ? ms.toFixed(1) + ' ms' : (ms / 1000).toFixed(2) + ' s'; }
// -- Generate row count selection --
document.querySelectorAll('.gen-group button').forEach(btn => {
btn.addEventListener('click', () => {
selectedCount = parseInt(btn.dataset.count);
document.querySelectorAll('.gen-group button').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
if (window.workerReady) generateBtn.disabled = false;
});
});
// -- Run / Clear (SQLite) --
runBtn.addEventListener('click', () => { if (window.runQuery) window.runQuery(); });
document.addEventListener('keydown', e => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
e.preventDefault();
if (currentMode === 'sqlite') {
if (window.runQuery) window.runQuery();
} else if (currentMode === 'gnata') {
if (window.gRunQuery) window.gRunQuery();
}
}
});
document.getElementById('clearBtn').addEventListener('click', () => {
document.getElementById('resultsBody').innerHTML = '<div class="results-message">Run a query to see results.</div>';
document.getElementById('resultsFooter').style.display = 'none';
document.getElementById('rowDetail').innerHTML = '';
timingEl.textContent = '';
});
// -- Resizable divider --
(function() {
const panels = document.getElementById('panels');
const divider = document.getElementById('panelDivider');
let dragging = false;
function positionDivider() {
const editorPanel = panels.querySelector('.editor-panel');
divider.style.left = (editorPanel.offsetWidth - 2) + 'px';
}
positionDivider();
divider.addEventListener('mousedown', function(e) {
e.preventDefault();
dragging = true;
divider.classList.add('dragging');
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
});
document.addEventListener('mousemove', function(e) {
if (!dragging) return;
const rect = panels.getBoundingClientRect();
const x = e.clientX - rect.left;
const pct = Math.max(20, Math.min(80, (x / rect.width) * 100));
panels.style.gridTemplateColumns = pct + '% 1fr';
positionDivider();
});
document.addEventListener('mouseup', function() {
if (!dragging) return;
dragging = false;
divider.classList.remove('dragging');
document.body.style.cursor = '';
document.body.style.userSelect = '';
});
new ResizeObserver(positionDivider).observe(panels);
})();
window._gnataModeLaunched = false;
</script>
<!-- ======== CodeMirror + Worker + Queries (SQLite mode) ======== -->
<script type="module">
try {
const progressBar = document.getElementById('progressBar');
const statusEl = document.getElementById('status');
progressBar.style.opacity = '1';
progressBar.style.width = '2%';
statusEl.querySelector('span:last-child').textContent = 'Loading editor...';
const { EditorView, keymap, lineNumbers } = await import('https://esm.sh/@codemirror/view@6');
progressBar.style.width = '8%';
const { EditorState, Compartment } = await import('https://esm.sh/@codemirror/state@6');
progressBar.style.width = '12%';
const { defaultKeymap, history, historyKeymap } = await import('https://esm.sh/@codemirror/commands@6');
progressBar.style.width = '16%';
const { syntaxHighlighting, HighlightStyle } = await import('https://esm.sh/@codemirror/language@6');
progressBar.style.width = '20%';
const { tags: t } = await import('https://esm.sh/@lezer/highlight@1');
progressBar.style.width = '24%';
const { sql, SQLite } = await import('https://esm.sh/@codemirror/lang-sql@6');
progressBar.style.width = '28%';
statusEl.querySelector('span:last-child').textContent = 'Editor ready, loading WASM...';
// -- CM Themes (TokyoNight Night / Day) --
const dark = { bg:'#1a1b26',fg:'#c0caf5',comment:'#565f89',string:'#9ece6a',number:'#ff9e64',keyword:'#bb9af7',func:'#7aa2f7',variable:'#9ece6a',operator:'#89ddff',error:'#f7768e',select:'#283457',cursor:'#c0caf5',property:'#73daca',bracket:'#698098' };
const light = { bg:'#e1e2e7',fg:'#3760bf',comment:'#848cb5',string:'#587539',number:'#b15c00',keyword:'#7847bd',func:'#2e7de9',variable:'#587539',operator:'#d20065',error:'#f52a65',select:'#b6bfe2',cursor:'#3760bf',property:'#118c74',bracket:'#848cb5' };
function isDark() { return document.documentElement.getAttribute('data-theme') !== 'light'; }
const themeComp = new Compartment();
function mkTheme(c, d) {
return EditorView.theme({
'&': { backgroundColor: c.bg, color: c.fg },
'.cm-content': { caretColor: c.cursor },
'.cm-cursor, .cm-dropCursor': { borderLeftColor: c.cursor },
'&.cm-focused .cm-selectionBackground, .cm-selectionBackground': { background: c.select + ' !important' },
'.cm-activeLine': { backgroundColor: d ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.04)' },
'.cm-gutters': { backgroundColor: c.bg, color: c.comment, borderRight: '1px solid ' + (d ? '#292e42' : '#c4c8da') },
'.cm-activeLineGutter': { backgroundColor: 'transparent' },
}, { dark: d });
}
function mkHL(c) {
return HighlightStyle.define([
{ tag: t.keyword, color: c.keyword, fontWeight: '600' },
{ tag: t.operator, color: c.operator },
{ tag: t.string, color: c.string },
{ tag: t.number, color: c.number },
{ tag: t.bool, color: c.number },
{ tag: t.null, color: c.comment },
{ tag: t.blockComment, color: c.comment },
{ tag: t.lineComment, color: c.comment },
{ tag: t.variableName, color: c.fg },
{ tag: t.typeName, color: c.func },
{ tag: t.function(t.variableName), color: c.func },
{ tag: t.special(t.variableName), color: c.variable },
{ tag: t.propertyName, color: c.property },
{ tag: t.paren, color: c.bracket },
{ tag: t.squareBracket, color: c.bracket },
{ tag: t.separator, color: c.comment },
]);
}
function themeExts() { const c = isDark() ? dark : light; return [mkTheme(c, isDark()), syntaxHighlighting(mkHL(c))]; }
window.switchCMTheme = () => {
sqlView.dispatch({ effects: themeComp.reconfigure(themeExts()) });
if (window._gSwitchCMTheme) window._gSwitchCMTheme();
};
// -- Queries --
const QUERIES = [
{
name: "Extract Fields",
sql: `-- jsonata() scalar: navigate nested JSON with dot paths
-- No json_extract() chains needed
SELECT id, status,
jsonata('items.product', data) as products,
jsonata('shipping.method', data) as ship_method,
jsonata('shipping.cost', data) as ship_cost
FROM orders LIMIT 20;`
},
{
name: "Per-Row Math",
sql: `-- Auto-mapping: items.(price * quantity) computes per-item then collects
-- $sum, $count work inline on nested arrays -- no subqueries needed
SELECT id, status,
jsonata('$round($sum(items.(price * quantity)), 2)', data) as subtotal,
jsonata('shipping.cost', data) as shipping,
jsonata('total', data) as total,
jsonata('$count(items)', data) as num_items,
jsonata('items[price > 200].product', data) as premium_items
FROM orders LIMIT 20;`
},
{
name: "Revenue by Status",
sql: `-- One jsonata_query per group computes all aggregates at once
-- Native gnata: single pass, O(1) memory, batch field extraction per group
SELECT status, count(*) as orders,
jsonata_query('{
"revenue": $round($sum(total), 2),
"avg": $round($average(total), 2),
"min": $min(total),
"max": $max(total)
}', data) as stats
FROM orders GROUP BY status ORDER BY orders DESC;`
},
{
name: "Dashboard",
sql: `-- One expression computes a full dashboard report
-- Native gnata: single pass, O(1) memory, batch field extraction
SELECT jsonata_query('{
"total_orders": $count($),
"total_revenue": $round($sum(total), 2),
"avg_order_value": $round($average(total), 2),
"min_order": $min(total),
"max_order": $max(total),
"avg_items": $round($average($map($, function($v){ $count($v.items) })), 2)
}', data) as dashboard
FROM orders;`
},
{
name: "Filtered Aggs",
sql: `-- $filter with lambdas: ClickHouse-style conditional aggregation
-- All filters in one expression -- native gnata shares identical predicates
SELECT jsonata_query('{
"total_orders": $count($),
"high_value_revenue": $round($sum($filter($, function($v){$v.total > 500}).total), 2),
"high_value_count": $count($filter($, function($v){$v.total > 500})),
"small_orders": $count($filter($, function($v){$v.total <= 100})),
"avg_mid_plus": $round($average($filter($, function($v){$v.total > 200}).total), 2)
}', data) as report
FROM orders;`
},
{
name: "Top Customers",
sql: `-- SQL JOIN for relational work + gnata for JSON aggregation
SELECT c.name, c.city,
count(*) as orders,
jsonata_query('{
"spent": $round($sum(total), 2),
"avg": $round($average(total), 2),
"biggest": $max(total)
}', data) as stats
FROM orders o
JOIN customers c ON c.id = o.customer_id
GROUP BY c.id ORDER BY orders DESC LIMIT 15;`
},
{
name: "Category Stats",
sql: `-- Aggregation across nested arrays
-- items.category reaches into every order's items array automatically
SELECT jsonata_query('{
"unique_categories": $count($distinct(items.category)),
"total_quantity_sold": $sum(items.quantity),
"avg_items_per_order": $round($average($map($, function($v){ $count($v.items) })), 2),
"unique_products": $count($distinct(items.product))
}', data) as stats
FROM orders;`
},
{
name: "Multi-Column",
sql: `-- Multi-column: combine data from different tables in one expression
-- Native extension supports key-value pairs directly:
-- jsonata(expr, 'name', c.name, 'city', c.city, 'data', o.data)
-- Playground uses json_object() to achieve the same result:
SELECT jsonata(
'name & " (" & city & ") \u2014 $" & $string(data.total) & " via " & data.shipping.method',
json_object('name', c.name, 'city', c.city, 'data', o.data)
) as summary,
jsonata(
'{"customer": name, "email": email, "items": $count(data.items), "total": data.total}',
json_object('name', c.name, 'email', c.email, 'data', o.data)
) as detail
FROM orders o
JOIN customers c ON c.id = o.customer_id
LIMIT 15;`
},
{
name: "String Transforms",
sql: `-- String functions: $uppercase, $lowercase, $join, $substring, &
-- Applied per-row as scalar transforms on nested JSON
SELECT id,
jsonata('$uppercase(items[0].product)', data) as first_product_upper,
jsonata('$join(items.category, ", ")', data) as categories,
jsonata('$uppercase(shipping.method) & " (" & $string(shipping.cost) & ")"', data)
as shipping_label,
jsonata('$substring(shipping.address, 0, 25) & "..."', data) as short_addr
FROM orders LIMIT 15;`
},
{
name: "Monthly Revenue",
sql: `-- SQL GROUP BY month + single gnata expression per group
SELECT substr(order_date, 1, 7) as month,
count(*) as orders,
jsonata_query('{
"revenue": $round($sum(total), 2),
"avg": $round($average(total), 2),
"peak": $max(total)
}', data) as stats
FROM orders GROUP BY month ORDER BY month;`
}
];
// -- SQL Editor --
document.getElementById('sqlEditor').innerHTML = '';
const sqlView = new EditorView({
state: EditorState.create({
doc: QUERIES[0].sql,
extensions: [
lineNumbers(),
keymap.of([...defaultKeymap, ...historyKeymap]),
history(),
sql({ dialect: SQLite }),
themeComp.of(themeExts()),
EditorView.domEventHandlers({
keydown(e) {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); if (window.runQuery) window.runQuery(); return true; }
}
}),
],
}),
parent: document.getElementById('sqlEditor'),
});
window.getSql = () => sqlView.state.doc.toString();
let activeQueryIdx = 0;
function loadQuery(idx) {
const q = QUERIES[idx];
if (!q) return;
activeQueryIdx = idx;
sqlView.dispatch({ changes: { from: 0, to: sqlView.state.doc.length, insert: q.sql } });
document.querySelectorAll('#queryPills .query-pill').forEach((p, i) => p.classList.toggle('active', i === idx));
}
// Build query pills
const pillsEl = document.getElementById('queryPills');
QUERIES.forEach((q, i) => {
const btn = document.createElement('button');
btn.className = 'query-pill' + (i === 0 ? ' active' : '');
btn.textContent = q.name;
btn.addEventListener('click', () => loadQuery(i));
pillsEl.appendChild(btn);
});
// -- Web Worker --
updateStatus('', 'Loading WASM...');
progressBar.style.width = '30%';
const [wasmExecText, wasmBytes] = await Promise.all([
fetch('wasm_exec.js').then(r => r.text()),
(async () => {
const resp = await fetch('gnata.wasm');
const total = parseInt(resp.headers.get('content-length') || '0', 10);
let loaded = 0;
const chunks = [];
const reader = resp.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
loaded += value.byteLength;
if (total > 0) progressBar.style.width = (30 + Math.min(25, (loaded / total) * 25)) + '%';
}
const buf = new Uint8Array(loaded);
let off = 0;
for (const c of chunks) { buf.set(c, off); off += c.byteLength; }
return buf.buffer;
})()
]);
progressBar.style.width = '55%';
updateStatus('', 'Starting worker...');
const workerSrc = document.getElementById('workerSrc').textContent;
const blob = new Blob([workerSrc], { type: 'application/javascript' });
const worker = new Worker(URL.createObjectURL(blob));
worker.postMessage({ type: 'init', wasmExecText, wasmBytes }, [wasmBytes]);
worker.onmessage = function(e) {
const msg = e.data;
if (msg.type === 'ready') {
window.workerReady = true;
updateStatus('ready', 'Ready');
progressBar.style.width = '100%';
setTimeout(() => { progressBar.style.opacity = '0'; }, 300);
runBtn.disabled = false;
if (selectedCount) generateBtn.disabled = false;
}
else if (msg.type === 'progress') {
progressBar.style.opacity = '1';
progressBar.style.width = msg.pct + '%';
updateStatus('', msg.msg);
}
else if (msg.type === 'generated') {
window.rowCount = msg.count;
document.getElementById('genHint').style.display = 'none';
updateStatus('ready', msg.count.toLocaleString() + ' orders, ' + msg.custCount + ' customers (' + msg.elapsed + 's)');
progressBar.style.width = '100%';
setTimeout(() => { progressBar.style.opacity = '0'; }, 300);
updateSchema(msg.count, msg.custCount);
generateBtn.disabled = false;
runBtn.disabled = false;
window.runQuery();
}
else if (msg.type === 'queryResult') {
renderResult(msg);