This repository was archived by the owner on Jul 29, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2052 lines (1728 loc) · 59.5 KB
/
script.js
File metadata and controls
2052 lines (1728 loc) · 59.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
const editor = ace.edit("editor");
editor.setTheme("ace/theme/chrome");
const languageSelect = document.getElementById("language-select");
languageSelect.addEventListener("change", function () {
const selectedLanguage = languageSelect.value;
editor.session.setMode("ace/mode/" + selectedLanguage);
});
function openFile(event) {
const input = event.target;
const file = input.files[0];
const reader = new FileReader();
reader.onload = function () {
const newTab = document.createElement("button");
newTab.className = "tab";
newTab.textContent = file.name;
newTab.addEventListener("click", switchToTab);
const newEditor = ace.edit(document.createElement("div"));
newEditor.setOptions({
maxLines: 38,
minLines: 38,
});
newEditor.setValue(reader.result);
const editorId = `editor-${Date.now()}`;
newEditor.container.id = editorId;
const extension = file.name.split(".").pop();
newEditor.session.setMode(`ace/mode/${extension}`);
newEditor.setKeyboardHandler(`ace/keyboard/${keyboard_mode}`);
newTab.setAttribute("data-editor-id", editorId);
newEditor.container.style.width = "99%";
newEditor.container.style.height = "600px";
newEditor.container.style.border = "1px solid #ccc";
newEditor.container.style.marginTop = "10px";
newEditor.container.style.border = "2px solid #cccccc";
newEditor.container.style.borderRadius = "5px";
newEditor.container.style.fontSize = fontSize;
newEditor.container.style.fontFamily = fontFamily;
const language = document.getElementById("language-select").value;
newEditor.session.setMode(`ace/mode/${extension}`);
newTab.setAttribute("data-language", extension);
newEditor.setOptions({
enableLiveAutocompletion: true,
enableBasicAutocompletion: true,
enableSnippets: true,
});
const closeButton = document.createElement("button");
document.getElementById("tabBar").appendChild(newTab);
document.body.appendChild(newEditor.container);
switchToTab({ target: newTab });
toggleTheme();
toggleTheme();
};
reader.readAsText(file);
}
function saveFile() {
const activeTab = document.querySelector(".tab.active");
const editorId = activeTab.getAttribute("data-editor-id");
const editor = document.getElementById(editorId);
const code = editor.env.editor.getValue();
const blob = new Blob([code], { type: "text/plain" });
const fileName = activeTab.textContent.trim();
if (!fileName) {
return;
}
const reader = new FileReader();
reader.onload = function (event) {
const a = document.createElement("a");
a.href = event.target.result;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
reader.readAsDataURL(blob);
}
function addTab() {
const currentTheme = editor.getTheme();
const newTab = document.createElement("button");
newTab.className = "tab";
newTab.textContent = `Tab ${
document.getElementsByClassName("tab").length + 1
}`;
const editorId = `editor${Date.now()}`;
newTab.setAttribute("data-editor-id", editorId);
newTab.addEventListener("click", switchToTab);
document.getElementById("tabBar").appendChild(newTab);
const newEditor = ace.edit(document.createElement("div"));
newEditor.setOptions({
maxLines: 38,
minLines: 38,
});
newEditor.container.style.width = "99%";
newEditor.container.style.height = "600px";
newEditor.container.style.border = "1px solid #ccc";
newEditor.container.style.marginTop = "10px";
newEditor.container.style.border = "2px solid #cccccc";
newEditor.container.style.borderRadius = "5px";
newEditor.container.style.fontSize = fontSize;
newEditor.container.style.fontFamily = fontFamily;
newEditor.container.id = editorId;
const language = document.getElementById("language-select").value;
newEditor.session.setMode(`ace/mode/${language}`);
newEditor.setKeyboardHandler(`ace/keyboard/${keyboard_mode}`);
newTab.setAttribute("data-language", language);
newEditor.setOptions({
enableLiveAutocompletion: true,
enableBasicAutocompletion: true,
enableSnippets: true,
});
document.body.appendChild(newEditor.container);
switchToTab({ target: newTab });
toggleTheme();
toggleTheme();
}
function switchToTab(event) {
const tab = event.target;
const editorId = tab.getAttribute("data-editor-id");
const editor = document.getElementById(editorId);
if (splitViewActive) {
const leftPane = document.getElementById("left-pane");
const rightPane = document.getElementById("right-pane");
const activePane = leftPane.contains(editor) ? leftPane : rightPane;
const inactivePane = activePane === leftPane ? rightPane : leftPane;
// Move the clicked editor to the active pane
activePane.innerHTML = "";
activePane.appendChild(editor);
editor.style.display = "block";
ace.edit(editorId).resize();
// If there's no editor in the inactive pane, move the next available one there
if (inactivePane.children.length === 0) {
const nextTab =
tab.nextElementSibling || document.querySelector(".tab:first-child");
if (nextTab && nextTab !== tab) {
const nextEditorId = nextTab.getAttribute("data-editor-id");
const nextEditor = document.getElementById(nextEditorId);
inactivePane.appendChild(nextEditor);
nextEditor.style.display = "block";
ace.edit(nextEditorId).resize();
}
}
} else {
document
.querySelectorAll(".ace_editor")
.forEach((ed) => (ed.style.display = "none"));
editor.style.display = "block";
ace.edit(editorId).resize();
}
document
.querySelectorAll(".tab.active")
.forEach((t) => t.classList.remove("active"));
tab.classList.add("active");
}
function closeTab(event) {
const tab = event.target;
const tabBar = document.getElementById("tabBar");
tabBar.removeChild(tab);
const editorId = tab.getAttribute("data-editor-id");
const editor = ace.edit(editorId);
editor.container.remove();
editor.destroy();
if (tab.classList.contains("active")) {
const nextTab = tab.nextElementSibling || tabBar.firstChild;
if (nextTab) {
switchToTab({ target: nextTab });
}
}
}
document
.getElementById("closeActiveTab")
.addEventListener("click", function () {
const activeTab = document.querySelector(".tab.active");
if (activeTab) {
closeTab({ target: activeTab });
}
});
function toggleTheme(theme) {
const currentTheme = editor.getTheme();
const newTheme =
currentTheme === `ace/theme/${light_theme}`
? `ace/theme/${dark_theme}`
: `ace/theme/${light_theme}`;
const editorInstances = document.querySelectorAll(".ace_editor");
for (const editorInstance of editorInstances) {
const editor = ace.edit(editorInstance);
editor.setTheme(newTheme);
}
const body = document.body;
const isDarkTheme = newTheme === `ace/theme/${dark_theme}`;
body.classList.toggle("dark-theme", isDarkTheme);
body.classList.toggle("light-theme", !isDarkTheme);
body.style.backgroundColor = isDarkTheme ? "#272822" : "#bdbdbd";
body.style.color = isDarkTheme ? "#dddddd" : "#000000";
const tabElements = document.querySelectorAll(".tab");
for (const tabElement of tabElements) {
tabElement.classList.toggle("dark-text", isDarkTheme);
tabElement.classList.toggle("light-text", !isDarkTheme);
}
const buttonElements = document.querySelectorAll("button");
for (const buttonElement of buttonElements) {
buttonElement.style.backgroundColor = isDarkTheme ? "#3b3b3b" : "#e0e0e0";
buttonElement.style.color = isDarkTheme ? "#dddddd" : "#000000";
}
const divElements = document.querySelectorAll(".navbar");
for (const divElement of divElements) {
divElement.style.backgroundColor = isDarkTheme ? "#3b3b3b" : "#e0e0e0";
divElement.style.color = isDarkTheme ? "#dddddd" : "#000000";
}
const divElements2 = document.querySelectorAll(".tabBar");
for (const divElement2 of divElements2) {
divElement2.style.backgroundColor = isDarkTheme ? "#3b3b3b" : "#e0e0e0";
divElement2.style.color = isDarkTheme ? "#dddddd" : "#000000";
}
const inputElements = document.querySelectorAll("input");
for (const inputElement of inputElements) {
inputElement.style.backgroundColor = isDarkTheme ? "#3b3b3b" : "#e0e0e0";
inputElement.style.color = isDarkTheme ? "#dddddd" : "#000000";
}
const selectElements = document.querySelectorAll("select");
for (const selectElement of selectElements) {
selectElement.style.backgroundColor = isDarkTheme ? "#3b3b3b" : "#e0e0e0";
selectElement.style.color = isDarkTheme ? "#dddddd" : "#000000";
}
const h1Elements = document.querySelectorAll("h1");
for (const h1Element of h1Elements) {
h1Element.style.color = isDarkTheme ? "#dddddd" : "#000000";
}
const aElements = document.querySelectorAll("a");
for (const aElement of aElements) {
aElement.style.color = isDarkTheme ? "#dddddd" : "#000000";
}
const editorElements = document.querySelectorAll(".ace_content");
for (const editorElement of editorElements) {
editorElement.classList.toggle("dark-text", isDarkTheme);
editorElement.classList.toggle("light-text", !isDarkTheme);
}
const modalElements = document.querySelectorAll(".modal-content");
for (const modalElement of modalElements) {
modalElement.style.backgroundColor = isDarkTheme ? "#3b3b3b" : "#e0e0e0";
}
const ulElements = document.querySelectorAll("ul");
for (const ulElement of ulElements) {
ulElement.style.backgroundColor = isDarkTheme ? "#3b3b3b" : "#e0e0e0";
ulElement.style.color = isDarkTheme ? "#dddddd" : "#000000";
}
const areaElements = document.querySelectorAll("textarea");
for (const areaElement of areaElements) {
areaElement.style.backgroundColor = isDarkTheme ? "#3b3b3b" : "#e0e0e0";
areaElement.style.color = isDarkTheme ? "#dddddd" : "#000000";
}
}
function setLanguageForActiveTab() {
const languageSelect = document.getElementById("language-select");
const selectedLanguage = languageSelect.value;
const activeTab = document.querySelector(".tab.active");
const editorId = activeTab.getAttribute("data-editor-id");
const activeEditor = ace.edit(editorId);
activeEditor.session.setMode("ace/mode/" + selectedLanguage);
}
const languageDropdown = document.getElementById("language-select");
languageSelect.addEventListener("change", setLanguageForActiveTab);
function openSettings() {
document.getElementById("settingsModal").style.display = "block";
}
function closeSettings() {
document.getElementById("settingsModal").style.display = "none";
}
function fileOps() {
document.getElementById("fileModal").style.display = "block";
}
function closefileOps() {
document.getElementById("fileModal").style.display = "none";
}
function runCode() {
document.getElementById("runModal").style.display = "block";
}
function closeRunCode() {
document.getElementById("runModal").style.display = "none";
}
function gitOps() {
document.getElementById("gitModal").style.display = "block";
}
function closeGitOps() {
document.getElementById("gitModal").style.display = "none";
}
function htmlOutput() {
var x = document.getElementById("output-container");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function executeHtmlCode() {
const activeTab = document.querySelector(".tab.active");
if (!activeTab) return;
const editorId = activeTab.getAttribute("data-editor-id");
const activeEditor = ace.edit(editorId);
if (!activeEditor) return;
const htmlCode = activeEditor.getValue();
// Separate script tags from the main process
const { htmlContent, scriptContent } = separateScriptTags(htmlCode);
const sanitizedHtml = DOMPurify.sanitize(htmlContent);
const outputContainer = document.getElementById("output-container");
outputContainer.innerHTML = "";
const blob = new Blob(
[
`
<!DOCTYPE html>
<html>
<head></head>
<body>
${sanitizedHtml}
<script>
${scriptContent}
<\/script>
</body>
</html>
`,
],
{ type: "text/html" }
);
const blobUrl = URL.createObjectURL(blob);
// Create an iframe for sandboxed execution
const iframe = document.createElement("iframe");
iframe.style.width = "100%";
iframe.style.height = "100%";
iframe.sandbox = "allow-scripts";
iframe.src = blobUrl;
outputContainer.appendChild(iframe);
}
// Separate <script> tags from the HTML
function separateScriptTags(htmlCode) {
const scriptRegex = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
let htmlContent = htmlCode;
let scriptContent = "";
htmlCode = htmlCode.replace(scriptRegex, (match, script) => {
scriptContent += script;
return "";
});
return { htmlContent, scriptContent };
}
// Run the Markdown conversion
function runMarkdown() {
const activeTab = document.querySelector(".tab.active");
if (!activeTab) return;
const editorId = activeTab.getAttribute("data-editor-id");
const activeEditor = ace.edit(editorId);
const editorValue = activeEditor.getValue();
// Sanitize Markdown content before conversion
const sanitizedMarkdown = DOMPurify.sanitize(editorValue);
const convertedHtml = convertToHtml(sanitizedMarkdown);
const resultDiv = document.createElement("div");
resultDiv.innerHTML = convertedHtml;
const outputContainer = document.getElementById("output-container");
outputContainer.innerHTML = "";
outputContainer.appendChild(resultDiv);
applySyntaxHighlighting();
}
// Convert Markdown to HTML
function convertToHtml(markdown) {
const noScripts = markdown.replace(
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
""
);
const noJavaScriptLinks = noScripts.replace(
/\bhttps?:\/\/\S+\bjavascript:/gi,
""
);
const noDataURIImages = noJavaScriptLinks.replace(
/\bdata:image\/\S+;base64,\S+/gi,
""
);
// Convert markdown to HTML
return noDataURIImages
.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>") // Bold
.replace(/\*(.*?)\*/g, "<em>$1</em>") // Italic
.replace(/^###(.*?)(\n|$)/gm, "<h3>$1</h3>") // H3
.replace(/^##(.*?)(\n|$)/gm, "<h2>$1</h2>") // H2
.replace(/^#(.*?)(\n|$)/gm, "<h1>$1</h1>") // H1
.replace(/\n[-*] (.*?)\n/g, "<ul><li>$1</li></ul>") // Bullet list with `-` and `*`
.replace(/```(\s*[\w-]*?)\n([\s\S]*?)```/g, (match, lang, code) => { // Code block
lang = lang.trim() || 'text';
return `<div class="code-block" data-lang="${lang}">${code}</div>`;
})
.replace(/`([^`]+)`/g, "<code>$1</code>") // Inline code
.replace(/\$([^\$]+)\$/g, '<span class="math-inline">$$$1$$</span>'); // Inline math
}
// Apply syntax highlighting for code blocks using Ace.js
function applySyntaxHighlighting() {
const actual_editor = ace.edit("editor");
const currentTheme = actual_editor.getTheme();
const codeBlocks = document.querySelectorAll('.code-block');
codeBlocks.forEach(block => {
const lang = block.getAttribute('data-lang') || 'text';
const editorDiv = document.createElement('div');
editorDiv.style.width = "100%";
editorDiv.style.height = "100px";
block.replaceWith(editorDiv);
const editor = ace.edit(editorDiv);
editor.setTheme(currentTheme);
editor.session.setMode(`ace/mode/${lang}`);
editor.setValue(block.textContent.trim(), -1);
editor.setReadOnly(true);
});
}
function loadExtensions() {
var username = "Okerew";
var repoName = "okraleditorlibs";
var fileName = prompt("Enter extension name:");
// Sanitize inputs to prevent injection attacks
if (!isValidFileName(fileName)) {
console.error(
"Invalid input. Please enter valid GitHub username, repository name, and file name."
);
return;
}
var script = document.createElement("script");
script.src =
"https://cdn.jsdelivr.net/gh/" +
username +
"/" +
repoName +
"/" +
fileName +
".js";
script.onload = function () {
console.log("Extension " + fileName + " loaded successfully!");
};
document.head.appendChild(script);
}
function isValidInput(input) {
var regex = /^[a-zA-Z0-9\-]+$/;
return regex.test(input);
}
function isValidFileName(fileName) {
var regex = /^[a-zA-Z0-9\-_\.]+$/;
return regex.test(fileName);
}
async function loadRepoFiles() {
const username = prompt("Enter the GitHub username:");
if (!username || !isValidFileName(username)) {
console.error("GitHub username not provided.");
return;
}
const repo = prompt("Enter the repository name:");
if (!repo || !isValidFileName(repo)) {
console.error("Repository name not provided.");
return;
}
const container = document.createElement("div");
container.id = "fileTreeContainer";
const repoUrl = `https://api.github.com/repos/${username}/${repo}/contents`;
try {
const response = await fetch(repoUrl);
if (!response.ok) {
throw new Error("Failed to fetch repository contents");
}
const data = await response.json();
await createGitFileTree("", container, username, repo);
container.style.display = "block";
} catch (error) {
console.error("Error loading repository files:", error);
alert(
"Error loading repository files. Please check the console for details."
);
}
document.body.appendChild(container);
}
async function createGitFileTree(dirPath, parentNode, username, repo) {
const repoUrl = `https://api.github.com/repos/${username}/${repo}/contents${dirPath}`;
try {
const response = await fetch(repoUrl);
if (!response.ok) {
throw new Error("Failed to fetch directory contents");
}
const data = await response.json();
const ul = document.createElement("ul");
for (const item of data) {
const li = document.createElement("li");
const itemName = item.name;
if (item.type === "file") {
const button = document.createElement("button");
button.textContent = itemName;
button.addEventListener("click", async () => {
const fileUrl = item.download_url;
const fileContent = await fetch(fileUrl).then((response) =>
response.text()
);
const editorId = `editor-${Date.now()}`;
openGitFolderFile(fileContent, editorId);
});
li.appendChild(button);
} else if (item.type === "dir") {
const button = document.createElement("button");
button.textContent = itemName;
button.classList.add("folder");
button.addEventListener("click", async () => {
// Clear the parent node
ul.innerHTML = "";
// Recursively create file tree for the directory
await createGitFileTree(`${dirPath}/${itemName}`, li, username, repo);
});
li.appendChild(button);
}
ul.appendChild(li);
}
parentNode.appendChild(ul);
} catch (error) {
console.error("Error creating file tree:", error);
alert("Error creating file tree. Please check the console for details.");
}
}
function openGitFolderFile(fileContent, editorId) {
const newTab = document.createElement("button");
newTab.className = "tab";
newTab.textContent = "New File";
newTab.addEventListener("click", switchToTab);
const newEditor = ace.edit(document.createElement("div"));
newEditor.setOptions({
maxLines: 38,
minLines: 38,
});
newEditor.container.style.width = "99%";
newEditor.container.style.height = "600px";
newEditor.container.style.border = "1px solid #ccc";
newEditor.container.style.marginTop = "10px";
newEditor.container.style.border = "2px solid #cccccc";
newEditor.container.style.borderRadius = "5px";
newEditor.container.style.fontSize = fontSize;
newEditor.container.style.fontFamily = fontFamily;
newEditor.setValue(fileContent);
const language = document.getElementById("language-select").value;
newEditor.session.setMode(`ace/mode/${language}`);
newTab.setAttribute("data-language", language);
newEditor.setKeyboardHandler(`ace/keyboard/${keyboard_mode}`);
newEditor.container.id = editorId;
newTab.setAttribute("data-editor-id", editorId);
document.getElementById("tabBar").appendChild(newTab);
document.body.appendChild(newEditor.container);
switchToTab({ target: newTab });
toggleTheme();
toggleTheme();
}
function pushToGithub() {
const username = prompt("Enter your GitHub username:");
if (!username || !isValidFileName(username)) {
console.error("GitHub username not provided.");
return;
}
const repo = prompt("Enter the name of your repository:");
if (!repo || !isValidFileName(repo)) {
console.error("Invalid repository name provided.");
return;
}
if (!token || !isValidFileName(token)) {
console.error("GitHub token not provided.");
return;
}
const filename = prompt("Enter the filename to save as:");
if (!filename || !isValidFileName(filename)) {
console.error("Filename not provided.");
return;
}
const commitMessage = prompt("Enter your commit message:");
if (!commitMessage || !isValidFileName(commitMessage)) {
console.error("Commit message not provided.");
return;
}
const branchName = prompt("Enter the name of the branch to commit to:");
if (!branchName || !isValidFileName(branchName)) {
console.error("Branch name not provided.");
return;
}
const activeTab = document.querySelector(".tab.active");
if (!activeTab) {
console.error("No active tab found.");
return;
}
const editorId = activeTab.getAttribute("data-editor-id");
const activeEditor = ace.edit(editorId);
const code = activeEditor.getValue();
const apiUrl = `https://api.github.com/repos/${username}/${repo}/contents/${encodeURIComponent(
filename
)}`;
const data = {
message: commitMessage,
content: btoa(unescape(encodeURIComponent(code))),
branch: branchName,
};
fetch(apiUrl, {
method: "PUT",
headers: {
Authorization: `token ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => {
if (!response.ok) {
throw new Error("Failed to push changes to the branch");
}
console.log("Changes pushed to branch successfully");
alert("Changes pushed to branch successfully!");
})
.catch((error) => {
console.error("Error pushing changes to branch:", error);
alert(
"Error pushing changes to branch. Please check the console for details."
);
});
}
function mergeBranches() {
const username = prompt("Enter your GitHub username:");
if (!username || !isValidFileName(username)) {
console.error("GitHub username not provided.");
return;
}
const repo = prompt("Enter the name of your repository:");
if (!repo || !isValidFileName(repo)) {
console.error("Repository name not provided.");
return;
}
const baseBranch = prompt("Enter the name of the base branch:");
if (!baseBranch || !isValidFileName(baseBranch)) {
console.error("Base branch name not provided.");
return;
}
const headBranch = prompt("Enter the name of the branch to merge:");
if (!headBranch || !isValidFileName(headBranch)) {
console.error("Head branch name not provided.");
return;
}
if (!token || !isValidFileName(token)) {
console.error("GitHub token not provided.");
return;
}
const apiUrl = `https://api.github.com/repos/${username}/${repo}/merges`;
const data = {
base: baseBranch,
head: headBranch,
commit_message: "Merge branch",
};
fetch(apiUrl, {
method: "POST",
headers: {
Authorization: `token ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => {
if (!response.ok) {
throw new Error("Failed to merge branches");
}
console.log("Branches merged successfully");
alert("Branches merged successfully!");
})
.catch((error) => {
console.error("Error merging branches:", error);
alert("Error merging branches. Please check the console for details.");
});
}
function executeCodeInWorker() {
const activeTab = document.querySelector(".tab.active");
if (!activeTab) return;
const editorId = activeTab.getAttribute("data-editor-id");
const activeEditor = ace.edit(editorId);
if (!activeEditor) return;
const jsCode = activeEditor.getValue();
const worker = new Worker("worker.js");
worker.postMessage({ jsCode, editorId });
}
function encryptConfig(config, key) {
const encrypted = CryptoJS.AES.encrypt(config, key);
return encrypted.toString();
}
function decryptConfig(encryptedConfig, key) {
const decrypted = CryptoJS.AES.decrypt(encryptedConfig, key);
return decrypted.toString(CryptoJS.enc.Utf8);
}
async function encryptOnServer(config) {
const response = await fetch(
"https://candle-cheerful-warlock.glitch.me/encrypt",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ config }),
}
);
const data = await response.json();
return data.encryptedConfig;
}
async function decryptOnServer(encryptedConfig) {
const response = await fetch(
"https://candle-cheerful-warlock.glitch.me/decrypt",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ encryptedConfig }),
}
);
const data = await response.json();
return data.config;
}
async function saveToCookie() {
const activeTab = document.querySelector(".tab.active");
if (!activeTab) return;
const editorId = activeTab.getAttribute("data-editor-id");
const activeEditor = ace.edit(editorId);
if (!activeEditor) return;
const unsafe_config = activeEditor.getValue();
const config = DOMPurify.sanitize(unsafe_config);
// Generate a random key
const key = generateRandomKey();
const encryptedConfig = encryptConfig(config, key);
const doublyEncryptedConfig = await encryptOnServer(encryptedConfig);
const now = new Date();
// Calculate expiration date (30 days from now)
const expirationDate = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000);
document.cookie = `encryptedConfig=${encodeURIComponent(
doublyEncryptedConfig
)}; expires=${expirationDate.toUTCString()}; path=/; SameSite=None; Secure`;
localStorage.setItem("encryptionKey", key);
}
async function loadFromCookie() {
const cookies = document.cookie.split(";");
let doublyEncryptedConfig = null;
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.startsWith("encryptedConfig=")) {
doublyEncryptedConfig = decodeURIComponent(
cookie.substring("encryptedConfig=".length)
);
break;
}
}
if (!doublyEncryptedConfig) return;
const serverDecryptedConfig = await decryptOnServer(doublyEncryptedConfig);
const key = localStorage.getItem("encryptionKey");
if (!key) {
console.error("Encryption key not found!");
return;
}
const config = decryptConfig(serverDecryptedConfig, key);
const scriptTag = document.createElement("script");
scriptTag.textContent = config;
document.body.appendChild(scriptTag);
}
loadFromCookie();
function generateRandomKey() {
// Generate a random string to be used as the key
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let key = "";
for (let i = 0; i < 32; i++) {
key += characters.charAt(Math.floor(Math.random() * characters.length));
}
return key;
}
function hideFileTree() {
const fileTreeContainer = document.getElementById("fileTreeContainer");
if (fileTreeContainer.style.display === "block") {
fileTreeContainer.style.display = "none";
} else {
fileTreeContainer.style.display = "block";
}
}
if (typeof keyboard_mode == "undefined") {
keyboard_mode = null;
}
if (typeof fontSize == "undefined") {
fontSize = "15px";
}
if (typeof fontFamily == "undefined") {
fontFamily = "monospace";
}
if (typeof light_theme == "undefined") {
light_theme = "chrome";
}
if (typeof dark_theme == "undefined") {
dark_theme = "monokai";
}
async function pushAllToGithub() {
const username = prompt("Enter your GitHub username:");
if (!username || !isValidFileName(username)) {
console.error("GitHub username not provided or invalid.");
return;
}
const repo = prompt("Enter the name of your repository:");
if (!repo || !isValidFileName(repo)) {
console.error("Invalid repository name provided.");
return;
}
if (!token) {
console.error("GitHub token not provided.");
return;
}
const commitMessage = prompt("Enter your commit message:");
if (!commitMessage) {
console.error("Commit message not provided.");
return;
}
const branchName = prompt("Enter the name of the branch to commit to:");
if (!branchName || !isValidFileName(branchName)) {
console.error("Branch name not provided or invalid.");
return;
}
const editorInstances = document.querySelectorAll(".ace_editor");
for (let i = 1; i < editorInstances.length; i++) {
const editorInstance = editorInstances[i];
const tabName = prompt("Enter file name: ");
if (!tabName || !isValideFileName(tabName)) {
console.error("File name not provided");
return;
}
const editorId = editorInstance.id;
const editor = ace.edit(editorId);
const code = editor.getValue();
const apiUrl = `https://api.github.com/repos/${username}/${repo}/contents/${encodeURIComponent(
tabName