-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
2250 lines (2019 loc) · 103 KB
/
index.html
File metadata and controls
2250 lines (2019 loc) · 103 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">
<title>SafeAI Beta - HouseLearning</title>
<link rel="stylesheet" href="food.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/monaco-editor@0.38.1/min/vs/editor/editor.main.css">
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.38.1/min/vs/loader.js"></script>
<style>
*{box-sizing:border-box;}
body,html{margin:0;padding:0;font-family:Arial,sans-serif;background:#1b0f33;color:white;overflow-x:hidden;}
/* Splash */
#splash{position:fixed;top:0;left:0;width:100%;height:100%;background:#1b0f33;display:flex;flex-direction:column;justify-content:center;align-items:center;z-index:9999;transition:opacity 0.6s;}
#splash h1{font-family:'Brush Script MT',cursive;font-size:72px;background:linear-gradient(135deg,#7a2cff,#d38cff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;opacity:0;animation:fadeIn 2s forwards;}
#splash #subtitle{opacity:0;margin-top:10px;font-size:20px;color:#9977cc;animation:fadeIn 2s 2s forwards;}
@keyframes fadeIn{to{opacity:1;}}
/* Main */
#main{display:none;padding:20px;padding-bottom:100px;}
#recentChatsGrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;margin-top:20px;}
.chatCard{background:#2b1a54;padding:16px;border-radius:12px;cursor:pointer;transition:transform 0.2s;position:relative;}
.chatCard:hover{transform:scale(1.03);}
.chatThumbnail{width:100%;height:100px;background:#7a2cff33;border-radius:8px;margin-bottom:10px;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:32px;color:white;}
.chatSummary{font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.deleteCardBtn{position:absolute;top:8px;right:8px;background:rgba(122,44,255,0.3);border:none;color:#d38cff;border-radius:50%;width:24px;height:24px;font-size:13px;cursor:pointer;display:none;align-items:center;justify-content:center;}
.chatCard:hover .deleteCardBtn{display:flex;}
.deleteCardBtn:hover{background:rgba(200,0,100,0.5);}
.emptyState{color:#9977cc;font-size:16px;margin-top:20px;}
/* Ask Bar */
#askBar{position:fixed;bottom:12px;left:50%;transform:translateX(-50%);display:flex;align-items:center;background:#2b1a54;border-radius:30px;padding:10px 20px;width:90%;max-width:900px;font-size:18px;z-index:5000;box-shadow:0 4px 30px rgba(122,44,255,0.4);}
#askBar .cursiveD{font-family:'Brush Script MT',cursive;font-size:28px;background:linear-gradient(135deg,#7a2cff,#d38cff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;margin-right:10px;flex-shrink:0;}
#askBar input{flex:1;background:transparent;border:none;color:white;font-size:18px;outline:none;padding-left:10px;}
#askBar input::placeholder{color:#9977cc;}
#askBar .sendBtn{background:linear-gradient(135deg,#7a2cff,#d38cff);border:none;color:white;padding:8px 16px;border-radius:20px;margin-left:10px;cursor:pointer;font-size:15px;}
#askBar #micBtn{background:rgba(122,44,255,0.3);border:1px solid rgba(122,44,255,0.5);color:#d38cff;padding:8px 12px;border-radius:50%;margin-left:8px;cursor:pointer;font-size:16px;transition:all 0.2s;}
#askBar #micBtn.listening{background:rgba(200,50,255,0.6);animation:pulse 1s infinite;}
#askBar #settingsBtn{margin-left:8px;background:#7a2cff;color:white;border:none;padding:8px 12px;border-radius:50%;cursor:pointer;font-size:16px;}
@keyframes pulse{0%,100%{box-shadow:0 0 0 0 rgba(200,50,255,0.5);}50%{box-shadow:0 0 0 10px rgba(200,50,255,0);}}
/* Voice Orb */
#voiceOrb{display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:8000;flex-direction:column;align-items:center;gap:20px;}
#orbCircle{width:140px;height:140px;border-radius:50%;background:radial-gradient(circle at 35% 35%,#c77dff,#7a2cff,#3b0080);box-shadow:0 0 40px rgba(180,80,255,0.8),0 0 80px rgba(120,30,255,0.4);animation:orbPulse 1.5s ease-in-out infinite;}
#orbLabel{font-family:'Brush Script MT',cursive;font-size:26px;background:linear-gradient(135deg,#7a2cff,#d38cff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;}
#orbStatus{font-size:13px;color:#9977cc;letter-spacing:0.08em;}
#orbClose{background:none;border:1px solid rgba(122,44,255,0.4);color:#9977cc;border-radius:20px;padding:6px 18px;cursor:pointer;font-size:13px;margin-top:4px;}
#orbClose:hover{color:#d38cff;border-color:#d38cff;}
@keyframes orbPulse{0%,100%{box-shadow:0 0 40px rgba(180,80,255,0.8),0 0 80px rgba(120,30,255,0.4);transform:scale(1);}50%{box-shadow:0 0 60px rgba(200,100,255,1),0 0 120px rgba(150,50,255,0.6);transform:scale(1.07);}}
#voiceOrb.active #orbCircle{animation:orbPulse 0.8s ease-in-out infinite;}
/* Chat */
#chatOverlay{display:none;position:fixed;top:0;left:0;width:100%;height:100%;z-index:2000;background:#1b0f33;flex-direction:column;align-items:center;}
#chatHeader{width:100%;max-width:760px;display:flex;justify-content:space-between;align-items:center;padding:14px 20px;flex-shrink:0;}
#chatHeader .chatTitle{font-size:15px;color:#9977cc;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:80%;}
#chatHeader .closeBtn{font-size:22px;background:none;border:none;color:#9977cc;cursor:pointer;}
#chatContent{display:flex;flex-direction:column;gap:10px;flex:1;overflow-y:auto;width:100%;max-width:760px;padding:0 20px 20px;}
#chatContent::after{content:'';display:block;height:80px;flex-shrink:0;}
.userMsg{background:#7a2cff88;align-self:flex-end;padding:10px 14px;border-radius:16px 16px 4px 16px;max-width:80%;line-height:1.5;word-break:break-word;white-space:pre-wrap;}
.doloresMsg{background:#4b2f8c;align-self:flex-start;padding:10px 14px;border-radius:16px 16px 16px 4px;max-width:80%;line-height:1.5;word-break:break-word;white-space:pre-wrap;}
/* Typing dots */
.typingDots span{display:inline-block;width:6px;height:6px;border-radius:50%;background:#d38cff;margin:0 2px;animation:bounce 1.2s infinite;}
.typingDots span:nth-child(2){animation-delay:0.2s;}
.typingDots span:nth-child(3){animation-delay:0.4s;}
@keyframes bounce{0%,80%,100%{transform:translateY(0);}40%{transform:translateY(-6px);}}
/* File cards */
.fileCard{background:#3b2a70;padding:12px;border-radius:10px;display:flex;justify-content:space-between;align-items:center;margin-top:4px;align-self:stretch;}
.fileCard:hover{background:#4b2f8c;}
.fileName{font-weight:bold;color:#d38cff;}
.fileActions button{margin-left:6px;padding:4px 10px;border:none;border-radius:6px;background:#7a2cff;color:white;cursor:pointer;font-size:13px;}
/* Food rendering container — uses food.css classes */
.foodContainer{align-self:flex-start;max-width:90%;width:100%;}
.foodContainer .food-text{background:#3b2a70 !important;border-radius:12px;color:white;}
.foodContainer .food-code{border:1px solid rgba(122,44,255,0.3);}
.foodContainer .food-code-title{background:#2b1a54 !important;color:#d38cff !important;}
.foodContainer .food-image{max-width:100%;border-radius:12px;margin:8px 0;}
.foodContainer .food-table th{background:#3b2a70 !important;color:#d38cff !important;}
.foodContainer .food-table td{background:#2b1a54 !important;}
.foodContainer .food-markdown{background:#3b2a70 !important;}
/* Image generation */
.imgWrap{background:#3b2a70;border-radius:12px;overflow:hidden;align-self:flex-start;max-width:512px;margin-top:4px;}
.imgWrap img{width:100%;max-width:512px;display:none;}
.imgLoading{padding:16px 20px;color:#9977cc;font-size:13px;}
.imgSaveBtn{align-self:flex-start;display:inline-block;margin-top:4px;padding:5px 14px;background:#7a2cff;color:white;border-radius:8px;font-size:12px;text-decoration:none;}
/* Code Preview (Monaco) */
#fileEditorOverlay{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(10,5,25,0.88);backdrop-filter:blur(10px);z-index:4000;flex-direction:column;align-items:center;justify-content:center;padding:24px;}
#codePanel{width:90%;max-width:860px;height:82vh;display:flex;flex-direction:column;border-radius:12px;overflow:hidden;border:1px solid rgba(122,44,255,0.4);box-shadow:0 24px 80px rgba(90,20,200,0.4);}
#codePanelHeader{display:flex;align-items:center;justify-content:space-between;background:#1a0f2e;padding:10px 16px;border-bottom:1px solid rgba(122,44,255,0.35);flex-shrink:0;}
#codePanelLeft{display:flex;align-items:center;gap:10px;}
#codePanelDots{display:flex;gap:6px;}
.dot{width:12px;height:12px;border-radius:50%;}
.dot.red{background:#9b5de5;}.dot.yellow{background:#c77dff;}.dot.green{background:#e0aaff;}
#codePanelFilename{font-family:'SF Mono',monospace;font-size:13px;color:#d38cff;font-weight:500;}
#codePanelLang{font-size:11px;color:#9b5de5;background:rgba(122,44,255,0.2);border:1px solid rgba(122,44,255,0.35);padding:2px 8px;border-radius:4px;text-transform:uppercase;letter-spacing:0.05em;}
#codePanelActions{display:flex;gap:8px;align-items:center;}
.panelBtn{background:rgba(122,44,255,0.2);border:1px solid rgba(122,44,255,0.4);color:#d38cff;padding:5px 12px;border-radius:6px;cursor:pointer;font-size:12px;display:flex;align-items:center;gap:5px;transition:background 0.15s;}
.panelBtn:hover{background:rgba(122,44,255,0.4);}
.panelBtn.close{background:transparent;border:none;font-size:18px;color:#9b5de5;padding:4px 8px;}
.panelBtn.close:hover{color:#d38cff;}
#editorContainer{flex:1;overflow:hidden;background:#1e1e2e;}
#runOutput{display:none;background:#0d0d1a;border-top:1px solid rgba(122,44,255,0.3);padding:12px 16px;font-family:'SF Mono',monospace;font-size:13px;color:#a0f0a0;max-height:150px;overflow-y:auto;white-space:pre-wrap;}
/* Toasts */
#copiedToast{position:fixed;bottom:90px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,#7a2cff,#d38cff);color:white;padding:8px 20px;border-radius:20px;font-size:14px;font-weight:600;opacity:0;transition:opacity 0.3s;pointer-events:none;z-index:9999;}
#copiedToast.show{opacity:1;}
#modeToast{position:fixed;top:14px;right:14px;background:rgba(27,15,51,0.85);border:1px solid rgba(122,44,255,0.4);color:#d38cff;padding:5px 14px;border-radius:20px;font-size:12px;opacity:0;transition:opacity 0.3s;pointer-events:none;z-index:9999;}
#modeToast.show{opacity:1;}
/* Settings */
#settingsOverlay{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.92);z-index:6000;overflow:auto;}
#settingsPanel{margin:40px auto;width:90%;max-width:700px;background:#1b0f33;padding:30px;border-radius:12px;color:white;position:relative;border:1px solid rgba(122,44,255,0.3);}
#settingsPanel h2{margin-top:0;background:linear-gradient(135deg,#7a2cff,#d38cff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;}
#settingsPanel label{display:flex;align-items:center;gap:8px;margin-top:14px;cursor:pointer;}
#settingsPanel input[type=checkbox]{width:16px;height:16px;accent-color:#7a2cff;}
.settingsBtn{margin-top:16px;padding:8px 16px;border:none;border-radius:8px;background:rgba(122,44,255,0.3);border:1px solid rgba(122,44,255,0.5);color:#d38cff;cursor:pointer;font-size:14px;display:block;transition:background 0.2s;}
.settingsBtn:hover{background:rgba(122,44,255,0.5);}
.settingsBtn.danger{background:rgba(180,0,60,0.3);border-color:rgba(200,0,80,0.5);color:#ff8080;}
.settingsBtn.danger:hover{background:rgba(200,0,60,0.5);}
.settingsDivider{border:none;border-top:1px solid rgba(122,44,255,0.2);margin:20px 0;}
</style>
</head>
<body>
<!-- Engines -->
<script src="food.js"></script>
<script src="image-engine.js"></script>
<script src="dolores-engine.js"></script>
<!-- Splash -->
<div id="splash">
<h1>SafeAI Beta</h1>
<span id="subtitle"></span>
</div>
<!-- Main -->
<div id="main">
<h1 style="font-family:'Brush Script MT',cursive;font-size:48px;background:linear-gradient(135deg,#7a2cff,#d38cff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;margin-bottom:4px;">Recent Chats</h1>
<div id="recentChatsGrid"></div>
</div>
<!-- Chat -->
<div id="chatOverlay">
<div id="chatHeader">
<span class="chatTitle" id="chatTitleText">Chat</span>
<button class="closeBtn" onclick="closeChat()">✖</button>
</div>
<div id="chatContent"></div>
</div>
<!-- Voice Orb -->
<div id="voiceOrb">
<div id="orbCircle"></div>
<div id="orbLabel">Dolores</div>
<div id="orbStatus">Listening...</div>
<button id="orbClose" onclick="stopWakeListening()">Dismiss</button>
</div>
<!-- Monaco Code Preview -->
<div id="fileEditorOverlay">
<div id="codePanel">
<div id="codePanelHeader">
<div id="codePanelLeft">
<div id="codePanelDots"><div class="dot red"></div><div class="dot yellow"></div><div class="dot green"></div></div>
<span id="codePanelFilename">untitled</span>
<span id="codePanelLang">text</span>
</div>
<div id="codePanelActions">
<button class="panelBtn" onclick="runCode()">▶ Run</button>
<button class="panelBtn" onclick="copyCode()">⎘ Copy</button>
<button class="panelBtn" onclick="downloadCurrentFile()">↓ Download</button>
<button class="panelBtn close" onclick="closeFileEditor()">✕</button>
</div>
</div>
<div id="editorContainer"></div>
<div id="runOutput"></div>
</div>
</div>
<div id="copiedToast">Copied!</div>
<div id="modeToast"></div>
<!-- Ask Bar -->
<div id="askBar">
<span class="cursiveD">D</span>
<input type="text" id="userInput" placeholder="Ask Dolores..." onkeydown="if(event.key==='Enter') askOrSend();" />
<button class="sendBtn" onclick="askOrSend()">Send</button>
<button id="micBtn" onclick="toggleMic()" title="Voice input">🎤</button>
<button id="settingsBtn" onclick="openSettings()">⚙</button>
</div>
<!-- Settings -->
<div id="settingsOverlay">
<div id="settingsPanel">
<button style="position:absolute;top:14px;right:14px;font-size:20px;background:none;border:none;color:#9977cc;cursor:pointer;" onclick="closeSettings()">✖</button>
<h2>Settings</h2>
<hr class="settingsDivider">
<p style="margin:0 0 8px;font-size:13px;color:#9977cc;font-weight:600;letter-spacing:0.05em;">VOICE — CHAT</p>
<label><input type="checkbox" id="voiceToggle"> Voice responses in chat (off by default)</label>
<label><input type="checkbox" id="voiceInputToggle" checked> Mic button (voice input)</label>
<hr class="settingsDivider">
<p style="margin:0 0 8px;font-size:13px;color:#9977cc;font-weight:600;letter-spacing:0.05em;">VOICE — DOLORES ASSISTANT</p>
<label><input type="checkbox" id="wakeWordToggle" checked> Wake word listening ("Dolores")</label>
<label><input type="checkbox" id="voiceAssistantSpeakToggle" checked> Dolores speaks responses (on by default)</label>
<hr class="settingsDivider">
<p style="margin:0 0 8px;font-size:13px;color:#9977cc;font-weight:600;letter-spacing:0.05em;">DISPLAY</p>
<label><input type="checkbox" id="typingAnimToggle" checked> Typing animation</label>
<hr class="settingsDivider">
<p style="margin:0 0 6px;font-size:13px;color:#9977cc;font-weight:600;letter-spacing:0.05em;">🤖 YOUR AI KEY</p>
<p style="margin:0 0 10px;font-size:12px;color:#9977cc;line-height:1.5;">Your personal <a href="https://openrouter.ai/keys" target="_blank" style="color:#d38cff;">OpenRouter</a> key. When set, Dolores uses AI for questions her knowledge base doesn't cover.</p>
<div style="display:flex;gap:8px;align-items:center;">
<input type="password" id="apiKeyInput" placeholder="sk-or-v1-..." style="flex:1;background:#2b1a54;border:1px solid rgba(122,44,255,0.4);color:white;padding:8px 12px;border-radius:8px;font-size:13px;outline:none;" oninput="saveApiKeyLive()">
<button class="settingsBtn" style="margin:0;padding:8px 14px;white-space:nowrap;" onclick="clearApiKey()">✕ Clear</button>
</div>
<div id="apiKeyStatus" style="font-size:12px;margin-top:6px;color:#9977cc;min-height:18px;"></div>
<hr class="settingsDivider">
<p style="margin:0 0 6px;font-size:13px;color:#d38cff;font-weight:600;letter-spacing:0.05em;">🧠 DOLORES KNOWLEDGE API</p>
<p style="margin:0 0 10px;font-size:12px;color:#9977cc;line-height:1.5;">Share Dolores's knowledge base with your friends or plug it into any AI. Use the ready-made JS file below — it wires up everything automatically.</p>
<p style="margin:0 0 4px;font-size:12px;color:#9977cc;">📡 Live endpoint:</p>
<div style="background:#2b1a54;border:1px solid rgba(122,44,255,0.3);border-radius:8px;padding:9px 12px;font-family:monospace;font-size:11px;color:#d38cff;word-break:break-all;user-select:all;margin-bottom:10px;">https://aidolores.github.io/smart.json</div>
<p style="margin:0 0 6px;font-size:12px;color:#9977cc;">📦 Download <b style="color:#d38cff;">dolores-integration.js</b> — drop it in any project:</p>
<div style="background:#0d0a1a;border:1px solid rgba(122,44,255,0.2);border-radius:8px;padding:10px 12px;font-family:monospace;font-size:10.5px;color:#a0f0a0;white-space:pre;overflow-x:auto;max-height:160px;overflow-y:auto;">// dolores-integration.js
// Drop into any project to use Dolores's knowledge base + image gen
// All files from aidolores.github.io are loaded automatically.
const Dolores = {
kb: {}, // flat knowledge base (smart.json)
functions: {}, // code patterns (functions.json)
templates: {}, // project templates (templates.json)
ready: false,
async init() {
const BASE = 'https://aidolores.github.io';
const [smart, funcs, tpls] = await Promise.all([
fetch(BASE + '/smart.json').then(r => r.json()),
fetch(BASE + '/functions.json').then(r => r.json()),
fetch(BASE + '/templates.json').then(r => r.json()),
]);
// Flatten smart.json categories into one lookup
if (smart.knowledge)
Object.values(smart.knowledge).forEach(cat =>
Object.assign(this.kb, cat));
if (smart.debug) Object.assign(this.kb, smart.debug);
this.functions = funcs;
this.templates = tpls;
this.ready = true;
console.log('[Dolores] Loaded', Object.keys(this.kb).length,
'KB entries,', Object.keys(this.templates.projects||{}).length,
'templates');
return this;
},
// Query the knowledge base
query(input) {
const lower = input.toLowerCase();
const words = lower.split(/\W+/).filter(w => w.length > 2);
let best = 0, result = null;
for (const [key, val] of Object.entries(this.kb)) {
let score = 0;
if (lower.includes(key)) score += 10;
key.split(' ').forEach(kw => { if (lower.includes(kw)) score += 3; });
words.forEach(w => { if (key.includes(w)) score += 2; });
words.forEach(w => { if (val.toLowerCase().includes(w)) score += 1; });
if (score > best) { best = score; result = val; }
}
return best >= 2 ? result : null;
},
// Generate an image URL via Pollinations.ai (free, no key)
imageURL(prompt, w = 512, h = 512) {
return 'https://image.pollinations.ai/prompt/' +
encodeURIComponent(prompt) +
'?width=' + w + '&height=' + h + '&nologo=true';
},
// Get a project template by name
template(name) {
return this.templates?.projects?.[name] || null;
},
// Respond to any message (KB first, then optional OpenRouter AI)
async respond(input, openRouterKey = null) {
const kbAnswer = this.query(input);
if (kbAnswer) return { source: 'kb', text: kbAnswer };
if (openRouterKey) {
const res = await fetch(
'https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + openRouterKey,
},
body: JSON.stringify({
model: 'openrouter/auto',
messages: [{ role: 'user', content: input }],
max_tokens: 1000,
}),
});
const data = await res.json();
const text = data.choices?.[0]?.message?.content?.trim();
if (text) return { source: 'ai', text };
}
return { source: 'none', text: null };
},
};
// Auto-init when script loads
Dolores.init();</div>
<div style="display:flex;gap:8px;margin-top:8px;flex-wrap:wrap;">
<button class="settingsBtn" style="margin:0;padding:6px 14px;font-size:12px;" onclick="downloadIntegrationJS()">⬇ Download dolores-integration.js</button>
<button class="settingsBtn" style="margin:0;padding:6px 14px;font-size:12px;" onclick="copySystemPrompt()">⎘ Copy System Prompt</button>
</div>
<div id="promptCopied" style="font-size:11px;color:#a0f0a0;margin-top:4px;display:none;">Copied! ✓</div>
<p style="margin:10px 0 6px;font-size:12px;color:#9977cc;">System prompt to give your AI access to the KB:</p>
<div id="systemPromptBox" style="background:#0d0a1a;border:1px solid rgba(122,44,255,0.2);border-radius:8px;padding:10px 12px;font-family:monospace;font-size:11px;color:#c0a0ff;white-space:pre-wrap;word-break:break-word;cursor:pointer;" onclick="copySystemPrompt()" title="Click to copy">You have access to the Dolores knowledge base.
Load it with: await Dolores.init(); (from aidolores.github.io)
Or fetch directly: https://aidolores.github.io/smart.json
The JSON has .knowledge (categorised) and .debug (error fixes).
Flatten with: Object.values(db.knowledge).forEach(c => Object.assign(kb, c))
Always check the KB before generating an answer from scratch.</div>
<hr class="settingsDivider">
<p style="margin:0 0 8px;font-size:13px;color:#9977cc;font-weight:600;letter-spacing:0.05em;">FILES IN THIS APP</p>
<div style="font-size:12px;color:#9977cc;line-height:2;background:#2b1a54;border-radius:8px;padding:10px 14px;">
<div>📄 <b style="color:#d38cff;">dolores.html</b> — main app (fully self-contained)</div>
<div>🧠 <b style="color:#d38cff;">smart.json</b> — knowledge database</div>
<div>🍕 <b style="color:#d38cff;">food.js</b> — rich content rendering engine</div>
<div>🎨 <b style="color:#d38cff;">food.css</b> — styles for food.js</div>
<div>🖼 <b style="color:#d38cff;">image-engine.js</b> — Pollinations.ai image gen</div>
<div>⚙️ <b style="color:#d38cff;">dolores-engine.js</b> — intent detection</div>
<div>📦 <b style="color:#d38cff;">functions.json</b> — code pattern templates</div>
<div>🗂 <b style="color:#d38cff;">templates.json</b> — project templates</div>
</div>
<p style="font-size:11px;color:#6644aa;margin:6px 0 0;">All files hosted at <b>aidolores.github.io</b></p>
<hr class="settingsDivider">
<button class="settingsBtn danger" onclick="deleteAllData()">🗑 Delete All Dolores Data</button>
</div>
</div>
<script>
// ── State ─────────────────────────────────────────────────────────
// API key loaded from localStorage (user sets it in Settings)
let voiceAssistantMode = false; // true when triggered by wake word / orb
let knowledgeBase = {};
let functionsDB = {};
let templatesDB = {};
let recentChats = JSON.parse(localStorage.getItem("recentChats") || "[]");
let inChat = false, currentChatId = null, currentFile = null;
let editor = null, micRecognition = null, wakeRecognition = null;
let isListening = false, orbVisible = false;
// ── Load all JSON databases ───────────────────────────────────────
async function loadDatabases() {
try {
const [smart, funcs, temps] = await Promise.all([
fetch("smart.json").then(r => r.json()),
fetch("functions.json").then(r => r.json()),
fetch("templates.json").then(r => r.json())
]);
// Flatten smart.json nested structure into flat KB
if (smart.knowledge) {
for (const category of Object.values(smart.knowledge)) {
Object.assign(knowledgeBase, category);
}
} else {
Object.assign(knowledgeBase, smart);
}
if (smart.debug) Object.assign(knowledgeBase, smart.debug);
functionsDB = funcs;
templatesDB = temps;
console.log("Dolores DB loaded:", Object.keys(knowledgeBase).length, "entries");
} catch(e) {
console.warn("DB load error:", e);
}
}
// ── Embedded fallback KB (always available) ───────────────────────
const embeddedKB = {
"javascript basics": "JavaScript is a high-level, interpreted language. Supports ES6+ features: arrow functions, classes, async/await, destructuring, modules.",
"python basics": "Python is interpreted, dynamically typed. Great for scripting, data science, ML, web backends. f-strings, list comprehensions, decorators.",
"html basics": "HTML5 semantic elements: header, nav, main, article, section, footer. Forms, canvas, media elements.",
"css basics": "CSS: selectors, flexbox, grid, animations, variables, responsive media queries.",
"data structures": "Arrays O(1) access, linked lists O(1) insert, hash maps O(1) avg lookup, trees/heaps O(log n), graphs O(V+E).",
"algorithms": "Sorting: merge O(n log n), quick O(n log n) avg. Searching: binary O(log n). Dynamic programming, BFS/DFS.",
"machine learning": "Supervised, unsupervised, reinforcement learning. Libraries: scikit-learn, TensorFlow, PyTorch. Neural networks, gradient descent.",
"web development": "Frontend: HTML/CSS/JS + React/Vue. Backend: Node.js/Express, Python/Flask/Django. Database: SQL/NoSQL. REST/GraphQL APIs.",
};
Object.assign(knowledgeBase, embeddedKB);
// ── Init ──────────────────────────────────────────────────────────
document.addEventListener("DOMContentLoaded", () => {
loadDatabases();
if (!localStorage.getItem("micAsked")) {
localStorage.setItem("micAsked", "1");
navigator.mediaDevices && navigator.mediaDevices.getUserMedia({audio:true})
.then(s => s.getTracks().forEach(t => t.stop())).catch(() => {});
}
setTimeout(() => {
const splash = document.getElementById("splash");
splash.style.opacity = "0";
setTimeout(() => {
splash.style.display = "none";
document.getElementById("main").style.display = "block";
renderRecentChats();
startWakeWordListener();
}, 600);
}, 4000);
});
// ── Recent Chats ──────────────────────────────────────────────────
function saveChats() { localStorage.setItem("recentChats", JSON.stringify(recentChats)); }
function renderRecentChats() {
const container = document.getElementById("recentChatsGrid");
container.innerHTML = "";
if (!recentChats.length) {
container.innerHTML = '<p class="emptyState">No chats yet. Ask Dolores something!</p>'; return;
}
recentChats.forEach(chat => {
const card = document.createElement("div"); card.className = "chatCard";
const thumb = document.createElement("div"); thumb.className = "chatThumbnail"; thumb.innerText = chat.title.slice(0,1).toUpperCase();
const summary = document.createElement("div"); summary.className = "chatSummary"; summary.innerText = chat.title;
const delBtn = document.createElement("button"); delBtn.className = "deleteCardBtn"; delBtn.innerText = "✕";
delBtn.onclick = e => { e.stopPropagation(); deleteChat(chat.id); };
card.appendChild(delBtn); card.appendChild(thumb); card.appendChild(summary);
card.onclick = () => openChatById(chat.id);
container.appendChild(card);
});
}
function deleteChat(id) { recentChats = recentChats.filter(c => c.id !== id); saveChats(); renderRecentChats(); }
// ── Ask Bar ───────────────────────────────────────────────────────
function askOrSend() {
const val = document.getElementById("userInput").value.trim();
if (!val) return;
document.getElementById("userInput").value = "";
if (!inChat) startNewChat(val); else sendChatMessage(val);
}
// ── Chat ──────────────────────────────────────────────────────────
function startNewChat(firstMessage) {
const id = Date.now().toString();
const chat = { id, title: firstMessage.slice(0,60), messages: [] };
recentChats.unshift(chat);
if (recentChats.length > 30) recentChats.pop();
saveChats(); renderRecentChats();
currentChatId = id;
openChatUI(chat.title);
sendChatMessage(firstMessage);
}
function openChatById(id) {
const chat = recentChats.find(c => c.id === id);
if (!chat) return;
currentChatId = id;
openChatUI(chat.title);
const container = document.getElementById("chatContent");
container.innerHTML = "";
chat.messages.forEach(msg => {
if (msg.html) {
const wrap = document.createElement("div");
wrap.className = "foodContainer";
wrap.innerHTML = msg.html;
container.appendChild(wrap);
} else {
addChatMessage(msg.sender, msg.text);
}
if (msg.file) renderFileCard(msg.file);
});
}
function openChatUI(title) {
inChat = true;
document.getElementById("chatOverlay").style.display = "flex";
document.getElementById("chatContent").innerHTML = "";
document.getElementById("chatTitleText").innerText = title;
}
function closeChat() { inChat = false; currentChatId = null; document.getElementById("chatOverlay").style.display = "none"; }
function sendChatMessage(msg) { addChatMessage("user", msg); saveMessage("user", msg); doloresRespond(msg); }
function saveMessage(sender, text, file=null, html=null) {
if (!currentChatId) return;
const chat = recentChats.find(c => c.id === currentChatId);
if (!chat) return;
const entry = { sender, text };
if (file) entry.file = file;
if (html) entry.html = html;
chat.messages.push(entry);
saveChats();
}
function addChatMessage(sender, text, isTyping=false) {
const container = document.getElementById("chatContent");
const div = document.createElement("div");
div.className = sender === "user" ? "userMsg" : "doloresMsg";
if (isTyping) div.innerHTML = '<div class="typingDots"><span></span><span></span><span></span></div>';
else div.innerText = text;
container.appendChild(div);
container.scrollTop = container.scrollHeight;
return div;
}
// ── Food Rendering (using Food engine from food.js) ───────────────
function renderWithFood(data) {
const container = document.getElementById("chatContent");
const wrap = document.createElement("div");
wrap.className = "foodContainer";
container.appendChild(wrap);
// Point Food engine at our wrapper div
Food.container = wrap;
if (typeof data === "string") {
Food.renderText(data);
} else {
Food.render(data);
}
const html = wrap.innerHTML;
saveMessage("dolores", typeof data === "string" ? data : JSON.stringify(data), null, html);
if (document.getElementById("voiceToggle").checked) {
const textContent = wrap.innerText || "";
if (textContent.trim()) speak(textContent.slice(0, 200));
}
container.scrollTop = container.scrollHeight;
}
// ── Image Generation ──────────────────────────────────────────────
function isImageRequest(txt) {
const t = txt.toLowerCase().trim();
// NEVER an image if it's a code/programming request
if (/\b(code|function|script|program|app|website|api|html|css|javascript|js|python|java|c\+\+|sql|component|algorithm|loop|array|class|method|database|server|calculator|game|timer|todo|form|login|quiz|generator|converter|navbar|button|modal)\b/.test(t)) return false;
// Pure draw verbs at start — always image
if (/^(draw|paint|sketch|render|imagine|illustrate)\b/.test(t)) return true;
// "generate/create/make" only image if an image noun follows
if (/\b(generate|create|make|design|show)\b/.test(t) &&
/\b(image|picture|photo|art|illustration|drawing|painting|portrait|landscape|scene|logo|icon|wallpaper|avatar|poster|banner|artwork|pic|meme|cartoon|anime|realistic|3d|render)\b/.test(t)) return true;
// "X of X" image phrases
if (/\b(image of|picture of|photo of|drawing of|art of|illustration of|portrait of|painting of)\b/.test(t)) return true;
return false;
}
// ── Image Request Queue — prevents "queue full" on Pollinations ───
const imgQueue = { running: false, tasks: [] };
function queueImage(fn) {
imgQueue.tasks.push(fn);
if (!imgQueue.running) processImageQueue();
}
async function processImageQueue() {
if (imgQueue.tasks.length === 0) { imgQueue.running = false; return; }
imgQueue.running = true;
const task = imgQueue.tasks.shift();
await task();
// Wait 1.5s between requests so Pollinations queue clears
setTimeout(processImageQueue, 1500);
}
function renderImageResponse(prompt) {
const container = document.getElementById("chatContent");
// Strip command words, keep the actual subject
const clean = prompt
.replace(/^(draw|paint|sketch|generate|render|imagine|illustrate|create|make|show me|give me|design)\s+(me\s+)?(a\s+|an\s+|the\s+|some\s+)?/i, "")
.replace(/\b(image of|picture of|photo of|drawing of|art of|illustration of|portrait of|painting of|image|picture)\b/gi, "")
.replace(/\b(can you|please|could you|would you)\b/gi, "")
.replace(/\s{2,}/g, " ").trim() || prompt;
const encoded = encodeURIComponent(clean);
// Multiple models to try in order
const models = ["flux", "flux-realism", "turbo"];
const label = document.createElement("div");
label.className = "doloresMsg";
label.innerText = `Generating: "${clean}" ✨`;
container.appendChild(label);
const imgWrap = document.createElement("div"); imgWrap.className = "imgWrap";
const loading = document.createElement("div");
loading.className = "imgLoading";
loading.innerText = "⏳ Queuing image request...";
imgWrap.appendChild(loading);
container.appendChild(imgWrap);
container.scrollTop = container.scrollHeight;
saveMessage("dolores", "Generated image: " + clean);
queueImage(async () => {
loading.innerText = "⏳ Generating image...";
let lastUrl = "";
for (let m = 0; m < models.length; m++) {
const seed = Date.now() + m;
const url = `https://image.pollinations.ai/prompt/${encoded}?width=512&height=512&nologo=true&seed=${seed}&model=${models[m]}`;
lastUrl = url;
for (let attempt = 0; attempt < 3; attempt++) {
if (attempt > 0) {
// Wait before retry: 3s, 6s
const wait = attempt * 3000;
loading.innerText = `⏳ Rate limited — retrying in ${wait/1000}s... (model: ${models[m]})`;
await new Promise(r => setTimeout(r, wait));
}
try {
// Fetch the URL first to check if it's an image or a JSON error
const res = await fetch(url, { mode: "cors" });
const contentType = res.headers.get("content-type") || "";
if (contentType.startsWith("image/")) {
// Real image — convert to blob URL to avoid browser CORS blocking
const blob = await res.blob();
const blobUrl = URL.createObjectURL(blob);
loading.remove();
const img = document.createElement("img");
img.style.cssText = "width:100%;max-width:512px;display:block;border-radius:12px;";
img.src = blobUrl;
imgWrap.appendChild(img);
const saveBtn = document.createElement("a");
saveBtn.href = url; saveBtn.target = "_blank"; saveBtn.className = "imgSaveBtn";
saveBtn.innerText = "↓ Open / Save Image";
container.appendChild(saveBtn);
container.scrollTop = container.scrollHeight;
return; // success — exit all loops
}
// Got JSON/text — check if it's rate limit
const text = await res.text();
let isRateLimit = false;
try {
const json = JSON.parse(text);
isRateLimit = json.error === "Too Many Requests" || (json.message||"").includes("Queue full");
if (!isRateLimit) {
// Different error — skip to next model
break;
}
} catch(e) { break; }
// Rate limited — will retry via loop
} catch(e) {
// Network error — try next model
break;
}
}
// All retries for this model exhausted, try next model
}
// All models failed — show links so user can try manually
imgWrap.innerHTML =
`<div class="imgLoading" style="line-height:2;">` +
`<span style="color:#ffaa44;">⚠ Pollinations is busy right now.</span><br>` +
`<span style="font-size:11px;color:#9977cc;">Click a link to open the image directly:</span><br>` +
models.map((m, i) =>
`<a href="https://image.pollinations.ai/prompt/${encoded}?width=512&height=512&nologo=true&model=${m}" ` +
`target="_blank" style="color:#d38cff;display:block;">↗ Try with model: ${m}</a>`
).join("") +
`</div>`;
container.scrollTop = container.scrollHeight;
});
}
// ── Code Generator ────────────────────────────────────────────────
// Detects code requests and generates real code locally
function isCodeRequest(txt) {
const t = txt.toLowerCase();
// "example X file" requests go to KB, not code generator
if (/\bexample\b/.test(t) && /\b(js|javascript|html|css|python|java|cpp|c\+\+|react|file)\b/.test(t)) return false;
return /\b(write|create|make|build|generate|give me|show me|code)\b/.test(t) &&
/\b(function|class|script|program|app|component|code|snippet|html|css|javascript|js|python|java|c\+\+|sql|api|server|website|page|game|timer|calculator|todo|form|button|menu|navbar|card|modal|animation|counter|clock|converter|quiz)\b/.test(t);
}
function generateCode(input) {
const t = input.toLowerCase();
// ── HTML/CSS/JS snippets ──────────────────────────────────────
if (t.includes("todo") || t.includes("to-do") || t.includes("to do list")) {
return { lang:"html", name:"todo_app.html", code:`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Todo App</title>
<style>
body{font-family:Arial,sans-serif;background:#1b0f33;color:white;display:flex;justify-content:center;padding:40px;}
.app{width:400px;}
h1{background:linear-gradient(135deg,#7a2cff,#d38cff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;}
.input-row{display:flex;gap:8px;margin-bottom:16px;}
input{flex:1;background:#2b1a54;border:1px solid #7a2cff;color:white;padding:10px;border-radius:8px;font-size:15px;}
button{background:#7a2cff;color:white;border:none;padding:10px 16px;border-radius:8px;cursor:pointer;}
li{background:#2b1a54;margin:6px 0;padding:10px 14px;border-radius:8px;display:flex;justify-content:space-between;align-items:center;}
li.done span{text-decoration:line-through;opacity:0.5;}
li button{background:rgba(200,0,80,0.3);padding:4px 10px;font-size:12px;}
</style>
</head>
<body>
<div class="app">
<h1>✓ Todo</h1>
<div class="input-row">
<input id="inp" placeholder="Add a task..." onkeydown="if(event.key==='Enter')add()">
<button onclick="add()">Add</button>
</div>
<ul id="list" style="list-style:none;padding:0;"></ul>
</div>
\x3cscript>
function add(){
const inp=document.getElementById('inp');
if(!inp.value.trim()) return;
const li=document.createElement('li');
const span=document.createElement('span');
span.innerText=inp.value.trim();
span.onclick=()=>li.classList.toggle('done');
const del=document.createElement('button');
del.innerText='✕'; del.onclick=()=>li.remove();
li.appendChild(span); li.appendChild(del);
document.getElementById('list').appendChild(li);
inp.value='';
}
<\/script>
</body>
</html>` };
}
if (t.includes("calculator") || t.includes("calc")) {
return { lang:"html", name:"calculator.html", code:`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculator</title>
<style>
body{background:#1b0f33;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;}
.calc{background:#2b1a54;border-radius:16px;padding:24px;width:280px;box-shadow:0 8px 40px rgba(122,44,255,0.4);}
#display{background:#1b0f33;color:#d38cff;font-size:28px;text-align:right;padding:12px 16px;border-radius:10px;margin-bottom:16px;min-height:52px;word-break:break-all;}
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;}
button{background:#3b2a70;color:white;border:none;padding:16px;border-radius:10px;font-size:18px;cursor:pointer;transition:background 0.15s;}
button:hover{background:#4b3a80;}
.op{background:#7a2cff;} .op:hover{background:#9a4cff;}
.eq{background:linear-gradient(135deg,#7a2cff,#d38cff);color:white;} .eq:hover{opacity:0.9;}
.span2{grid-column:span 2;}
</style>
</head>
<body>
<div class="calc">
<div id="display">0</div>
<div class="grid">
<button onclick="clr()">C</button><button onclick="sign()">+/-</button><button onclick="pct()">%</button><button class="op" onclick="op('/')">÷</button>
<button onclick="num(7)">7</button><button onclick="num(8)">8</button><button onclick="num(9)">9</button><button class="op" onclick="op('*')">×</button>
<button onclick="num(4)">4</button><button onclick="num(5)">5</button><button onclick="num(6)">6</button><button class="op" onclick="op('-')">−</button>
<button onclick="num(1)">1</button><button onclick="num(2)">2</button><button onclick="num(3)">3</button><button class="op" onclick="op('+')">+</button>
<button class="span2" onclick="num(0)">0</button><button onclick="dot()">.</button><button class="eq" onclick="eq()">=</button>
</div>
</div>
\x3cscript>
let cur='0',prev='',operator='',newNum=true;
const d=()=>document.getElementById('display');
function update(v){d().innerText=v;}
function num(n){if(newNum){cur=String(n);newNum=false;}else{cur=cur==='0'?String(n):cur+n;}update(cur);}
function dot(){if(newNum){cur='0.';newNum=false;}else if(!cur.includes('.'))cur+='.';update(cur);}
function op(o){prev=cur;operator=o;newNum=true;}
function eq(){if(!operator)return;const a=parseFloat(prev),b=parseFloat(cur);let r;switch(operator){case'+':r=a+b;break;case'-':r=a-b;break;case'*':r=a*b;break;case'/':r=b===0?'Error':a/b;break;}cur=String(Math.round(r*1e10)/1e10);operator='';newNum=true;update(cur);}
function clr(){cur='0';prev='';operator='';newNum=true;update('0');}
function sign(){cur=String(-parseFloat(cur));update(cur);}
function pct(){cur=String(parseFloat(cur)/100);update(cur);}
<\/script>
</body>
</html>` };
}
if (t.includes("timer") || t.includes("countdown") || t.includes("stopwatch")) {
return { lang:"html", name:"timer.html", code:`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Timer</title>
<style>
body{background:#1b0f33;color:white;font-family:Arial,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0;gap:20px;}
#time{font-size:72px;font-weight:bold;background:linear-gradient(135deg,#7a2cff,#d38cff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;letter-spacing:4px;}
.btns{display:flex;gap:12px;}
button{background:#7a2cff;color:white;border:none;padding:12px 28px;border-radius:10px;font-size:16px;cursor:pointer;}
button:hover{background:#9a4cff;}
#reset{background:#2b1a54;}
</style>
</head>
<body>
<div id="time">00:00:00</div>
<div class="btns">
<button onclick="toggle()" id="btn">Start</button>
<button onclick="reset()" id="reset">Reset</button>
</div>
\x3cscript>
let ms=0,running=false,iv=null;
function pad(n){return String(n).padStart(2,'0');}
function update(){const h=Math.floor(ms/3600000),m=Math.floor(ms%3600000/60000),s=Math.floor(ms%60000/1000);document.getElementById('time').innerText=pad(h)+':'+pad(m)+':'+pad(s);}
function toggle(){running=!running;document.getElementById('btn').innerText=running?'Pause':'Resume';if(running)iv=setInterval(()=>{ms+=10;update();},10);else clearInterval(iv);}
function reset(){clearInterval(iv);running=false;ms=0;update();document.getElementById('btn').innerText='Start';}
<\/script>
</body>
</html>` };
}
if (t.includes("clock") || t.includes("analog clock") || t.includes("digital clock")) {
return { lang:"html", name:"clock.html", code:`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Clock</title>
<style>
body{background:#1b0f33;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;}
#time{font-size:80px;font-family:'SF Mono',monospace;font-weight:bold;background:linear-gradient(135deg,#7a2cff,#d38cff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;letter-spacing:4px;}
#date{color:#9977cc;font-size:20px;text-align:center;margin-top:12px;font-family:Arial,sans-serif;}
</style>
</head>
<body>
<div style="text-align:center;">
<div id="time"></div>
<div id="date"></div>
</div>
\x3cscript>
function tick(){
const now=new Date();
const h=String(now.getHours()).padStart(2,'0');
const m=String(now.getMinutes()).padStart(2,'0');
const s=String(now.getSeconds()).padStart(2,'0');
document.getElementById('time').innerText=h+':'+m+':'+s;
document.getElementById('date').innerText=now.toLocaleDateString(undefined,{weekday:'long',year:'numeric',month:'long',day:'numeric'});
}
tick(); setInterval(tick,1000);
<\/script>
</body>
</html>` };
}
if (t.includes("quiz") || t.includes("trivia")) {
return { lang:"html", name:"quiz.html", code:`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Quiz</title>
<style>
body{background:#1b0f33;color:white;font-family:Arial,sans-serif;display:flex;justify-content:center;padding:40px;}
.quiz{max-width:500px;width:100%;}
h2{background:linear-gradient(135deg,#7a2cff,#d38cff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;}
.q{background:#2b1a54;border-radius:12px;padding:20px;margin-bottom:16px;}
.q p{font-size:16px;margin:0 0 14px;}
.opt{display:block;background:#3b2a70;border:none;color:white;width:100%;padding:10px 14px;border-radius:8px;margin:6px 0;cursor:pointer;text-align:left;font-size:14px;}
.opt:hover{background:#4b3a80;}
.opt.correct{background:#2d6a2d !important;}
.opt.wrong{background:#6a2d2d !important;}
#score{font-size:20px;color:#d38cff;margin-top:16px;}
</style>
</head>
<body>
<div class="quiz">
<h2>Quick Quiz</h2>
<div id="questions"></div>
<div id="score"></div>
</div>
\x3cscript>
const qs=[
{q:"What does HTML stand for?",opts:["HyperText Markup Language","High Tech Modern Language","HyperText Modern Links","None"],ans:0},
{q:"Which planet is closest to the Sun?",opts:["Venus","Earth","Mercury","Mars"],ans:2},
{q:"What is 7 × 8?",opts:["54","56","58","64"],ans:1},
{q:"Who wrote Romeo and Juliet?",opts:["Dickens","Shakespeare","Hemingway","Austen"],ans:1},
];
let score=0,answered=0;
const el=document.getElementById('questions');
qs.forEach((q,qi)=>{
const div=document.createElement('div');div.className='q';
const p=document.createElement('p');p.innerText=(qi+1)+'. '+q.q;div.appendChild(p);
q.opts.forEach((opt,oi)=>{
const btn=document.createElement('button');btn.className='opt';btn.innerText=opt;
btn.onclick=function(){
if(this.disabled)return;
div.querySelectorAll('.opt').forEach(b=>b.disabled=true);
this.classList.add(oi===q.ans?'correct':'wrong');
if(oi===q.ans)score++;
answered++;
if(answered===qs.length)document.getElementById('score').innerText='Score: '+score+'/'+qs.length;
};
div.appendChild(btn);
});
el.appendChild(div);
});
<\/script>
</body>
</html>` };
}
if (t.includes("weather") || (t.includes("api") && t.includes("fetch"))) {
return { lang:"js", name:"fetch_example.js", code:`// Fetch API Example — get weather data
async function getWeather(city) {
// Using Open-Meteo (free, no key needed)
// First geocode the city
const geo = await fetch(
\`https://geocoding-api.open-meteo.com/v1/search?name=\${encodeURIComponent(city)}&count=1\`
).then(r => r.json());
if (!geo.results?.length) {
console.error('City not found:', city);
return null;
}
const { latitude, longitude, name, country } = geo.results[0];
// Get weather
const weather = await fetch(
\`https://api.open-meteo.com/v1/forecast?latitude=\${latitude}&longitude=\${longitude}¤t_weather=true\`
).then(r => r.json());
const temp = weather.current_weather.temperature;
const wind = weather.current_weather.windspeed;
console.log(\`\${name}, \${country}: \${temp}°C, wind \${wind} km/h\`);
return weather;
}
getWeather('New York');` };
}
if ((t.includes("python") || t.includes("py")) && (t.includes("class") || t.includes("oop"))) {
return { lang:"python", name:"classes_example.py", code:`# Python OOP Example
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}!"
def __repr__(self):
return f"Animal(name='{self.name}')"
class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Woof")
self.tricks = []
def learn(self, trick):
self.tricks.append(trick)
return f"{self.name} learned {trick}!"
def perform(self):
if not self.tricks:
return f"{self.name} doesn't know any tricks yet."
return f"{self.name} performs: " + ", ".join(self.tricks)
class Cat(Animal):
def __init__(self, name):
super().__init__(name, "Meow")
def speak(self):
return f"{self.name} says {self.sound}... but only when it wants to."
# Usage
dog = Dog("Rex")
cat = Cat("Luna")
print(dog.speak())
print(cat.speak())
print(dog.learn("sit"))
print(dog.learn("roll over"))
print(dog.perform())` };
}
if (t.includes("sort") || t.includes("sorting") || t.includes("algorithm")) {
const lang = t.includes("python") ? "python" : "js";
if (lang === "python") {
return { lang:"python", name:"sorting.py", code:`# Sorting Algorithms in Python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def merge_sort(arr):
if len(arr) <= 1:
return arr