-
Notifications
You must be signed in to change notification settings - Fork 0
/
meai.html
1073 lines (912 loc) · 45 KB
/
meai.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
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">
<link rel="shortcut icon" type="image/png"
href="https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73500d39-5ecb-44f8-9188-f44c25addc6b_160x160.png">
<meta http-equiv="Page-Enter" content="blendTrans(Duration=.5)" />
<meta http-equiv="Page-Exit" content="blendTrans(Duration=.5)" />
<title>ME_AI - Markdown editor with AI </title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
<link rel="stylesheet" href="meai.css">
<style>
body {
opacity: 0;
}
</style>
</head>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-FJWPNMDQTK"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-FJWPNMDQTK');
</script>
<body>
<div class="container">
<div class="editor">
<textarea id="markdown-editor">
# Markdown Syntax Samples
## Headers
This is some text
# Header 1
## Header 2
### Header 3
## Emphasis
*Italic Text*
**Bold Text**
***Bold Italic Text***
## Lists
### Unordered List
- Item 1
- Item 2
- Subitem 1
- Subitem 2
### Ordered List
1. First Item
2. Second Item
1. Subitem A
2. Subitem B
## Links
[Visit OpenAI](https://www.openai.com)
[Visit GitHub](https://www.github.com)
## Images
![Alt Text](https://www.example.com/image.jpg)
## Blockquotes
> This is a blockquote.
> It can span multiple lines.
## Code
### Inline Code
Use backticks to highlight `inline code`.
### Code Block
```python
def greet(name):
print(f"Hello, {name}!")
</textarea>
<div id="promptOverlay" class="contrainer" data-bs-theme="dark">
<!-- <div id="promptIcon">✨</div> -->
<div class="col" data-bs-theme="dark">
<div class="row">
<div
class="d-flex flex-column flex-md-row p-4 gap-4 py-md-5 align-items-center justify-content-center">
<textarea id="promptText"
placeholder="✨ Ask AI to write anything... e.g. 'Write me a blogpost.'"></textarea>
</div>
</div>
<div class="row">
<div
class="d-flex flex-column flex-md-row p-4 gap-4 py-md-5 align-items-center justify-content-center">
<ul id="promptHistoryList" class="dropdown-menu position-static d-grid rounded-2 w-220px">
<li class="dropdown-item disabled">No history yet</li>
</ul>
</div>
</div>
</div>
</div>
<div class="context-menu" id="contextMenu" data-bs-theme="dark">
<ul data-bs-theme="dark"
class="dropdown-menu position-static d-grid gap-1 p-2 rounded-3 mx-0 border-0 shadow w-220px">
<li class="dropdown-item" href="#" id="autoComplete">Autocomplete</li>
<li class="dropdown-item" href="#" id="makeFluent">Make it Fluent</li>
<li class="dropdown-item" href="#" id="paraphrase">Paraphrase</li>
<li class="dropdown-item" href="#" id="correctSpelling">Correct Spelling</li>
</ul>
</div>
<div class="text-area-overlay" id="loadingOverlay">
<div class="text-area-loading-spinner"></div>
</div>
<!-- FILEPATH: /Users/erengolge/Projects/erogol.github.io/meai.html -->
<div id="settings-window" class="card text-light" style="background-color: #212529;">
<div class="card-header d-flex justify-content-between">
<h2>Settings</h2>
<button type="button" class="btn-close btn-close-white" aria-label="Close"
id="settingsCloseBtn"></button>
</div>
<div class="card-body">
<div class="mb-3">
<label for="apiKeyInput" class="form-label">OpenAI API Key</label>
<div class="input-group">
<input type="text" class="form-control" id="apiKeyInput"
placeholder="Enter your API key here">
</div>
</div>
<div class="mb-3">
<label for="maxTokensInput" class="form-label"
title="Maximum number of tokens that can be returned by the API.">Max Tokens</label>
<div class="input-group">
<input type="number" class="form-control" id="maxTokensInput"
title="Maximum number of tokens that can be returned by the API."
placeholder="Enter the max number of tokens here">
</div>
</div>
<div class="mb-3">
<label for="apiTimeoutInput" class="form-label"
title="Seconds to timeout hanging API call.">Request Timeout</label>
<div class="input-group">
<input type="number" class="form-control" id="apiTimeoutInput"
title="Seconds to timeout hanging API call." placeholder="Enter secs to timeout here.">
</div>
</div>
<!-- single save button -->
<button class="btn btn-outline-light" type="button" id="saveSettingsBtn">Save All Settings</button>
</div>
</div>
<div id="help-window">
<button type="button" class="btn-close btn-close-white closeButton" aria-label="Close"
id="helpCloseBtn"></button>
<!-- <div class="closeButton" id="helpCloseBtn">X</div> -->
<h1>🤖 ME-AI</h1>
<p>
aka Markdown editor with AI.<br><br>
</p>
<h1>Usage</h1>
<p>
<div>
<p>To access the AI options, simply right-click anywhere in the editor.</p><br>
<h3>AI Command Menu</h3>
<p>The menu will then appear, providing you with a range of choices:</p>
<ul>
<li>Autocomplete: Autocompletes the selected text.</li>
<li>Make It Fluent: Makes the selected text fluent.</li>
<li>Paraphrase: Paraphrases the selected text.</li>
<li>Correct Spelling: Corrects the spelling of the selected text.</li>
</ul><br>
<h3>Ask AI to do anything</h3>
<ol>
<li>(Optional) Select a text.</li>
<li>Press <strong>Ctrl+Shift+P</strong></li>
<li>Type your command and press Enter.</li>
</ol><br>
<h3>Toolbar</h3>
<p>The editor is equipped with a convenient toolbar that becomes visible when you hover your
mouse
at the top. In addition to the classic editor options, it also offers a few additional
features:
</p>
<ul>
<li>Preview: Toggle the preview pane.</li>
<li>Save: Save the text to local storage, so you can continue writing next time.</li>
<li>Load: Load the text from local storage.</li>
<li>Download: Download the text as a .md file.</li>
<li>Upload: Upload a .md file to the editor.</li>
<li>Help: Show this help dialog.</li>
</ul><br><br>
<h1>Notes</h1>
<ul>
<li>ME-AI does not retain any of your data including your API key.</li>
<li>ME_AI requires you to enter an OpenAI API key to use the AI functions.</li>
<li>🤖 is a fully local. There is no server in the background.</li>
<li>If no text selected, 🤖 will try to update the last paragraph.</li>
<li>The editor automatically saves the current content to local storage every minute,
allowing
you to conveniently resume your work later.</li>
</ul><br><br>
<!-- Do not show me again checkbox -->
<!-- Do not show me again checkbox -->
<div class="form-check">
<input class="form-check-input" type="checkbox" id="doNotShowAgainCheckbox">
<label class="form-check-label" for="doNotShowAgainCheckbox">
Do not show me this at start.
</label>
</div>
</div>
</div>
</div>
</p>
</div>
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsdiff/5.0.0/diff.min.js"></script>
<script src="app.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
var contextMenu = document.getElementById("contextMenu");
var editorDiv = document.querySelector(".editor");
var promptForum = document.getElementById("promptOverlay");
var simplemde;
var savedScrollInfo = null;
var cursorPosition = null;
var loadingOverlay = document.getElementById("loadingOverlay"); // Get the loading overlay
var helpWindow = document.getElementById("help-window");
var helpWindowCloseBtn = document.getElementById("helpCloseBtn");
var previousText = ""; // Store the previous text for highlighting
var promptHistoryList = document.getElementById("promptHistoryList"); // Get the prompt text field
// ##############################################
// ############# EDITOR BUTTONS ###############
// ##############################################
var saveAction = function (editor) {
// Load the text from local storage and set it to SimpleMDE
console.log("Saving text to local storage");
localStorage.setItem("editorText", simplemde.codemirror.getValue());
};
var loadAction = function (editor) {
// Load the text from local storage and set it to SimpleMDE
console.log("Loading text from local storage");
simplemde.value(localStorage.getItem("editorText"));
};
var deleteAction = function (editor) {
// Show a confirmation dialog before deleting the text from local storage
var confirmed = confirm("❗ This nukes all the text. Are you sure?");
if (confirmed) {
// Delete the text from local storage
console.log("Deleting text from local storage");
localStorage.removeItem("ed☢️itorText");
simplemde.value("");
}
};
var downloadAction = function (editor) {
// Get the content from the editor
var content = simplemde.value();
// Create a Blob with the content
var blob = new Blob([content], { type: "text/plain" });
// Create a downloadable URL for the Blob
var url = URL.createObjectURL(blob);
// Create a link element for downloading
var downloadLink = document.createElement("a");
downloadLink.href = url;
downloadLink.download = "markdown.txt"; // Specify the filename
downloadLink.textContent = "Download"; // Displayed text
downloadLink.style.display = "none"; // Hide the link
// Append the link to the document and simulate a click
document.body.appendChild(downloadLink);
downloadLink.click();
// Clean up
document.body.removeChild(downloadLink);
URL.revokeObjectURL(url);
};
var uploadAction = function (editor) {
// Create an input element for file selection
var fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.accept = ".txt"; // Accept only text files
fileInput.style.display = "none"; // Hide the input
// Append the input to the document and simulate a click
document.body.appendChild(fileInput);
fileInput.click();
// Listen for the file input change event
fileInput.addEventListener("change", function (e) {
var file = e.target.files[0];
if (file) {
var reader = new FileReader();
reader.onload = function (event) {
// Set the loaded content to the editor
simplemde.value(event.target.result);
};
reader.readAsText(file);
}
// Clean up the input element
document.body.removeChild(fileInput);
});
};
var helpAction = function (editor) {
// Show a help dialog
helpWindow.style.display = "block";
document.getElementById("doNotShowAgainCheckbox").checked = localStorage.getItem("doNotShowAgain");
helpWindowCloseBtn = document.createElement("div");
};
var resetApiKeyAction = function (editor) {
// Show a confirmation dialog before deleting the text from local storage
var confirmed = confirm("❗ This will reset your API key. Are you sure?");
if (confirmed) {
// Delete the text from local storage
console.log("Deleting API key from local storage");
localStorage.removeItem("API_KEY");
API_KEY = null;
}
set_api_key();
};
// Open the settings window
var openSettingsWindow = function (editor) {
// Show the settings window
document.getElementById("settings-window").style.display = "block";
console.log("Opening settings window");
};
simplemde = new SimpleMDE({
element: document.getElementById("markdown-editor"),
toolbar: [
"bold", "italic", "heading", "|", "quote", "unordered-list", "ordered-list", "|",
"link", "image", "table", "|", "preview", "side-by-side", "fullscreen", "|",
{
name: "save",
action: saveAction,
className: "fa fa-save",
title: "Save to Cache"
},
{
name: "load",
action: loadAction,
className: "fa fa-undo",
title: "Load from Cache"
},
{
name: "delete",
action: deleteAction,
className: "fa fa-trash",
title: "Empty Cache"
},
{
name: "download",
action: downloadAction,
className: "fa fa-download",
title: "Download"
},
{
name: "upload",
action: uploadAction,
className: "fa fa-upload",
title: "Upload",
}, "|",
{
name: "settings",
action: openSettingsWindow,
className: "fa fa-cog",
title: "Settings"
},
{
name: "reset-api-key",
action: resetApiKeyAction,
className: "fa fa-key",
title: "Reset API Key"
},
{
name: "help",
action: helpAction,
className: "fa fa-question-circle",
title: "Help"
},
],
// Apply custom styles for full-screen mode
fullscreenToggle: true,
onToggleFullScreen: function (isFullScreen) {
if (isFullScreen) {
// Apply custom styles for full-screen mode
document.querySelector(".editor-toolbar").style.backgroundColor = "#3a3a3a";
document.querySelector(".editor-toolbar").style.color = "#d4d4d4";
} else {
// Restore original styles when exiting full-screen mode
document.querySelector(".editor-toolbar").style.backgroundColor = "#3a3a3a";
document.querySelector(".editor-toolbar").style.color = "#d4d4d4";
}
}
});
// Load the text from local storage and set it to SimpleMDE
var savedText = localStorage.getItem("editorText");
if (savedText) {
previousText = savedText;
simplemde.value(savedText);
}
editorDiv.addEventListener("contextmenu", function (e) {
if (!e.shiftKey) {
e.preventDefault();
contextMenu.style.left = e.pageX + "px";
contextMenu.style.top = e.pageY + "px";
contextMenu.classList.add("active");
}
});
document.addEventListener("click", function (e) {
if (!contextMenu.contains(e.target)) {
contextMenu.classList.remove("active");
}
contextMenu.classList.remove("active");
});
// Close the help window when the close button is clicked
helpWindowCloseBtn.addEventListener("click", function () {
helpWindow.style.display = "none";
localStorage.setItem("doNotShowAgain", document.getElementById("doNotShowAgainCheckbox").checked);
helpWindow.removeChild(helpWindowCloseBtn);
});
// Show the help window at start
if (localStorage.getItem("doNotShowAgain") !== "true") {
document.getElementById("doNotShowAgainCheckbox").checked = !localStorage.getItem("doNotShowAgain");
helpWindow.style.display = "block";
}
/**************************************************************
* UTILS
* ***********************************************************/
function add_prompt_to_favorite() {
// Get the prompt text
var instruction = get_prompt();
if (instruction !== '') {
if (!favPromptList.includes(instruction)) {
favPromptList.push(instruction);
localStorage.setItem('favPrompts', JSON.stringify(favPromptList));
}
}
}
function delete_prompt_from_favorite(instruction) {
// Get the prompt text
if (instruction !== '') {
if (favPromptList.includes(instruction)) {
var index = favPromptList.indexOf(instruction);
if (index > -1) {
favPromptList.splice(index, 1);
}
localStorage.setItem('favPrompts', JSON.stringify(favPromptList));
}
}
}
function update_prompt_history_list() {
// Clear existing list
while (promptHistoryList.firstChild) {
promptHistoryList.removeChild(promptHistoryList.firstChild);
}
// Re-create list from updated promptHistory array
promptHistory.forEach(function (value) {
createPromptHistoryList(value);
});
}
function createPromptHistoryList(value) {
var li = document.createElement('li');
li.className = 'h-100 text-truncate list-group-item list-group-item-action prompt-history-item';
// li.style = 'display: flex;';
var a = document.createElement('a');
a.className = 'text-truncate dropdown-item rounded-2';
a.href = '#';
var del_button = document.createElement('button');
del_button.className = 'btn btn-sm delete-button';
del_button.style = 'color: gray;';
var i = document.createElement('i');
i.className = 'bi bi-x-circle';
del_button.appendChild(i);
// a.appendChild(del_button);
del_button.addEventListener('click', function (e) {
e.stopPropagation();
var index = promptHistory.indexOf(value);
if (index > -1) {
promptHistory.splice(index, 1);
}
localStorage.setItem('promptHistory', JSON.stringify(promptHistory));
update_prompt_history_list();
});
// add favorite button
var fav_button = document.createElement('button');
fav_button.className = 'btn btn-sm fav-button bi bi-star';
fav_button.style = 'color: gray;';
fav_button.addEventListener('click', function (e) {
// stops the click event from triggering the event on the parent element
e.stopPropagation();
if (!favorites.includes(value)) {
favorites.push(value);
localStorage.setItem('favorites', JSON.stringify(favorites));
}
});
a.appendChild(del_button);
a.appendChild(fav_button);
a.appendChild(document.createTextNode(value));
li.appendChild(a);
// Add click event listener to li
li.addEventListener('click', function () {
// Get textarea by id and set its value to the clicked list item's text
set_prompt_text(value);
document.getElementById('promptText').focus();
resizeTextarea();
});
promptHistoryList.appendChild(li);
}
function get_favorite_prompt_history() {
favPromptHistory = JSON.parse(localStorage.getItem("favPromptHistory")) || [];
return favPromptHistory;
}
function get_prompt_history() {
promptHistory = JSON.parse(localStorage.getItem("promptHistory")) || [];
return promptHistory;
}
// Function to show the loading overlay
function showLoadingOverlay() {
loadingOverlay.style.display = "flex";
// Set the loading spinner off with a delay
setTimeout(function () {
loadingOverlay.style.opacity = 1;
}, 100);
}
// Function to hide the loading overlay
function hideLoadingOverlay() {
loadingOverlay.style.display = "none";
}
// Function to get the paragraph where the cursor is located
function getCurrentParagraph() {
cursorPosition = simplemde.codemirror.getCursor();
var lineNumber = cursorPosition.line;
var content = simplemde.value();
var lines = content.split("\n");
var currentParagraph = "";
for (var i = lineNumber; i >= 0; i--) {
if (lines[i].trim() === "") {
break;
} else if (lines[i].startsWith("#")) {
currentParagraph = lines[i] + "\n" + currentParagraph;
break;
} else if (/^(\*|\-|\+|\d+\.)\s/.test(lines[i])) {
currentParagraph = lines[i] + "\n" + currentParagraph;
break;
} else {
currentParagraph = lines[i] + "\n" + currentParagraph;
}
}
return currentParagraph.trim();
}
document.getElementById("settingsCloseBtn").onclick = function () {
document.getElementById("settings-window").style.display = "none";
}
/**************************************************************
* Prompt Dialog
* ***********************************************************/
function openPromptDialog() {
document.getElementById('promptOverlay').style.display = 'flex';
// set the cursor to the prompt text
document.getElementById('promptText').focus();
const textarea = document.getElementById('promptText');
textarea.style.height = 'auto';
textarea.style.height = textarea.scrollHeight + 'px';
// append prompt history to the prompt history list
favPromptHistory = get_favorite_prompt_history();
promptHistory = get_prompt_history();
// merge prompt history and fav prompt history
promptHistory = favPromptHistory.concat(promptHistory);
if (promptHistory.length > 0) {
promptHistoryList.innerHTML = '';
promptHistory.forEach(createPromptHistoryList);
}
}
function closePromptDialog() {
document.getElementById('promptOverlay').style.display = 'none';
// if there is no text except ✨ in the field then clear the field
if (document.getElementById('promptText').value === '✨ ') {
document.getElementById('promptText').value = '';
}
// Update prompt history
console.log("Updating prompt history")
instruction = get_prompt()
if (instruction !== '') {
if (!promptHistory.includes(instruction)) {
promptHistory.unshift(instruction);
console.log(promptHistory);
localStorage.setItem('promptHistory', JSON.stringify(promptHistory));
} else {
console.log("Instruction already exists in prompt history")
var index = promptHistory.indexOf(instruction);
if (index > -1) {
promptHistory.splice(index, 1);
}
promptHistory.unshift(instruction);
localStorage.setItem('promptHistory', JSON.stringify(promptHistory));
}
}
}
// close prompt dialog when user clicks outside of the dialog or press ESC
promptForum.addEventListener("click", function (e) {
if (!promptForum.contains(e.target)) {
closePromptDialog();
}
});
document.addEventListener("keydown", function (e) {
if (e.key === "Escape") {
closePromptDialog();
}
});
function resizeTextarea() {
const textarea = document.getElementById('promptText');
textarea.style.height = 'auto';
textarea.style.height = textarea.scrollHeight + 'px';
// prepend ✨ and a space to the prompt text as the first character if it is not already there
if (textarea.value[0] !== '✨') {
textarea.value = '✨ ' + textarea.value;
}
}
function get_prompt() {
instruction = document.getElementById('promptText').value;
// remove ✨ from the prompt text
instruction = instruction.replace('✨ ', '');
return instruction;
}
function set_prompt_text(text) {
document.getElementById('promptText').value = '✨ ' + text;
}
promptText.addEventListener('input', resizeTextarea);
// get the entered text from the prompt dialog when it is active and pressed enter
document.getElementById('promptText').addEventListener("keydown", async function (e) {
if (event.key === 'Enter' && event.shiftKey) {
// If Shift + Enter is pressed, insert a new line character
const cursorPosition = promptText.selectionStart;
const textBeforeCursor = promptText.value.substring(0, cursorPosition);
const textAfterCursor = promptText.value.substring(cursorPosition);
promptText.value = textBeforeCursor + '\n' + textAfterCursor;
// Prevent the default behavior of Enter key (submitting the form in a textarea)
event.preventDefault();
}
else if (e.key === "Enter") {
event.preventDefault();
instruction = get_prompt();
showLoadingOverlay();
// Set the input text
var selectedText = simplemde.codemirror.getSelection();
previousText = simplemde.codemirror.getValue();
// Keep the scroll position the same after updating the text
savedScrollInfo = simplemde.codemirror.getScrollInfo();
if (instruction === null) {
// User clicked cancel
console.log("User cancelled the prompt");
} else {
// User entered an instruction
console.log("User entered instruction:", instruction);
console.log("Selected text:", selectedText);
// Do something with the user's instruction (you can send it to your AI model)
const ai_response = await userInstruction(instruction, selectedText);
console.log(ai_response);
if (ai_response) {
if (selectedText) {
const updatedContent = simplemde.value().replace(selectedText, ai_response);
simplemde.value(updatedContent);
}
else {
insertTextAtCursor(ai_response);
}
}
}
if (savedScrollInfo) {
simplemde.codemirror.scrollTo(savedScrollInfo.left, savedScrollInfo.top);
savedScrollInfo = null; // Reset after restoration
}
hideLoadingOverlay();
highlightAddedText();
closePromptDialog();
// pass focus to the editor
simplemde.codemirror.focus();
}
});
// Listen for Ctrl+Shift+P (Cmd+Shift+P on Mac)
document.addEventListener("keydown", function (e) {
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "p") {
// show prompt forum
openPromptDialog();
}
});
/**************************************************************
* CONTEXT MENU
* ***********************************************************/
contextMenu.addEventListener("click", async function (e) {
// Keep the scroll position the same after updating the text
var selectedText = simplemde.codemirror.getSelection();
savedScrollInfo = simplemde.codemirror.getScrollInfo();
previousText = simplemde.codemirror.getValue();
showLoadingOverlay();
if (e.target.id === "autoComplete") {
if (selectedText) {
await autoCompleteText(selectedText);
}
else {
var lastParagraph = getCurrentParagraph();
console.log(lastParagraph);
if (lastParagraph) {
await autoCompleteText(lastParagraph);
}
}
}
if (e.target.id === "makeFluent") {
if (selectedText) {
await makeFluentLastParagraph(selectedText);
}
else {
var lastParagraph = getCurrentParagraph();
if (lastParagraph) {
await makeFluentLastParagraph(lastParagraph);
}
}
}
if (e.target.id === "paraphrase") {
if (selectedText) {
await paraphraseLastParagraph(selectedText);
}
else {
var lastParagraph = getCurrentParagraph();
if (lastParagraph) {
await paraphraseLastParagraph(lastParagraph);
}
}
}
if (e.target.id === "correctSpelling") {
if (selectedText) {
await correctSpellingText(selectedText);
}
else {
var lastParagraph = getCurrentParagraph();
if (lastParagraph) {
await correctSpellingText(lastParagraph);
}
}
}
if (savedScrollInfo) {
simplemde.codemirror.scrollTo(savedScrollInfo.left, savedScrollInfo.top);
savedScrollInfo = null; // Reset after restoration
}
hideLoadingOverlay();
highlightAddedText();
});
// Function to auto complete the last paragraph
// Function to auto-complete text
async function autoCompleteText(inputText) {
// const response = await fetch("http://127.0.0.1:5000/auto_complete", {
// method: "POST",
// headers: {
// "Content-Type": "application/json"
// },
// body: JSON.stringify({ input: inputText })
// });
// const data = await response.json();
// const autoCompletion = data.auto_completion;
const autoCompletion = await auto_complete(inputText)
console.log(autoCompletion);
if (autoCompletion) {
simplemde.codemirror.replaceSelection(autoCompletion);
// Get the start and end positions of the inserted text
var fromPos = simplemde.codemirror.indexFromPos(cursorPosition);
var toPos = fromPos + autoCompletion.length;
// Remove the highlighting class after the specified duration
console.log("Marking inserted text:", fromPos, toPos);
simplemde.codemirror.markText(
simplemde.codemirror.posFromIndex(fromPos),
simplemde.codemirror.posFromIndex(toPos),
{ className: "highlight-inserted" }
);
setTimeout(function () {
console.log("Clearing highlights");
simplemde.codemirror.getAllMarks().forEach(function (mark) {
if (mark.className === "highlight-inserted") {
mark.clear();
}
});
}, 3000);
}
}
// Function to make the last paragraph fluent
async function makeFluentLastParagraph(lastParagraph) {
// const response = await fetch("http://127.0.0.1:5000/make_fluent", {
// method: "POST",
// headers: {
// "Content-Type": "application/json"
// },
// body: JSON.stringify({ input: lastParagraph })
// });
// const data = await response.json();
// const fluentResponse = data.fluent_response;
const fluentResponse = await make_fluent(lastParagraph)
if (fluentResponse) {
const updatedContent = simplemde.value().replace(lastParagraph, fluentResponse);
simplemde.value(updatedContent);
}
}
// Function to make the last paragraph fluent
async function paraphraseLastParagraph(lastParagraph) {
// const response = await fetch("http://127.0.0.1:5000/paraphrase", {
// method: "POST",
// headers: {
// "Content-Type": "application/json"
// },
// body: JSON.stringify({ input: lastParagraph })
// });
// const paraphraseRespose = await response.json();
// const paraphraseRespose = data.paraphrase_response;
const paraphraseRespose = await paraphrase(lastParagraph)
console.log(paraphraseRespose);
if (paraphraseRespose) {
const updatedContent = simplemde.value().replace(lastParagraph, paraphraseRespose);
simplemde.value(updatedContent);
}
}
//Fucntion to correct spelling
async function correctSpellingText(inputText) {
const response = await correctSpelling(inputText)
console.log(response)
if (response) {
const updatedContent = simplemde.value().replace(inputText, response);
simplemde.value(updatedContent);
}
}
// Function to insert text at the cursor position
function insertTextAtCursor(text) {
var cursorPosition = simplemde.codemirror.getCursor();
var currentLine = cursorPosition.line;
var currentCh = cursorPosition.ch;
var position = { line: currentLine, ch: currentCh };
simplemde.codemirror.replaceSelection(text);
}
// Function to highlight added text
function highlightAddedText() {
var addedText = simplemde.codemirror.getValue();
var diff = Diff.diffWordsWithSpace(previousText, addedText);
// Reset previous highlights
simplemde.codemirror.getAllMarks().forEach(function (mark) {
if (mark.className === "highlight-added") {
mark.clear();
}
});
var addedCount = 0;
diff.forEach(function (part) {
if (part.added) {
// Apply highlighting class to the added part
var from = addedCount;
var to = from + part.value.length;
simplemde.codemirror.markText(
simplemde.codemirror.posFromIndex(from),
simplemde.codemirror.posFromIndex(to),
{ className: "highlight-added" }
);
addedCount += part.value.length;
} else if (!part.removed) {
addedCount += part.value.length;
}
});
// Store the current text as previousText for the next change event
previousText = addedText;
setTimeout(function () {
console.log("Clearing highlights");
simplemde.codemirror.getAllMarks().forEach(function (mark) {
if (mark.className === "highlight-added") {
mark.clear();
}
});