-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathswipe.html
More file actions
1419 lines (1204 loc) · 64.1 KB
/
swipe.html
File metadata and controls
1419 lines (1204 loc) · 64.1 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">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Neural Swipe Typing - Enhanced Demo</title>
<script src="https://cdn.tailwindcss.com"></script>
<!-- ONNX Runtime Web -->
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/ort.min.js"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
'dark-bg': '#0a0a0f',
'dark-surface': '#141420',
'dark-key': '#1a1a2e',
'dark-key-hover': '#252540',
'neon-blue': '#00d4ff',
'neon-purple': '#b300ff',
'neon-pink': '#ff00d4',
'neon-green': '#00ff88',
},
animation: {
'glow': 'glow 2s ease-in-out infinite',
'pulse-neon': 'pulse-neon 1.5s ease-in-out infinite',
}
}
}
}
</script>
<style>
@keyframes glow {
0%, 100% { box-shadow: 0 0 20px rgba(0, 212, 255, 0.5); }
50% { box-shadow: 0 0 30px rgba(179, 0, 255, 0.8); }
}
@keyframes pulse-neon {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
.neon-trail {
filter: drop-shadow(0 0 6px currentColor) drop-shadow(0 0 12px currentColor);
}
.key-active {
background: linear-gradient(135deg, #00d4ff, #b300ff) !important;
box-shadow: 0 0 20px rgba(0, 212, 255, 0.8), inset 0 0 20px rgba(179, 0, 255, 0.3);
transform: scale(0.95);
}
.loading-spinner {
border: 3px solid rgba(0, 212, 255, 0.1);
border-top: 3px solid #00d4ff;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.debug-overlay {
font-family: 'Courier New', monospace;
text-shadow: 0 0 5px rgba(0, 212, 255, 0.8);
}
* {
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
-webkit-tap-highlight-color: transparent;
}
.dropdown-content {
display: none;
position: absolute;
background: #1a1a2e;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
margin-top: 4px;
z-index: 1000;
}
.dropdown-content.show {
display: block;
}
.trail-data-input {
user-select: text;
-webkit-user-select: text;
}
.playback-dot {
position: absolute;
width: 12px;
height: 12px;
background: radial-gradient(circle, #00ff88, transparent);
border-radius: 50%;
pointer-events: none;
transform: translate(-50%, -50%);
box-shadow: 0 0 15px #00ff88;
}
</style>
</head>
<body class="bg-gradient-to-br from-dark-bg via-gray-900 to-dark-bg min-h-screen flex flex-col overflow-hidden">
<!-- Header -->
<div class="bg-dark-surface/80 backdrop-blur-xl border-b border-white/10">
<div class="p-4 text-center">
<h1 class="text-2xl font-bold bg-gradient-to-r from-neon-blue to-neon-purple bg-clip-text text-transparent">
Neural Swipe Typing - Enhanced
</h1>
<p class="text-gray-400 text-sm mt-1">
<span id="modelStatus">Models not loaded</span>
</p>
</div>
</div>
<!-- Status Bar -->
<div class="bg-dark-surface/60 backdrop-blur px-4 py-3 flex justify-between items-center border-b border-white/5">
<div class="flex items-center gap-3">
<div class="flex items-center gap-2">
<div id="statusIndicator" class="w-2 h-2 bg-gray-500 rounded-full"></div>
<span id="statusText" class="text-gray-300 text-sm">Ready</span>
</div>
<div id="coordinateDisplay" class="text-xs text-neon-blue font-mono hidden">
X: <span id="xCoord">0</span> Y: <span id="yCoord">0</span> |
Norm: <span id="normCoords">0.00, 0.00</span>
</div>
</div>
<div class="flex gap-2">
<!-- Model Load Button with Dropdown -->
<div class="relative">
<button id="modelLoadBtn" onclick="toggleModelDropdown()"
class="px-4 py-1.5 rounded-lg bg-gradient-to-r from-neon-blue/20 to-neon-purple/20 hover:from-neon-blue/30 hover:to-neon-purple/30 border border-neon-blue/30 text-white text-sm transition-all flex items-center gap-2">
Load Model
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
</svg>
</button>
<div id="modelDropdown" class="dropdown-content">
<button onclick="loadDefaultModels()" class="w-full px-4 py-2 text-left text-gray-300 hover:bg-white/10 text-sm">Default Models</button>
<button onclick="showCustomModelUpload()" class="w-full px-4 py-2 text-left text-gray-300 hover:bg-white/10 text-sm">Upload Custom</button>
</div>
</div>
<button onclick="clearInput()"
class="px-4 py-1.5 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 text-gray-300 text-sm transition-all hover:border-neon-blue/50">
Clear
</button>
<button onclick="toggleDebug()"
class="px-4 py-1.5 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 text-gray-300 text-sm transition-all hover:border-neon-purple/50">
Debug: <span id="debugStatus">OFF</span>
</button>
</div>
</div>
<!-- Trail Animation Controls -->
<div class="bg-dark-surface/40 backdrop-blur px-4 py-3 border-b border-white/5">
<div class="flex items-center gap-4 flex-wrap">
<div class="text-gray-400 text-xs uppercase tracking-wide">Trail Playback</div>
<div class="flex gap-2">
<button onclick="showTrailInput()"
class="px-3 py-1 rounded bg-neon-green/20 hover:bg-neon-green/30 border border-neon-green/30 text-white text-sm transition-all">
Import Trail Data
</button>
<input type="file" id="trailFileInput" accept=".json,.jsonl" style="display: none;" onchange="handleTrailFile(this)">
<button onclick="document.getElementById('trailFileInput').click()"
class="px-3 py-1 rounded bg-white/5 hover:bg-white/10 border border-white/10 text-gray-300 text-sm transition-all">
Upload File
</button>
</div>
<div id="trailControls" class="hidden flex gap-2 items-center">
<select id="wordSelector" class="bg-dark-key text-white px-3 py-1 rounded text-sm border border-white/10">
<option value="all">All Words</option>
</select>
<button onclick="playTrail()" id="playBtn"
class="px-3 py-1 rounded bg-neon-green/20 hover:bg-neon-green/30 border border-neon-green/30 text-white text-sm transition-all flex items-center gap-1">
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
<path d="M5 4v12l10-6z"/>
</svg>
Play
</button>
<button onclick="stopTrail()" id="stopBtn" class="hidden px-3 py-1 rounded bg-red-500/20 hover:bg-red-500/30 border border-red-500/30 text-white text-sm transition-all">
Stop
</button>
<span class="text-gray-400 text-sm">Speed:
<input type="range" id="playbackSpeed" min="0.5" max="3" step="0.5" value="1" class="w-20">
<span id="speedValue">1x</span>
</span>
</div>
</div>
</div>
<!-- Trail Data Input Modal -->
<div id="trailInputModal" class="hidden fixed inset-0 bg-black/75 backdrop-blur flex items-center justify-center z-50 p-4">
<div class="bg-dark-surface rounded-xl p-6 max-w-2xl w-full max-h-[80vh] overflow-auto">
<h3 class="text-white text-lg mb-4">Import Trail Data</h3>
<div class="mb-4">
<label class="text-gray-400 text-sm block mb-2">Paste JSON/JSONL data or enter URL:</label>
<textarea id="trailDataInput"
class="trail-data-input w-full h-32 bg-dark-key text-white p-3 rounded border border-white/10 font-mono text-sm"
placeholder='[{"t": 1234567890, "x": 0.5, "y": 0.5}, ...]'></textarea>
</div>
<div class="flex justify-end gap-2">
<button onclick="closeTrailInput()"
class="px-4 py-2 rounded bg-white/5 hover:bg-white/10 border border-white/10 text-gray-300 text-sm">
Cancel
</button>
<button onclick="processTrailData()"
class="px-4 py-2 rounded bg-neon-green/20 hover:bg-neon-green/30 border border-neon-green/30 text-white text-sm">
Load Data
</button>
</div>
</div>
</div>
<!-- Custom Model Upload Modal -->
<div id="customModelModal" class="hidden fixed inset-0 bg-black/75 backdrop-blur flex items-center justify-center z-50 p-4">
<div class="bg-dark-surface rounded-xl p-6 max-w-md w-full">
<h3 class="text-white text-lg mb-4">Upload Custom ONNX Models</h3>
<div class="space-y-4">
<div>
<label class="text-gray-400 text-sm block mb-2">Encoder Model (.onnx):</label>
<input type="file" id="encoderFile" accept=".onnx" class="text-white text-sm">
</div>
<div>
<label class="text-gray-400 text-sm block mb-2">Decoder Model (.onnx):</label>
<input type="file" id="decoderFile" accept=".onnx" class="text-white text-sm">
</div>
<div>
<label class="text-gray-400 text-sm block mb-2">Tokenizer Config (.json):</label>
<input type="file" id="tokenizerFile" accept=".json" class="text-white text-sm">
</div>
</div>
<div class="flex justify-end gap-2 mt-6">
<button onclick="closeCustomModelModal()"
class="px-4 py-2 rounded bg-white/5 hover:bg-white/10 border border-white/10 text-gray-300 text-sm">
Cancel
</button>
<button onclick="loadCustomModels()"
class="px-4 py-2 rounded bg-neon-purple/20 hover:bg-neon-purple/30 border border-neon-purple/30 text-white text-sm">
Load Models
</button>
</div>
</div>
</div>
<!-- Input Display -->
<div class="bg-dark-surface/40 backdrop-blur px-4 py-2 min-h-[50px]">
<div class="text-gray-400 text-xs uppercase tracking-wide mb-1">Input Text</div>
<div id="inputText" class="text-white text-lg min-h-[25px]"></div>
</div>
<!-- Word Suggestions -->
<div id="suggestions" class="px-4 py-3 flex gap-2 flex-wrap bg-dark-surface/40 backdrop-blur min-h-[60px]">
<div class="text-gray-500 text-sm">Load model to begin</div>
</div>
<!-- Debug Output -->
<div id="debugOutput" class="hidden px-4 py-2 bg-black/50 backdrop-blur max-h-32 overflow-auto">
<pre id="debugText" class="text-xs text-neon-blue font-mono"></pre>
</div>
<!-- Debug Overlay -->
<div id="debugOverlay" class="absolute top-32 left-2 pointer-events-none z-20 hidden">
<div class="text-xs text-neon-blue debug-overlay bg-black/70 p-2 rounded">
<div>Current Key: <span id="currentKeyDebug">-</span></div>
<div>Path Length: <span id="pathLength">0</span></div>
<div>Keys Touched: <span id="keysTouched">-</span></div>
</div>
</div>
<!-- Loading Overlay -->
<div id="loadingOverlay" class="hidden fixed inset-0 bg-black/75 backdrop-blur flex items-center justify-center z-50">
<div class="text-center">
<div class="loading-spinner mx-auto mb-4"></div>
<p class="text-white">Loading ONNX models...</p>
<p id="loadingDetails" class="text-gray-400 text-sm mt-2"></p>
</div>
</div>
<!-- Keyboard Container -->
<div class="flex-grow flex items-end pb-safe">
<div class="w-full max-w-2xl mx-auto">
<div class="relative bg-dark-surface/90 backdrop-blur-xl rounded-t-3xl p-3 shadow-2xl border-t border-white/10">
<!-- Canvas for swipe trail -->
<canvas id="swipeCanvas" class="absolute inset-0 z-10"></canvas>
<!-- Playback dot for animation -->
<div id="playbackDot" class="playback-dot hidden"></div>
<!-- Keyboard -->
<div class="space-y-2" id="keyboard">
<!-- Row 1: QWERTYUIOP -->
<div class="flex justify-center gap-1.5 px-1">
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="q" data-row="0" data-col="0">Q</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="w" data-row="0" data-col="1">W</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="e" data-row="0" data-col="2">E</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="r" data-row="0" data-col="3">R</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="t" data-row="0" data-col="4">T</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="y" data-row="0" data-col="5">Y</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="u" data-row="0" data-col="6">U</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="i" data-row="0" data-col="7">I</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="o" data-row="0" data-col="8">O</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="p" data-row="0" data-col="9">P</button>
</div>
<!-- Row 2: ASDFGHJKL -->
<div class="flex justify-center gap-1.5 px-6">
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="a" data-row="1" data-col="0">A</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="s" data-row="1" data-col="1">S</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="d" data-row="1" data-col="2">D</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="f" data-row="1" data-col="3">F</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="g" data-row="1" data-col="4">G</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="h" data-row="1" data-col="5">H</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="j" data-row="1" data-col="6">J</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="k" data-row="1" data-col="7">K</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="l" data-row="1" data-col="8">L</button>
</div>
<!-- Row 3: Shift + ZXCVBNM + Backspace -->
<div class="flex justify-center gap-1.5 px-1">
<button class="key w-14 h-12 bg-gray-800 hover:bg-gray-700 rounded-lg text-gray-400 text-sm transition-all border border-white/5" data-key="shift">⇧</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="z" data-row="2" data-col="1">Z</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="x" data-row="2" data-col="2">X</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="c" data-row="2" data-col="3">C</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="v" data-row="2" data-col="4">V</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="b" data-row="2" data-col="5">B</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="n" data-row="2" data-col="6">N</button>
<button class="key flex-1 h-12 bg-dark-key hover:bg-dark-key-hover rounded-lg text-white text-xl font-light transition-all border border-white/5" data-key="m" data-row="2" data-col="7">M</button>
<button class="key w-14 h-12 bg-gray-800 hover:bg-gray-700 rounded-lg text-gray-400 text-sm transition-all border border-white/5" data-key="backspace" onclick="handleBackspace()">⌫</button>
</div>
<!-- Row 4: Special keys -->
<div class="flex justify-center gap-1.5 px-1">
<button class="w-16 h-12 bg-gray-800 hover:bg-gray-700 rounded-lg text-gray-400 text-sm transition-all border border-white/5">123</button>
<button class="w-12 h-12 bg-gray-800 hover:bg-gray-700 rounded-lg text-gray-400 text-sm transition-all border border-white/5">😊</button>
<button class="flex-1 h-12 bg-gray-800 hover:bg-gray-700 rounded-lg text-gray-400 text-sm transition-all border border-white/5" onclick="handleSpace()">space</button>
<button class="w-20 h-12 bg-gradient-to-r from-neon-blue/20 to-neon-purple/20 hover:from-neon-blue/30 hover:to-neon-purple/30 rounded-lg text-white text-sm transition-all border border-neon-blue/30">return</button>
</div>
</div>
</div>
</div>
</div>
<script>
// Configuration
const NORMALIZED_WIDTH = 360;
const NORMALIZED_HEIGHT = 215;
const MAX_SEQUENCE_LENGTH = 150;
const DEBUG = { enabled: false };
// Model variables
let encoderSession = null;
let decoderSession = null;
let tokenizer = null;
let isModelReady = false;
// Trail animation variables
let trailData = [];
let playbackAnimation = null;
let currentTrailIndex = 0;
// Canvas setup
const canvas = document.getElementById('swipeCanvas');
const ctx = canvas.getContext('2d');
// Swipe tracking
let isDrawing = false;
let swipePath = [];
let keySequence = [];
let currentKey = null;
let keyboardBounds = null;
let inputText = '';
// Initialize canvas and keyboard (but not models)
function init() {
resizeCanvas();
updateKeyboardBounds();
window.addEventListener('resize', () => {
resizeCanvas();
updateKeyboardBounds();
});
// Update playback speed display
document.getElementById('playbackSpeed').addEventListener('input', (e) => {
document.getElementById('speedValue').textContent = e.target.value + 'x';
});
}
// Model loading functions
function toggleModelDropdown() {
const dropdown = document.getElementById('modelDropdown');
dropdown.classList.toggle('show');
// Close dropdown when clicking outside
setTimeout(() => {
document.addEventListener('click', closeDropdowns);
}, 100);
}
function closeDropdowns(e) {
if (!e.target.closest('#modelLoadBtn')) {
document.getElementById('modelDropdown').classList.remove('show');
document.removeEventListener('click', closeDropdowns);
}
}
function loadDefaultModels() {
document.getElementById('modelDropdown').classList.remove('show');
loadModels();
}
function showCustomModelUpload() {
document.getElementById('modelDropdown').classList.remove('show');
document.getElementById('customModelModal').classList.remove('hidden');
}
function closeCustomModelModal() {
document.getElementById('customModelModal').classList.add('hidden');
}
async function loadCustomModels() {
const encoderFile = document.getElementById('encoderFile').files[0];
const decoderFile = document.getElementById('decoderFile').files[0];
const tokenizerFile = document.getElementById('tokenizerFile').files[0];
if (!encoderFile || !decoderFile) {
alert('Please select both encoder and decoder ONNX files');
return;
}
try {
document.getElementById('loadingOverlay').classList.remove('hidden');
updateLoadingStatus('Loading custom models...');
// Configure ONNX Runtime
if (typeof ort !== 'undefined') {
ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/';
}
// Load tokenizer if provided
if (tokenizerFile) {
const tokenizerText = await tokenizerFile.text();
tokenizer = JSON.parse(tokenizerText);
}
// Load custom models
const sessionOptions = {
executionProviders: ['wasm'],
graphOptimizationLevel: 'all'
};
const encoderArrayBuffer = await encoderFile.arrayBuffer();
encoderSession = await ort.InferenceSession.create(encoderArrayBuffer, sessionOptions);
const decoderArrayBuffer = await decoderFile.arrayBuffer();
decoderSession = await ort.InferenceSession.create(decoderArrayBuffer, sessionOptions);
isModelReady = true;
closeCustomModelModal();
hideLoadingOverlay();
updateStatus('Custom models loaded', 'success');
document.getElementById('suggestions').innerHTML = '<div class="text-gray-500 text-sm">Swipe on the keyboard to begin</div>';
} catch (error) {
console.error('Error loading custom models:', error);
updateStatus('Custom model loading failed', 'error');
hideLoadingOverlay();
alert('Failed to load custom models: ' + error.message);
}
}
// Original loadModels function (for default models)
async function loadModels() {
try {
document.getElementById('loadingOverlay').classList.remove('hidden');
updateLoadingStatus('Initializing ONNX Runtime...');
if (typeof ort !== 'undefined') {
ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.18.0/dist/';
console.log('ONNX Runtime initialized');
} else {
throw new Error('ONNX Runtime not loaded');
}
updateLoadingStatus('Loading tokenizer...');
const tokenizerResponse = await fetch('models/tokenizer_config.json');
tokenizer = await tokenizerResponse.json();
updateLoadingStatus('Loading encoder model...');
const sessionOptions = {
executionProviders: ['wasm'],
graphOptimizationLevel: 'all'
};
encoderSession = await ort.InferenceSession.create('models/swipe_model_character_quant.onnx', sessionOptions);
updateLoadingStatus('Loading decoder model...');
decoderSession = await ort.InferenceSession.create('models/swipe_decoder_character_quant.onnx', sessionOptions);
isModelReady = true;
hideLoadingOverlay();
updateStatus('Ready', 'success');
document.getElementById('suggestions').innerHTML = '<div class="text-gray-500 text-sm">Swipe on the keyboard to begin</div>';
} catch (error) {
console.error('Error loading models:', error);
updateStatus('Model loading failed', 'error');
hideLoadingOverlay();
document.getElementById('suggestions').innerHTML = `<div class="text-red-500 p-2">Error loading models: ${error.message}</div>`;
}
}
// Trail data handling functions
function showTrailInput() {
document.getElementById('trailInputModal').classList.remove('hidden');
}
function closeTrailInput() {
document.getElementById('trailInputModal').classList.add('hidden');
document.getElementById('trailDataInput').value = '';
}
async function handleTrailFile(input) {
const file = input.files[0];
if (!file) return;
try {
const text = await file.text();
parseTrailData(text);
} catch (error) {
alert('Error reading file: ' + error.message);
}
}
async function processTrailData() {
const input = document.getElementById('trailDataInput').value.trim();
if (!input) {
alert('Please enter trail data');
return;
}
// Check if it's a URL
if (input.startsWith('http://') || input.startsWith('https://')) {
try {
const response = await fetch(input);
const text = await response.text();
parseTrailData(text);
} catch (error) {
alert('Error fetching URL: ' + error.message);
}
} else {
parseTrailData(input);
}
}
function parseTrailData(text) {
try {
let data;
// Try to parse as JSONL first
if (text.includes('\n') && !text.trim().startsWith('[')) {
const lines = text.split('\n').filter(line => line.trim());
data = [];
for (const line of lines) {
try {
const parsed = JSON.parse(line);
if (Array.isArray(parsed)) {
data = data.concat(parsed);
} else {
data.push(parsed);
}
} catch (e) {
console.warn('Skipping invalid JSONL line:', line);
}
}
} else {
// Parse as JSON
data = JSON.parse(text);
}
// Process trail data
const trails = extractTrails(data);
if (trails.length === 0) {
alert('No valid trail data found. Expected array with objects containing t, x, and y values.');
return;
}
trailData = trails;
updateTrailControls();
closeTrailInput();
} catch (error) {
alert('Error parsing data: ' + error.message);
}
}
function extractTrails(data) {
const trails = [];
function extractFromObject(obj) {
if (Array.isArray(obj)) {
// Check if this array contains trail points
if (obj.length > 0 && obj[0].hasOwnProperty('t') &&
obj[0].hasOwnProperty('x') && obj[0].hasOwnProperty('y')) {
// Validate equal lengths
const hasAllFields = obj.every(p =>
p.hasOwnProperty('t') && p.hasOwnProperty('x') && p.hasOwnProperty('y')
);
if (hasAllFields) {
trails.push(obj);
}
} else {
// Recursively check array elements
obj.forEach(item => extractFromObject(item));
}
} else if (typeof obj === 'object' && obj !== null) {
// Recursively check object values
Object.values(obj).forEach(value => extractFromObject(value));
}
}
extractFromObject(data);
return trails;
}
function updateTrailControls() {
const selector = document.getElementById('wordSelector');
selector.innerHTML = '<option value="all">All Words</option>';
// Detect word boundaries (gaps in timestamps)
trailData.forEach((trail, index) => {
const option = document.createElement('option');
option.value = index;
option.textContent = `Word ${index + 1} (${trail.length} points)`;
selector.appendChild(option);
});
document.getElementById('trailControls').classList.remove('hidden');
}
function playTrail() {
const selector = document.getElementById('wordSelector');
const speed = parseFloat(document.getElementById('playbackSpeed').value);
let trailsToPlay = [];
if (selector.value === 'all') {
trailsToPlay = trailData;
} else {
trailsToPlay = [trailData[parseInt(selector.value)]];
}
if (trailsToPlay.length === 0) {
alert('No trail data to play');
return;
}
// Update UI
document.getElementById('playBtn').classList.add('hidden');
document.getElementById('stopBtn').classList.remove('hidden');
document.getElementById('playbackDot').classList.remove('hidden');
// Start animation
animateTrails(trailsToPlay, speed);
}
function animateTrails(trails, speed) {
let currentTrailIdx = 0;
let currentPointIdx = 0;
let animationPath = [];
let lastKey = null;
const animate = () => {
if (currentTrailIdx >= trails.length) {
stopTrail();
return;
}
const trail = trails[currentTrailIdx];
const point = trail[currentPointIdx];
if (!keyboardBounds) {
updateKeyboardBounds();
}
// Convert normalized coordinates to canvas coordinates
const canvasX = point.x * keyboardBounds.width;
const canvasY = point.y * keyboardBounds.height;
// Update dot position
const dot = document.getElementById('playbackDot');
const rect = canvas.getBoundingClientRect();
dot.style.left = canvasX + 'px';
dot.style.top = canvasY + 'px';
// Add to animation path
animationPath.push({
x: point.x * NORMALIZED_WIDTH,
y: point.y * NORMALIZED_HEIGHT,
normalized: { x: point.x, y: point.y }
});
// Check which key we're over
const clientX = rect.left + canvasX;
const clientY = rect.top + canvasY;
const key = getKeyAtPosition(clientX, clientY);
if (key) {
const keyChar = key.dataset.key;
if (keyChar !== lastKey) {
if (lastKey) {
document.querySelector(`.key[data-key="${lastKey}"]`)?.classList.remove('key-active');
}
key.classList.add('key-active');
lastKey = keyChar;
}
}
// Draw trail
drawAnimationTrail(animationPath);
// Calculate delay to next point
let delay = 16; // Default 16ms
if (currentPointIdx < trail.length - 1) {
const timeDiff = trail[currentPointIdx + 1].t - point.t;
delay = Math.max(1, timeDiff / speed);
}
currentPointIdx++;
if (currentPointIdx >= trail.length) {
currentTrailIdx++;
currentPointIdx = 0;
animationPath = [];
// Clear last key highlight
if (lastKey) {
document.querySelector(`.key[data-key="${lastKey}"]`)?.classList.remove('key-active');
lastKey = null;
}
// Pause between words
delay = 500 / speed;
}
playbackAnimation = setTimeout(animate, delay);
};
animate();
}
function drawAnimationTrail(path) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (path.length < 2) return;
// Create gradient for animation trail (green theme)
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, '#00ff88');
gradient.addColorStop(0.5, '#00d4ff');
gradient.addColorStop(1, '#00ff88');
// Draw trail
ctx.strokeStyle = gradient;
ctx.lineWidth = 3;
ctx.globalAlpha = 0.8;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.shadowColor = '#00ff88';
ctx.shadowBlur = 10;
ctx.beginPath();
path.forEach((point, i) => {
const canvasX = (point.x / NORMALIZED_WIDTH) * keyboardBounds.width;
const canvasY = (point.y / NORMALIZED_HEIGHT) * keyboardBounds.height;
if (i === 0) {
ctx.moveTo(canvasX, canvasY);
} else {
ctx.lineTo(canvasX, canvasY);
}
});
ctx.stroke();
ctx.globalAlpha = 1;
ctx.shadowBlur = 0;
}
function stopTrail() {
if (playbackAnimation) {
clearTimeout(playbackAnimation);
playbackAnimation = null;
}
document.getElementById('playBtn').classList.remove('hidden');
document.getElementById('stopBtn').classList.add('hidden');
document.getElementById('playbackDot').classList.add('hidden');
// Clear any active keys
document.querySelectorAll('.key-active').forEach(key => {
key.classList.remove('key-active');
});
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function updateLoadingStatus(message) {
document.getElementById('loadingDetails').textContent = message;
}
function hideLoadingOverlay() {
document.getElementById('loadingOverlay').classList.add('hidden');
}
function updateStatus(message, type = 'info') {
const statusText = document.getElementById('statusText');
const statusIndicator = document.getElementById('statusIndicator');
const modelStatus = document.getElementById('modelStatus');
statusText.textContent = message;
if (type === 'success') {
statusIndicator.className = 'w-2 h-2 bg-neon-blue rounded-full animate-pulse-neon';
modelStatus.textContent = 'ONNX Models Ready • Character-level Transformer';
} else if (type === 'error') {
statusIndicator.className = 'w-2 h-2 bg-red-500 rounded-full';
modelStatus.textContent = 'Models Failed to Load';
} else {
statusIndicator.className = 'w-2 h-2 bg-yellow-500 rounded-full';
}
}
function resizeCanvas() {
const rect = canvas.parentElement.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
}
function updateKeyboardBounds() {
const keys = document.querySelectorAll('.key[data-row]');
if (keys.length === 0) return;
let minX = Infinity, minY = Infinity;
let maxX = -Infinity, maxY = -Infinity;
keys.forEach(key => {
const rect = key.getBoundingClientRect();
minX = Math.min(minX, rect.left);
minY = Math.min(minY, rect.top);
maxX = Math.max(maxX, rect.right);
maxY = Math.max(maxY, rect.bottom);
});
keyboardBounds = { minX, minY, maxX, maxY, width: maxX - minX, height: maxY - minY };
}
function getEventPosition(e) {
const rect = canvas.getBoundingClientRect();
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
return { x: clientX - rect.left, y: clientY - rect.top, clientX, clientY };
}
function getNormalizedCoords(clientX, clientY) {
if (!keyboardBounds) return { x: 0, y: 0, normalized: { x: 0, y: 0 } };
const x = clientX - keyboardBounds.minX;
const y = clientY - keyboardBounds.minY;
const normX = (x / keyboardBounds.width) * NORMALIZED_WIDTH;
const normY = (y / keyboardBounds.height) * NORMALIZED_HEIGHT;
const norm01X = x / keyboardBounds.width;
const norm01Y = y / keyboardBounds.height;
return {
x: Math.round(normX),
y: Math.round(normY),
normalized: { x: norm01X.toFixed(3), y: norm01Y.toFixed(3) }
};
}
function getKeyAtPosition(clientX, clientY) {
const keys = document.querySelectorAll('.key[data-key]');
for (let key of keys) {
const rect = key.getBoundingClientRect();
if (clientX >= rect.left && clientX <= rect.right &&
clientY >= rect.top && clientY <= rect.bottom) {
return key;
}
}
return null;
}
// [Keep all the original swipe handling functions from here on]
function startSwipe(e) {
e.preventDefault();
isDrawing = true;
swipePath = [];
keySequence = [];
currentKey = null;
const pos = getEventPosition(e);
const coords = getNormalizedCoords(pos.clientX, pos.clientY);
const key = getKeyAtPosition(pos.clientX, pos.clientY);
if (key) {
currentKey = key.dataset.key;
key.classList.add('key-active');
keySequence.push({ key: currentKey, timestamp: Date.now(), index: 0 });
}
swipePath.push({
x: coords.x,
y: coords.y,
normalized: coords.normalized,
key: currentKey,
timestamp: Date.now()
});
if (DEBUG.enabled) {
updateDebugDisplay(coords, currentKey);
document.getElementById('coordinateDisplay').classList.remove('hidden');
}
}
function continueSwipe(e) {
if (!isDrawing) return;
e.preventDefault();
const pos = getEventPosition(e);
const coords = getNormalizedCoords(pos.clientX, pos.clientY);
const key = getKeyAtPosition(pos.clientX, pos.clientY);
const keyChar = key ? key.dataset.key : null;
if (keyChar !== currentKey) {
if (currentKey) {
document.querySelector(`.key[data-key="${currentKey}"]`)?.classList.remove('key-active');
}
if (key) {
key.classList.add('key-active');
keySequence.push({
key: keyChar,
timestamp: Date.now(),
index: swipePath.length
});
}
currentKey = keyChar;
}
swipePath.push({
x: coords.x,
y: coords.y,
normalized: coords.normalized,
key: currentKey,
timestamp: Date.now()
});
drawNeonTrail();
if (DEBUG.enabled) {
updateDebugDisplay(coords, currentKey);
}
}
function drawNeonTrail() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (swipePath.length < 2) return;
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, '#00d4ff');
gradient.addColorStop(0.5, '#b300ff');
gradient.addColorStop(1, '#ff00d4');
for (let layer = 3; layer > 0; layer--) {
ctx.strokeStyle = gradient;
ctx.lineWidth = layer * 2;
ctx.globalAlpha = 0.3 / layer;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.shadowColor = layer === 1 ? '#00d4ff' : '#b300ff';
ctx.shadowBlur = 15 * layer;
ctx.beginPath();
swipePath.forEach((point, i) => {
const canvasX = (point.x / NORMALIZED_WIDTH) * keyboardBounds.width;
const canvasY = (point.y / NORMALIZED_HEIGHT) * keyboardBounds.height;