-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode_update.js
354 lines (287 loc) · 13.2 KB
/
code_update.js
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
// -------------------------------------------------------------------------
// The main part of script for all the functionality of the extension
// Description: This script is used to update the table with
// totals row for each subject.
// -------------------------------------------------------------------------
function getColumnSums(table) {
// iterate all rows and sum the values in each column separately
// Some might be strings, so we need to check for that and skip them
// Then, if number cols, return sum to 2 decimal places
// else, return empty string
const rows = Array.from(table.querySelectorAll('tr'));
if (rows.length < 2) return; // Skip tables with no data rows
// Initialize totals array based on the number of columns
const totals = Array.from(rows[0].children).map(() => 0);
// Iterate through data rows to calculate totals
rows.slice(1).forEach((row) => {
// Iterate through cells in the row and keep updating totals:
row.querySelectorAll('td').forEach((cell, index) => {
const value = parseFloat(cell.textContent.trim());
// Skip the SrNo column
if (index === 0) {
totals[index] = '-';
}
// Title column
else if (index === 1) {
totals[index] = 'Total';
}
else if (!isNaN(value)) {
totals[index] += value;
}
});
});
for (let i = 0; i < totals.length; i++) {
if (totals[i] === 0) {
totals[i] = '-';
}
if (typeof totals[i] === 'number') {
totals[i] = totals[i].toFixed(2);
}
}
return totals;
}
function removeTotalsRows(logDetails = true) {
// Select all rows with ID 'bbs_custom'
const existingTotalsRows = document.querySelectorAll('tr#bbs_custom');
if (logDetails) console.log('[BBS Extension] Removing totals rows');
if (existingTotalsRows.length > 0) {
if (logDetails) console.log(` |-> Found ${existingTotalsRows.length} totals row(s) to remove`);
// Iterate over the NodeList and remove each row
existingTotalsRows.forEach(row => row.remove());
if (logDetails) console.log(` |-> Removed all totals rows with ID #bbs_custom`);
} else {
if (logDetails) console.log(` |-> No totals rows found to remove`);
}
}
function processTables(updateOnPage = true, highlightRow = false, logDetails = true) {
// Pick the parent table:
const parent_table = document.querySelector('table.customTable');
if (logDetails) console.log('[BBS Extension] Adding totals rows:');
if (logDetails) console.log(' |-> Found parent table');
try {
// Get only the direct child rows of the parent table
const rows = Array.from(parent_table.tBodies[0]?.children || []);
// Skip tables with no data rows
if (rows.length < 2) {
console.log(' |-> Table has no data rows:', parent_table);
return;
}
// Find the header row of the parent table (which is 0th row actually):
const headerRow = rows.find(row => row.classList.contains('tableHeader'));
if (!headerRow) {
console.log(' |-> Table has no header row:', parent_table);
return;
}
// Find the 'Course Title' column index
const courseTitleIndex = Array.from(headerRow.children).findIndex(cell =>
cell.textContent.trim() === 'Course Title'
);
if (logDetails) console.log(' |-> Found Course Title index:', courseTitleIndex);
// Iterate through data rows to get subjects and marks in alternate rows:
currentRow = 1;
subjectCount = 0;
// Check if the totals row already exists, and remove it if it does
const existingTotalsRows = document.querySelectorAll('tr#bbs_custom');
if (existingTotalsRows.length > 0) {
if (logDetails) console.log(` |-> Totals row already exists, removing it...`);
if (logDetails) console.log(` |-> Found ${existingTotalsRows.length} totals row(s) to remove`);
// Iterate over the NodeList and remove each row
existingTotalsRows.forEach(row => row.remove());
if (logDetails) console.log(` |-> Removed all totals rows with ID #bbs_custom`);
}
while (currentRow < rows.length) {
let row = rows[currentRow];
let cells = row.querySelectorAll('td');
const courseTitle = cells[courseTitleIndex].textContent.trim();
subjectCount++;
if (logDetails) console.log(` |-> [${subjectCount}] Found Course:`);
// if (logDetails) console.log(` | |-> Course Title: '${courseTitle}'`);
if (logDetails) {
const highlightColor = '\x1b[33m';
const resetColor = '\x1b[0m';
console.log(` | |-> Course Title: ${highlightColor}'${courseTitle}'${resetColor}`);
}
row = rows[++currentRow];
// Now this row has only one td which hold the table in it, get that table pass to fn
const table = row.querySelector('table');
if (!table) {
console.log(' | |-> No table found in row:', row);
currentRow++;
continue;
}
// Get the totals (array) for the table
const totals = getColumnSums(table);
if (logDetails) console.log(` | |-> Calculated totals:`, totals);
// Show the totals on page in new row with id #bbs_custom:
if (updateOnPage) {
// Create a new row for totals
const totalsRow = document.createElement('tr');
// assign the class "tableContent-level1" to the row
totalsRow.className = 'tableContent-level1';
// Assign the unique ID "bbs_custom" to the row
totalsRow.id = 'bbs_custom';
// // align center for all cells:
// totalsRow.style.textAlign = 'center';
totals.forEach((total, index) => {
const cell = document.createElement('td');
// Set cell content based on the column type
if (typeof total === 'string') {
// For "Total" label in the second column
cell.textContent = total;
} else if (total !== 0) {
// Format numbers to 2 decimal places
cell.textContent = total.toFixed(2);
} else {
// Leave blank for non-numeric columns
cell.textContent = '-';
}
totalsRow.appendChild(cell);
});
// Optional: Add custom styling for the totals row
if (highlightRow) {
totalsRow.style.backgroundColor = '#f0f0f0';
totalsRow.style.fontWeight = 'bold';
totalsRow.style.border = '1px solid black';
// show the border between cells:
totalsRow.style.borderCollapse = 'collapse';
}
// Append the totals row to the table > tbody >
table.tBodies[0].appendChild(totalsRow);
if (logDetails) console.log(` | |-> Appended totals row to table with ID #bbs_custom`);
}
currentRow += 1;
}
return true;
}
catch (error) {
console.error(' |-> Error processing table:', error);
return false;
}
};
// -------------------------------------------------------------------------
// test function
// -------------------------------------------------------------------------
function testFunction() {
console.log("[BBS Extension] Test function called");
window.alert('[BBS Extension] Test function active');
return true;
}
// -------------------------------------------------------------------------
// Sample calls:
// -------------------------------------------------------------------------
// Testing:
// processTables(updateOnPage = true, highlightRow = false, logDetails = true);
// Development:
// processTables(updateOnPage = true, highlightRow = true, logDetails = true);
// Production:
// processTables(updateOnPage = true, highlightRow = true, logDetails = false);
// Un-comment this to test via console:
// window.addEventListener('DOMContentLoaded', () => {
// processTables(updateOnPage = true, highlightRow = true, logDetails = true);
// });
// -------------------------------------------------------------------------
// Event listeners for the popup buttons:
// Description: This file contains the code for the popup window that appears when the extension icon is clicked.
// -------------------------------------------------------------------------
document.addEventListener("DOMContentLoaded", () => {
// Elements
const enableLogging = document.getElementById("enableLogging");
const highlightTotals = document.getElementById("highlightTotals");
const alertBeforeOps = document.getElementById("alertBeforeOps");
const updateOnPage = document.getElementById("updateOnPage");
const saveCustomizationsButton = document.getElementById("saveCustomizations");
// Load saved preferences when popup opens
chrome.storage.local.get(["customizations"], (result) => {
const customizations = result.customizations || {};
enableLogging.checked = customizations.enableLogging !== undefined ? customizations.enableLogging : true;
highlightTotals.checked = customizations.highlightTotals !== undefined ? customizations.highlightTotals : true;
alertBeforeOps.checked = customizations.alertBeforeOps !== undefined ? customizations.alertBeforeOps : true;
updateOnPage.checked = customizations.updateOnPage !== undefined ? customizations.updateOnPage : true;
});
// Save preferences when "Save Customizations" button is clicked
saveCustomizationsButton.addEventListener("click", () => {
const customizations = {
enableLogging: enableLogging.checked,
highlightTotals: highlightTotals.checked,
alertBeforeOps: alertBeforeOps.checked,
updateOnPage: updateOnPage.checked
};
chrome.storage.local.set({ customizations }, () => {
alert("Customizations saved!");
console.log("[BBS Extension] Customizations saved:", customizations);
});
});
});
document.getElementById('addTotals').addEventListener('click', () => {
chrome.storage.local.get(["customizations"], (result) => {
const customizations = result.customizations || {};
if (customizations.enableLogging) {
console.log("[BBS Extension] addTotals button clicked");
}
if (customizations.alertBeforeOps) {
if (!confirm("Are you sure you want to add totals row?")) {
return;
}
}
// Query the active tab
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tabId = tabs[0].id;
chrome.scripting.executeScript({
target: { tabId: tabId },
// Pass customizations values explicitly via args
func: (updateOnPage, highlightRow, logDetails) => {
processTables(updateOnPage, highlightRow, logDetails);
},
args: [
customizations.updateOnPage || false,
customizations.highlightTotals || false,
customizations.enableLogging || false
]
});
});
});
});
document.getElementById('removeTotals').addEventListener('click', () => {
chrome.storage.local.get(["customizations"], (result) => {
const customizations = result.customizations || {};
if (customizations.enableLogging) {
console.log("[BBS Extension] removeTotals button clicked");
}
if (customizations.alertBeforeOps) {
if (!confirm("Are you sure you want to remove totals row?")) {
return;
}
}
// Query the active tab
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
// Get the tabId of the active tab
const tabId = tabs[0].id;
chrome.scripting.executeScript({
// Specify the tabId
target: { tabId: tabId },
// Pass customizations values explicitly via args
func: (logDetails) => {
removeTotalsRows(logDetails);
},
args: [
customizations.enableLogging || true
]
});
});
});
});
document.getElementById('test').addEventListener('click', () => {
console.log("Test button clicked");
// Query the active tab
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
// Get the tabId of the active tab
const tabId = tabs[0].id;
chrome.scripting.executeScript({
// Specify the tabId
target: { tabId: tabId },
// Call the removeTotalsRows function
func: () => testFunction(),
});
});
}
);