-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
372 lines (314 loc) · 11.9 KB
/
Copy pathscript.js
File metadata and controls
372 lines (314 loc) · 11.9 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
// let originalEditor, userEditor;
// window.onload = () => {
// // Initialize editors in Python mode by default
// if (document.getElementById("originalCode")) {
// originalEditor = CodeMirror.fromTextArea(document.getElementById("originalCode"), {
// lineNumbers: true,
// mode: "python"
// });
// }
// if (document.getElementById("userCode")) {
// userEditor = CodeMirror.fromTextArea(document.getElementById("userCode"), {
// lineNumbers: true,
// mode: "python"
// });
// }
// // Only load history if we are on the history page
// if (document.getElementById("history-container")) {
// loadHistoryFromSession();
// }
// };
// function changeLanguage() {
// const lang = document.getElementById('languageSelector').value;
// if (originalEditor) originalEditor.setOption("mode", lang);
// if (userEditor) userEditor.setOption("mode", lang);
// }
// function escapeHtml(text) {
// return text.replace(/[&<>"']/g, match => {
// const escapeMap = {
// '&': '&',
// '<': '<',
// '>': '>',
// '"': '"',
// "'": '''
// };
// return escapeMap[match];
// });
// }
// async function compareCode() {
// const original = originalEditor.getValue();
// const user = userEditor.getValue();
// const result = document.getElementById('result');
// const originalLines = original.split('\n');
// const userLines = user.split('\n');
// const maxLines = Math.max(originalLines.length, userLines.length);
// let html = `<strong>🔍 Line-by-Line Comparison:</strong><br>`;
// for (let i = 0; i < maxLines; i++) {
// const orig = originalLines[i] || '';
// const usr = userLines[i] || '';
// let lineText = `<div style="margin-bottom: 10px;"><strong>Line ${i + 1}:</strong> `;
// if (orig === usr) {
// lineText += `<div style="background-color:#e7fbe7; padding: 6px; border-radius: 5px;">✔️ ${escapeHtml(usr)}</div>`;
// } else {
// lineText += `<div style="background-color:#ffe6e6; padding: 6px; border-radius: 5px;">
// ❌ <b>Expected:</b> ${escapeHtml(orig)}<br>
// <b>Got:</b> ${escapeHtml(usr)}
// </div>`;
// }
// lineText += `</div>`;
// html += lineText;
// }
// result.innerHTML = html;
// result.style.display = 'block';
// // Save to backend silently
// try {
// const response = await fetch('http://localhost:3000/save', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ original, user })
// });
// const data = await response.json();
// console.log("Save response:", data);
// // Removed alert
// } catch (err) {
// console.error("Failed to save to backend", err);
// // Removed alert
// }
// // Save to sessionStorage so it’s kept until tab is closed
// saveHistoryToSession(original, user);
// }
// function saveHistoryToSession(original, user) {
// let history = JSON.parse(sessionStorage.getItem("history")) || [];
// history.push({
// original,
// user,
// createdAt: new Date().toISOString()
// });
// sessionStorage.setItem("history", JSON.stringify(history));
// }
// function loadHistoryFromSession() {
// let history = JSON.parse(sessionStorage.getItem("history")) || [];
// if (history.length > 0) {
// const result = document.getElementById('result');
// result.innerHTML = '<h3>📜 Comparison History (This Session)</h3>';
// history.forEach(entry => {
// result.innerHTML += `
// <strong>${new Date(entry.createdAt).toLocaleString()}</strong><br>
// <code>Original:</code><br><pre>${escapeHtml(entry.original)}</pre>
// <code>User:</code><br><pre>${escapeHtml(entry.user)}</pre><hr>
// `;
// });
// result.style.display = 'block';
// }
// }
// function viewHistory() {
// loadHistoryFromSession();
// }
// function clearHistory() {
// sessionStorage.removeItem("history");
// const result = document.getElementById('result');
// result.innerHTML = '🗑️ History cleared successfully!';
// result.style.display = 'block';
// result.style.backgroundColor = '#fff3cd';
// result.style.borderLeft = '4px solid orange';
// }
// // Toggle dark mode (persistent using localStorage)
// document.getElementById("darkModeToggle").addEventListener("click", function () {
// document.body.classList.toggle("dark-mode");
// // Save state to localStorage
// if (document.body.classList.contains("dark-mode")) {
// localStorage.setItem("theme", "dark");
// } else {
// localStorage.setItem("theme", "light");
// }
// // Toggle CodeMirror theme
// const editors = document.querySelectorAll(".CodeMirror");
// editors.forEach(editor => {
// const cm = editor.CodeMirror;
// if (cm) {
// cm.setOption("theme", document.body.classList.contains("dark-mode") ? "darcula" : "default");
// }
// });
// });
// // On page load, restore theme
// window.addEventListener("DOMContentLoaded", () => {
// const theme = localStorage.getItem("theme");
// if (theme === "dark") {
// document.body.classList.add("dark-mode");
// const editors = document.querySelectorAll(".CodeMirror");
// editors.forEach(editor => {
// const cm = editor.CodeMirror;
// if (cm) cm.setOption("theme", "darcula");
// });
// }
// });
//Creates two variables to store the CodeMirror editors for the original code and user code.
//We need to keep references to these editors so we can get their content and change settings later.
let originalEditor, userEditor;
//Preprocessing code before comparison
//Cleans the code for comparison by removing comments, extra spaces, and blank lines.
//So that small formatting differences don’t affect the comparison.
function preprocessCodeForCompare(code) {
return code
// Remove multi-line comments
.replace(/\/\*[\s\S]*?\*\//g, "")
// Remove single-line comments
.replace(/#.*$/gm, "") // Python-style comments
.replace(/\/\/.*$/gm, "") // JS/Java-style comments
// Trim spaces at start/end of lines
.split("\n")
.map(line => line.trim())
// Remove blank lines
.filter(line => line.length > 0)
// Normalize spaces within the line
.map(line => line.replace(/\s+/g, " "))
.join("\n");
}
//Initialize editors and history on page load
//Finds the text areas in the page for original and user code.
// Converts them into CodeMirror editors with line numbers and Python syntax highlighting.
// Loads previous comparison history if available.
//It provides syntax highlighting, line numbers, and easier code editing compared to a plain <textarea>.
window.onload = () => {
if (document.getElementById("originalCode")) {
originalEditor = CodeMirror.fromTextArea(document.getElementById("originalCode"), {
lineNumbers: true,
mode: "python"
});
}
if (document.getElementById("userCode")) {
userEditor = CodeMirror.fromTextArea(document.getElementById("userCode"), {
lineNumbers: true,
mode: "python"
});
}
if (document.getElementById("history-container")) {
loadHistoryFromSession();
}
};
function changeLanguage() {
const lang = document.getElementById('languageSelector').value;
if (originalEditor) originalEditor.setOption("mode", lang);
if (userEditor) userEditor.setOption("mode", lang);
}
//Converts <, >, &, ", ' into safe HTML so they don’t break the page.
// Why: Without this, code like <div> would be rendered as HTML instead of showing as code.
function escapeHtml(text) {
return text.replace(/[&<>"']/g, match => {
const escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return escapeMap[match];
});
}
//Compare the code
//Gets code from both editors.
// Cleans the code using preprocessCodeForCompare.
// Compares line by line.
// Shows green for correct lines and red for differences, with "Expected" vs "Got".
// Saves the comparison to session storage.
async function compareCode() {
const originalRaw = originalEditor.getValue();
const userRaw = userEditor.getValue();
// Preprocess for comparison (ignore comments/whitespace/blank lines)
const original = preprocessCodeForCompare(originalRaw);
const user = preprocessCodeForCompare(userRaw);
const result = document.getElementById('result');
const originalLines = original.split('\n');
const userLines = user.split('\n');
const maxLines = Math.max(originalLines.length, userLines.length);
let html = `<strong>🔍 Line-by-Line Comparison :</strong><br>`;
for (let i = 0; i < maxLines; i++) {
const orig = originalLines[i] || '';
const usr = userLines[i] || '';
let lineText = `<div style="margin-bottom: 10px;"><strong>Line ${i + 1}:</strong> `;
if (orig === usr) {
lineText += `<div style="background-color:#e7fbe7; padding: 6px; border-radius: 5px;">✔️ ${escapeHtml(usr)}</div>`;
} else {
lineText += `<div style="background-color:#ffe6e6; padding: 6px; border-radius: 5px;">
❌ <b>Expected:</b> ${escapeHtml(orig)}<br>
<b>Got:</b> ${escapeHtml(usr)}
</div>`;
}
lineText += `</div>`;
html += lineText;
}
result.innerHTML = html;
result.style.display = 'block';
// Save to sessionStorage (keep original raw code for display in history)
saveHistoryToSession(originalRaw, userRaw);
}
function saveHistoryToSession(original, user) {
let history = JSON.parse(sessionStorage.getItem("history")) || [];
history.push({
original,
user,
createdAt: new Date().toISOString()
});
sessionStorage.setItem("history", JSON.stringify(history));
}
//Session storage functions
// Saves each comparison in the browser session.
// Loads all previous comparisons.
// Clears history when requested.
// Why sessionStorage: Keeps data for the current session without using a backend database. Safer for temporary storage.
function loadHistoryFromSession() {
let history = JSON.parse(sessionStorage.getItem("history")) || [];
if (history.length > 0) {
const result = document.getElementById('result');
result.innerHTML = '<h3>📜 Comparison History (This Session)</h3>';
history.forEach(entry => {
result.innerHTML += `
<strong>${new Date(entry.createdAt).toLocaleString()}</strong><br>
<code>Original:</code><br><pre>${escapeHtml(entry.original)}</pre>
<code>User:</code><br><pre>${escapeHtml(entry.user)}</pre><hr>
`;
});
result.style.display = 'block';
}
}
function viewHistory() {
loadHistoryFromSession();
}
function clearHistory() {
sessionStorage.removeItem("history");
const result = document.getElementById('result');
result.innerHTML = '🗑️ History cleared successfully!';
result.style.display = 'block';
result.style.backgroundColor = '#fff3cd';
result.style.borderLeft = '4px solid orange';
}
// Toggles dark mode for the page and CodeMirror editors.
// Saves the preference in localStorage to remember it.
document.getElementById("darkModeToggle").addEventListener("click", function () {
document.body.classList.toggle("dark-mode");
if (document.body.classList.contains("dark-mode")) {
localStorage.setItem("theme", "dark");
} else {
localStorage.setItem("theme", "light");
}
const editors = document.querySelectorAll(".CodeMirror");
editors.forEach(editor => {
const cm = editor.CodeMirror;
if (cm) {
cm.setOption("theme", document.body.classList.contains("dark-mode") ? "darcula" : "default");
}
});
});
// On page load, applies the saved dark mode preference.
// So the user doesn’t have to switch to dark mode every time.
window.addEventListener("DOMContentLoaded", () => {
const theme = localStorage.getItem("theme");
if (theme === "dark") {
document.body.classList.add("dark-mode");
const editors = document.querySelectorAll(".CodeMirror");
editors.forEach(editor => {
const cm = editor.CodeMirror;
if (cm) cm.setOption("theme", "darcula");
});
}
});