Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1024 lines (861 loc) · 38.5 KB
/
Copy pathscript.js
File metadata and controls
1024 lines (861 loc) · 38.5 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
window.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.number-input').forEach((element) => {
element.querySelector('.down').addEventListener('click', function () {
element.querySelector('input[type=number]').stepDown()
element.querySelector('input[type=number]').dispatchEvent(new Event('change'));
});
element.querySelector('.up').addEventListener('click', function () {
element.querySelector('input[type=number]').stepUp()
element.querySelector('input[type=number]').dispatchEvent(new Event('change'));
});
element.querySelector('input[type=number]').addEventListener('change', function () {
if (this.value > parseInt(this.max)) {
this.value = this.max;
this.dispatchEvent(new Event('change'));
}
if (this.value < parseInt(this.min)) {
this.value = this.min;
this.dispatchEvent(new Event('change'));
}
});
});
document.querySelectorAll('.horizontalScrollBarJS').forEach((element) => {
let scrollAmount = 0;
let isScrolling = false;
let isDragging = false;
let startX;
let scrollLeft;
element.addEventListener('wheel', function (event) {
if (event.deltaY !== 0) {
event.preventDefault();
scrollAmount += event.deltaY;
if (!isScrolling) {
isScrolling = true;
requestAnimationFrame(smoothScroll);
}
}
});
element.addEventListener('mousedown', (event) => {
isDragging = true;
startX = event.pageX - element.offsetLeft;
scrollLeft = element.scrollLeft;
element.classList.add('active');
});
element.addEventListener('mouseleave', () => {
isDragging = false;
element.classList.remove('active');
});
element.addEventListener('mouseup', () => {
isDragging = false;
element.classList.remove('active');
});
element.addEventListener('mousemove', (event) => {
if (!isDragging) return;
event.preventDefault();
const x = event.pageX - element.offsetLeft;
const walk = (x - startX) * 1.5; // The multiplier can be adjusted for sensitivity
element.scrollLeft = scrollLeft - walk;
});
function smoothScroll() {
if (scrollAmount !== 0) {
const scrollStep = scrollAmount / 10;
element.scrollBy({
left: scrollStep,
behavior: 'auto'
});
scrollAmount -= scrollStep;
if (Math.abs(scrollAmount) < 1) {
scrollAmount = 0;
}
requestAnimationFrame(smoothScroll);
} else {
isScrolling = false;
}
}
});
});
class FormBuilder {
form;
constructor(title, onSubmit, onCancel) {
this.background = document.createElement('div');
this.container = document.createElement('div');
this.fields = [];
this.title = title;
this.onSubmit = onSubmit;
this.onCancel = onCancel;
this.background.className = 'form-background';
this.container.className = 'form-container';
this.background.appendChild(this.container);
document.body.appendChild(this.background);
}
addInputField(id, placeholder, startValue, onChange = () => {}) {
this.fields.push({ id, type: 'input', placeholder, startValue, onChange });
}
addColorField(id, startValue, onChange = () => {}) {
this.fields.push({ id, type: 'color', startValue, onChange });
}
addCheckbox(id, label, checked, onChange = () => {}) {
this.fields.push({ id, type: 'checkbox', label, checked, onChange });
}
addNumberField(id, min, max, startValue, onChange = () => {}) {
this.fields.push({ id, type: 'number', min, max, startValue, onChange });
}
addCustomNumberField(id, min, max, step, startValue, onChange = () => {}) {
this.fields.push({ id, type: 'custom-number', min, max, step, startValue, onChange });
}
addRangeField(id, min, max, startValue, onChange = () => {}) {
this.fields.push({ id, type: 'range', min, max, startValue, onChange });
}
addFileField(id, accept, onChange = () => {}) {
this.fields.push({ id, type: 'file', accept, onChange });
}
addSelectField(id, options, startValue, onChange = () => {}) {
this.fields.push({ id, type: 'select', options, startValue, onChange });
}
addHeader(Name) {
this.fields.push({ type: 'header', Name });
}
addHTML(html) {
this.fields.push({ type: 'html', html });
}
addButton(text, onKlick = () => {}) {
this.fields.push({ type: 'button', text, onKlick });
}
addDateInput(id, startValue, onChange = () => {}) {
this.fields.push({ id, type: 'date', startValue, onChange });
}
addQuillField(id, placeholder, startValue, onChange = () => {}) {
this.fields.push({ id, type: 'quill', placeholder, startValue, onChange });
}
closeForm() {
this.onCancel();
this.background.style.pointerEvents = 'none';
this.container.style.animation = 'form-container-out-animation 0.25s forwards';
this.background.style.animation = 'form-background-out-animation 0.25s forwards ease';
setTimeout(() => {
document.body.removeChild(this.background);
}, 500);
delete this;
}
fucus(id) {
document.getElementById(id).focus();
}
select(menge) {
document.getElementById(menge).select();
}
submitForm() {
const formData = {};
this.fields.forEach((field) => {
if (field.type === 'header' || field.type === 'html') return;
const input = this.form.querySelector(`#${field.id}`);
if (field.type === 'button') {
} else if (field.type === 'color') {
formData[field.id] = input.value;
} else if (field.type === 'checkbox') {
formData[field.id] = input.checked;
} else if (field.type === 'file') {
formData[field.id] = input.files[0];
} else if (field.type === 'quill') {
formData[field.id] = "\"" + field.quill.root.innerHTML + "\"";
} else {
formData[field.id] = input.value;
}
});
this.onSubmit(formData);
this.background.style.pointerEvents = 'none';
this.container.style.animation = 'form-container-out-animation 0.25s forwards';
this.background.style.animation = 'form-background-out-animation 0.25s forwards ease';
setTimeout(() => {
document.body.removeChild(this.background);
}, 500);
delete this;
}
renderForm(showButtons = true) {
// Clear previous content
this.container.innerHTML = '';
const form = document.createElement('form');
// Add title
const title = document.createElement('h2');
title.textContent = this.title;
form.appendChild(title);
this.container.appendChild(form);
this.form = form;
// Generate fields
this.fields.forEach((field) => {
let element;
switch (field.type) {
case 'input':
element = document.createElement('input');
element.type = 'text';
element.id = field.id;
element.placeholder = field.placeholder;
element.value = field.startValue || '';
element.autocomplete = 'off';
break;
case 'color':
element = document.createElement('input');
element.type = 'color';
element.id = field.id;
element.value = field.startValue || '#000000';
break;
case 'checkbox':
element = document.createElement('label');
element.htmlFor = field.id;
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = field.id;
checkbox.checked = field.checked || false;
checkbox.addEventListener('change', (e) => field.onChange(e.target.checked));
element.appendChild(checkbox);
element.appendChild(document.createTextNode(field.label));
break;
case 'number':
element = document.createElement('input');
element.type = 'number';
element.id = field.id;
element.min = field.min;
element.max = field.max;
element.value = field.startValue || field.min;
break;
case 'range':
element = document.createElement('input');
element.type = 'range';
element.id = field.id;
element.min = field.min;
element.max = field.max;
element.value = field.startValue || field.min;
break;
case 'file':
element = document.createElement('input');
element.type = 'file';
element.id = field.id;
element.accept = field.accept;
element.addEventListener('change', (e) => field.onChange(e.target.files[0]));
break;
case 'header':
element = document.createElement('h3');
element.textContent = field.Name;
break;
case 'html':
element = document.createElement('div');
element.innerHTML = field.html;
break;
case 'select':
element = document.createElement('select');
element.id = field.id;
field.options.forEach((option) => {
const optionElement = document.createElement('option');
optionElement.value = option.value;
optionElement.textContent = option.text;
element.appendChild(optionElement);
});
element.value = field.startValue || field.options[0].value;
element.addEventListener('change', (e) => field.onChange(e.target.value));
break;
case 'button':
element = document.createElement('button');
element.type = 'button';
element.textContent = field.text;
element.addEventListener('click', field.onKlick);
break;
case 'date':
element = document.createElement('input');
element.type = 'date';
element.id = field.id;
element.value = field.startValue || new Date().toISOString().split('T')[0];
break;
case 'quill':
element = document.createElement('div');
element.id = field.id;
break;
case 'custom-number':
element = document.createElement('div');
element.className = 'number-input';
const downButton = document.createElement('button');
downButton.type = 'button';
downButton.className = 'down';
downButton.innerHTML = '<i class="fas fa-minus"></i>';
downButton.addEventListener('click', () => {
const input = element.querySelector('input[type=number]');
input.stepDown();
input.dispatchEvent(new Event('change'));
});
element.appendChild(downButton);
const input = document.createElement('input');
input.type = 'number';
input.id = field.id;
input.min = field.min;
input.max = field.max;
input.step = field.step;
input.value = field.startValue || field.min;
input.addEventListener('change', (e) => field.onChange(e.target.value));
element.appendChild(input);
const upButton = document.createElement('button');
upButton.type = 'button';
upButton.className = 'up';
upButton.innerHTML = '<i class="fas fa-plus"></i>';
upButton.addEventListener('click', () => {
const input = element.querySelector('input[type=number]');
input.stepUp();
input.dispatchEvent(new Event('change'));
});
element.appendChild(upButton);
break;
default:
console.error(`Unknown field type: ${field.type}`);
}
if (field.type !== 'checkbox') {
element.addEventListener('input', (e) => field.onChange(e.target.value));
}
form.appendChild(element);
form.appendChild(document.createElement('br'));
});
//register quill
this.fields.forEach((field) => {
if (field.type === 'quill') {
var settings = {
modules: {
toolbar: [
['bold', 'italic', 'underline', 'blockquote'],
[{'list': 'ordered'}, {'list': 'bullet'}],
['link'],
['clean']
]
},
theme: 'snow'
};
const quill = new Quill(`#${field.id}`, {
theme: 'snow',
placeholder: field.placeholder,
modules: {
toolbar: settings.modules.toolbar
},
});
quill.root.innerHTML = field.startValue || '';
quill.root.addEventListener('input', (e) => field.onChange(quill.root.innerHTML));
field.quill = quill;
}
});
// Add buttons
if (showButtons) {
const buttonContainer = document.createElement('div');
buttonContainer.className = 'button-container';
const saveButton = document.createElement('button');
saveButton.type = 'button';
saveButton.textContent = 'Speichern';
saveButton.addEventListener('click', () => {
this.submitForm();
});
const cancelButton = document.createElement('button');
cancelButton.type = 'button';
cancelButton.textContent = 'Abbrechen';
cancelButton.addEventListener('click', () => {
this.closeForm();
});
buttonContainer.appendChild(saveButton);
buttonContainer.appendChild(cancelButton);
form.appendChild(buttonContainer);
}
// submit form on enter
form.addEventListener('submit', (e) => {
e.preventDefault();
this.submitForm();
});
this.background.addEventListener('click', (e) => {
if (e.target === this.background) {
this.background.style.pointerEvents = 'none';
this.container.style.animation = 'form-container-out-animation 0.25s forwards';
this.background.style.animation = 'form-background-out-animation 0.25s forwards ease';
setTimeout(() => {
document.body.removeChild(this.background);
}, 500);
delete this;
}
});
}
}
class SystemMessage {
constructor(text) {
this.text = text;
this.duration = 5000;
}
setDuration(duration) {
this.duration = duration;
}
show() {
//wenn system-messages noch nicht existieren, erstellen
let systemMessages = document.querySelector('.system-messages');
if (!systemMessages) {
systemMessages = document.createElement('div');
systemMessages.className = 'system-messages';
document.body.appendChild(systemMessages);
}
const message = document.createElement('div');
message.className = 'system-message';
const text = document.createElement('p');
text.textContent = this.text;
message.appendChild(text);
const timebar = document.createElement('div');
timebar.className = 'timebar';
message.appendChild(timebar);
timebar.style.animation = `timebar-animation ${this.duration}ms linear forwards`;
systemMessages.appendChild(message);
setTimeout(() => {
message.style.animation = 'system-message-out-animation 0.25s forwards';
setTimeout(() => {
systemMessages.removeChild(message);
}, 500);
}, this.duration);
}
}
class KiChat {
constructor(apiKey) {
this.messages = [];
this.kontextParts = [];
this.timestamp = new Date().getTime();
this.container = document.createElement('div');
this.container.className = 'ki-chat';
this.container.classList.add('no-print');
this.header = document.createElement('div');
this.header.className = 'ki-chat-header';
this.headerChatsSelect = document.createElement('select');
this.headerChatsSelect.className = 'ki-chat-header-chats-select';
this.apiKey = apiKey;
this.updateChatsSelect();
this.headerChatsSelect.addEventListener('change', (e) => {
if (e.target.value === 'new') {
this.messages = [];
this.kontextParts = [];
this.timestamp = new Date().getTime();
this.renderMessages();
return;
}
const chats = JSON.parse(localStorage.getItem('chats'));
const chat = chats[e.target.value];
this.messages = chat.messages;
this.kontextParts = chat.kontextParts;
this.timestamp = e.target.value;
this.renderMessages();
});
this.header.appendChild(this.headerChatsSelect);
const headerClosed = document.createElement('div');
headerClosed.className = 'ki-chat-header-closed';
this.header.appendChild(headerClosed);
this.headerClose = document.createElement('i');
this.headerClose.className = 'ki-chat-header-close';
this.headerClose.classList.add('fas', 'fa-robot');
this.headerClose.style.fontSize = '1.5em';
this.headerClose.addEventListener('click', () => {
if (this.container.classList.contains('open')) {
const editChatForm = new FormBuilder('Chat bearbeiten', (formData) => {}, () => {});
//löschen button
editChatForm.addButton('Löschen', () => {
const chats = JSON.parse(localStorage.getItem('chats'));
delete chats[this.timestamp];
localStorage.setItem('chats', JSON.stringify(chats));
this.messages = [];
this.kontextParts = [];
this.updateChatsSelect();
editChatForm.closeForm();
this.renderMessages();
});
editChatForm.renderForm(false);
}
});
this.container.appendChild(this.header);
this.header.appendChild(this.headerClose);
this.chat = document.createElement('div');
this.chat.className = 'ki-chat-chat';
this.container.appendChild(this.chat);
this.chat.scrollTop = this.chat.scrollHeight;
this.chatInput = document.createElement('div');
this.chatInput.className = 'ki-chat-input';
this.container.appendChild(this.chatInput);
this.input = document.createElement('textarea');
this.input.placeholder = 'Nachricht';
this.chatInput.appendChild(this.input);
this.send = document.createElement('button');
this.send.textContent = 'Senden';
this.chatInput.appendChild(this.send);
this.send.addEventListener('click', () => {
this.sendMessage(this.input.value);
});
this.input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.sendMessage(this.input.value);
}
});
this.container.addEventListener('click', () => {
if (!this.container.classList.contains('open')) {
this.container.classList.add('open');
this.container.style.width = 'min(calc(100% - 20px), 500px)';
setTimeout(() => {
this.container.style.height = 'min(calc(100% - 150px), 700px)';
}, 100);
setTimeout(() => {
this.input.focus();
}, 500);
}
});
//wenn ausserhalb des chat-bereichs geklickt wird, wird der chat geschlossen
document.addEventListener('click', (e) => {
if (e.target !== this.container && !this.container.contains(e.target)) {
//wenn in einem formular geklickt wird, wird der chat nicht geschlossen
if (document.querySelector('.form-background')) return;
this.container.style.width = '65px';
setTimeout(() => {
this.container.style.height = '65px';
this.container.classList.remove('open');
}, 100);
}
});
document.body.appendChild(this.container);
this.renderMessages();
}
updateChatsSelect() {
this.headerChatsSelect.innerHTML = '';
const newChatOption = document.createElement('option');
newChatOption.value = 'new';
newChatOption.textContent = 'Neuer Chat';
this.headerChatsSelect.appendChild(newChatOption);
const chats = JSON.parse(localStorage.getItem('chats')) || {};
// Sort timestamps so that newest chats appear first
const timestamps = Object.keys(chats).sort((a, b) => parseInt(b, 10) - parseInt(a, 10));
timestamps.forEach((timestamp) => {
const chat = chats[timestamp];
const option = document.createElement('option');
option.value = timestamp;
option.textContent = new Date(parseInt(timestamp)).toLocaleString('de-DE', { hour: '2-digit', minute: '2-digit', day: '2-digit', month: 'numeric', year: 'numeric' }).split(', ').reverse().join(', ');
//füge dem textContent die ersten 100 zeichen des ersten parts hinzu
if (chat.messages && chat.messages[0] && chat.messages[0].parts && chat.messages[0].parts[0] && chat.messages[0].parts[0].text.length > 30) {
option.textContent += ': ' + chat.messages[0].parts[0].text.substring(0, 30) + '...';
} else if (chat.messages && chat.messages[0] && chat.messages[0].parts && chat.messages[0].parts[0]) {
option.textContent += ': ' + chat.messages[0].parts[0].text;
}
this.headerChatsSelect.appendChild(option);
});
//wenn es kein chat mit dem timestamp gibt, wird der new chat ausgewählt, sonst der letzte chat
if (!chats[this.timestamp]) {
this.headerChatsSelect.value = 'new';
} else {
this.headerChatsSelect.value = this.timestamp;
}
}
saveToStorage() {
//in localstorage bei chats array den neuen chat speichern mit timestamp als key und value mit messages und kontextParts
let chats = JSON.parse(localStorage.getItem('chats')) || {};
chats[this.timestamp] = {messages: this.messages, kontextParts: this.kontextParts};
localStorage.setItem('chats', JSON.stringify(chats));
}
async sendMessage(prompt) {
if (!prompt || (typeof prompt === 'string' && prompt.trim() === '')) return;
this.input.value = '';
//close keyboard on mobile
this.input.blur();
this.messages.push({
role: 'user',
parts: [
{ text: prompt }
]
});
this.renderMessages();
this.showTypingIndicator();
const response = await this.generateResponse(this.messages);
// response is an object: { content, relatedQuestions, links }
const modelMessage = {
role: 'model',
parts: [
{ text: (response && response.content) ? response.content : (typeof response === 'string' ? response : '') }
]
};
if (response && response.links && response.links.length) modelMessage.links = response.links;
if (response && response.relatedQuestions && response.relatedQuestions.length) modelMessage.relatedQuestions = response.relatedQuestions;
this.messages.push(modelMessage);
this.renderMessages();
this.saveToStorage();
this.updateChatsSelect();
}
renderMessages() {
this.chat.innerHTML = '';
//add start message "Hallo, ich bin CookMate, dein persönlicher Rezept-Assistent. Wie kann ich dir helfen?"
this.addRenderedMessage({ parts: [{ text: "Hallo, ich bin CookMate, dein persönlicher Rezept-Assistent. Wie kann ich dir helfen?" }] }, 'model', false);
this.messages.forEach((message, idx) => {
const isLast = idx === (this.messages.length - 1);
this.addRenderedMessage(message, message.role, isLast);
});
}
addRenderedMessage(message, role, isLast = false) {
// message is an object with .parts (array of {text}) and optional .links (array of {title, uri})
const messageElement = document.createElement('div');
messageElement.className = `ki-chat-message ki-chat-message-${role}`;
const parts = message.parts || [];
parts.forEach((part) => {
const partElement = document.createElement('p');
partElement.innerHTML = marked.parse(part.text);
messageElement.appendChild(partElement);
});
// if there are links, render them as buttons under the message
if (message.links && Array.isArray(message.links) && message.links.length) {
const linksContainer = document.createElement('div');
linksContainer.className = 'ki-chat-links-container';
message.links.forEach((link) => {
const btn = document.createElement('button');
btn.className = 'ki-chat-link-button';
// show a short label: title or hostname
let label = link.title || link.uri || link;
try {
// if label is long, shorten
if (label.length > 60) label = label.substring(0, 57) + '...';
} catch (e) {}
btn.textContent = label;
btn.addEventListener('click', (e) => {
// open in new tab/window
const url = link.uri || link;
if (!url) return;
window.open(url, '_blank');
});
linksContainer.appendChild(btn);
});
messageElement.appendChild(linksContainer);
}
// if there are related questions, render them as small buttons as well
// Show related questions ONLY if this is the last (bottom-most) message
if (isLast && message.relatedQuestions && Array.isArray(message.relatedQuestions) && message.relatedQuestions.length) {
const rqContainer = document.createElement('div');
rqContainer.className = 'ki-chat-related-questions';
message.relatedQuestions.forEach((q) => {
const qbtn = document.createElement('button');
qbtn.className = 'ki-chat-related-question-button';
qbtn.textContent = q;
// When clicking a related question, send it immediately in the same chat
qbtn.addEventListener('click', (e) => {
e.stopPropagation();
// Use the chat instance's sendMessage to submit the question directly
this.sendMessage(q);
});
rqContainer.appendChild(qbtn);
});
messageElement.appendChild(rqContainer);
}
this.chat.appendChild(messageElement);
this.chat.scrollTop = this.chat.scrollHeight;
}
addKontext(kontext) {
if (kontext.name === 'Rezept') {
let response = "'" + kontext.value.Name + "' ist für " + kontext.value.Portionen + " Portionen und dauert " + kontext.value.Zeit + " Minuten. Die Zutaten sind: ";
kontext.value.Zutaten_JSON.forEach((zutat) => {
response += zutat.Menge + " " + zutat.unit + " " + zutat.Name + ", ";
});
response += "Die Zubereitung ist: " + kontext.value.Zubereitung;
this.kontextParts.push({
role: 'model',
parts: [
{ text: response }
]
});
}
this.renderMessages();
}
async generateResponse(prompt) {
try {
const url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-preview:generateContent?key=" + this.apiKey;
//bei prompt ganz oben die kontextParts hinzufügen
prompt = this.kontextParts.concat(prompt);
// Sanitize contents: the API rejects unknown fields like `links` or `relatedQuestions` inside contents.
// Build a cleaned array that only contains allowed properties (role, parts, maybe name) to avoid INVALID_ARGUMENT errors.
const sanitizedContents = (prompt || []).map((item) => {
const clean = {};
if (item.role) clean.role = item.role;
if (item.parts) clean.parts = item.parts;
if (item.name) clean.name = item.name;
return clean;
});
const jsonInput = JSON.stringify({
contents: sanitizedContents,
systemInstruction: {
role: "user",
parts: [
{
text: "Dein Name ist CookMate, du bist ein Unterstützer für eine Rezepte-Kochwebseite. Antworte nur auf die Fragen, die etwas mit Zutaten, Rezepten oder Kochen zu tun haben. Wenn die Frage nicht zu deinem Fachgebiet passt, antworte mit 'Das liegt nicht in meinem Fachgebiet, oder gebe mir mehr Informationen'. Aber auf Höflichkeitsfragen darfst du antworten. Der Entwickler der Seite ist Leon Rabe, wenn der benutzer Hilfe bezüglich der Webseite benötigt, soll er sich an ihn wenden. Schreib das aber nur, wenn du dir sicher bist, dass es eine Frage zu der Webseite ist, also das ausdrücklich erwähnt wird."
},
{
text: "Finde auf die Antwort der Frage weitere 3 kurze Fragen, die sich auf die Antwort beziehen."
}
]
},
generationConfig: {
temperature: 1,
topK: 40,
topP: 0.95,
maxOutputTokens: 8192,
response_mime_type: "application/json",
response_schema: {
type: "OBJECT",
properties: {
content: {type:"STRING"},
relatedQuestions: {
type:"ARRAY", items: {
type:"STRING"
}
},
},
required: ["content"],
},
thinkingConfig: {
thinkingLevel: "LOW"
}
},
tools: [
{
googleSearch: {}
}
]
});
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: jsonInput
});
console.log(JSON.parse(jsonInput));
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const jsonResponse = await response.json();
const candidate = jsonResponse.candidates && jsonResponse.candidates[0];
if (!candidate) return { content: 'Keine Antwort erhalten', relatedQuestions: [], links: [] };
// Parse the generated content which is stored as a JSON string in candidate.content.parts[0].text
let content = '';
let relatedQuestions = [];
try {
const text = candidate.content.parts[0].text;
const parsed = JSON.parse(text);
content = parsed.content || '';
relatedQuestions = parsed.relatedQuestions || [];
} catch (e) {
// fallback: use raw text
try {
content = candidate.content.parts[0].text || '';
} catch (e2) {
content = '';
}
}
// Extract grounding links if present
let links = [];
try {
const gm = candidate.groundingMetadata;
if (gm) {
// prefer groundingChunks with web entries
if (Array.isArray(gm.groundingChunks) && gm.groundingChunks.length) {
gm.groundingChunks.forEach((chunk) => {
if (chunk.web && chunk.web.uri) {
links.push({ title: chunk.web.title || chunk.web.uri, uri: chunk.web.uri });
}
});
}
// fallback: parse searchEntryPoint.renderedContent for anchor tags (runs in browser)
if (!links.length && gm.searchEntryPoint && gm.searchEntryPoint.renderedContent) {
try {
const tmp = document.createElement('div');
tmp.innerHTML = gm.searchEntryPoint.renderedContent;
const anchors = tmp.querySelectorAll('a');
anchors.forEach((a) => {
const href = a.getAttribute('href');
const title = a.textContent || href;
if (href) links.push({ title: title.trim(), uri: href });
});
} catch (e) {
// ignore
}
}
}
} catch (e) {
// ignore
}
return { content, relatedQuestions, links };
} catch (error) {
console.error(error);
return { content: `Error: ${error.message}`, relatedQuestions: [], links: [] };
}
}
showTypingIndicator() {
const typingIndicator = document.createElement('div');
typingIndicator.className = 'ki-chat-typing-indicator';
const dots = document.createElement('div');
dots.className = 'ki-chat-typing-indicator-dots';
typingIndicator.appendChild(dots);
const dot1 = document.createElement('div');
dot1.className = 'ki-chat-typing-indicator-dot';
dot1.style.animationDelay = '0s';
dots.appendChild(dot1);
const dot2 = document.createElement('div');
dot2.className = 'ki-chat-typing-indicator-dot';
dot2.style.animationDelay = '0.20s';
dots.appendChild(dot2);
const dot3 = document.createElement('div');
dot3.className = 'ki-chat-typing-indicator-dot';
dot3.style.animationDelay = '0.4s';
dots.appendChild(dot3);
this.chat.appendChild(typingIndicator);
this.chat.scrollTop = this.chat.scrollHeight;
}
}
document.querySelectorAll('.horizontalScrollBarJS').forEach((element) => {
let scrollAmount = 0;
let isScrolling = false;
let isDragging = false;
let startX;
let scrollLeft;
element.addEventListener('wheel', function(event) {
if (event.deltaY !== 0) {
event.preventDefault();
scrollAmount += event.deltaY;
if (!isScrolling) {
isScrolling = true;
requestAnimationFrame(smoothScroll);
}
}
});
element.addEventListener('mousedown', (event) => {
isDragging = true;
startX = event.pageX - element.offsetLeft;
scrollLeft = element.scrollLeft;
element.classList.add('active');
});
element.addEventListener('mouseleave', () => {
isDragging = false;
element.classList.remove('active');
});
element.addEventListener('mouseup', () => {
isDragging = false;
element.classList.remove('active');
});
element.addEventListener('mousemove', (event) => {
if (!isDragging) return;
event.preventDefault();
const x = event.pageX - element.offsetLeft;
const walk = (x - startX) * 1.5; // The multiplier can be adjusted for sensitivity