-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathoptions.js
More file actions
728 lines (590 loc) · 23.2 KB
/
options.js
File metadata and controls
728 lines (590 loc) · 23.2 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
const settingsEnum = {
RANDOMIZEMETHOD: "randomizemethod",
TABOPTION: "taboption",
TABACTIVE: "tabactive",
CONTEXTMENU: "contextmenu",
GROUP: "bookmarkgroups",
CONTEXTOPENCOUNT: "contextopencount",
SHOWACTIONNOTICE: "showactionnotice",
RANDOMIZEHISTORY: "randomizeHistory",
DISABLEAUTOMTICREFRESH: "disableautomaticrefresh",
};
var loading = true;
var treeID = "#bookmarks-wrapper";
var replacements = { "&": "&", '"': """, "'": "'", "<": "<", ">": ">" };
var bookmarkGroupSettings = [
{
name: "Default",
id: "default",
selected: [],
reload: true,
},
];
var selectAll = document.getElementById("select-all");
selectAll.onclick = function () {
var allCheckboxes = document.getElementsByName("selected-folder");
for (var i = 0, n = allCheckboxes.length; i < n; i++) {
allCheckboxes[i].checked = selectAll.checked;
}
};
var randomizedHistoryTracking = false;
// Close Settings
// -------------------------------------------------------------
// var closeSettings = document.getElementById('action-close');
// closeSettings.onclick = function() {
// var currentTab = browser.tabs.getCurrent();
// currentTab.then((res) => {
// browser.tabs.remove(res.id);
// });
// };
// Clear All Data
var btnClearData = document.getElementById("action-clear-data");
btnClearData.onclick = function (e) {
browser.storage.sync.clear();
browser.storage.local.clear();
location.reload();
};
// Log all Data
var btnLogAllData = document.getElementById("action-log-all-data");
btnLogAllData.onclick = async function (e) {
var localStorage = await browser.storage.local.get(null);
console.log(localStorage);
var syncStorage = await browser.storage.sync.get(null);
console.log(syncStorage);
console.log(pluginSettings);
};
// Randomize Method
// -------------------------------------------------------------
var radioRandomizeDefault = document.getElementById("randomoption-default");
radioRandomizeDefault.addEventListener("change", function () {
saveSettings(settingsEnum.RANDOMIZEMETHOD);
});
var radioRandomizeByBookmark = document.getElementById("randomoption-bybookmark");
radioRandomizeByBookmark.addEventListener("change", function () {
saveSettings(settingsEnum.RANDOMIZEMETHOD);
});
var radioRandomizeAlphbetical = document.getElementById("randomoption-alphabetical");
radioRandomizeAlphbetical.addEventListener("change", function () {
saveSettings(settingsEnum.RANDOMIZEMETHOD);
});
// Tab Options
// -------------------------------------------------------------
var checkboxSetTabActive = document.getElementById("activeoption");
checkboxSetTabActive.addEventListener("change", function () {
saveSettings(settingsEnum.TABACTIVE);
});
// Tab Open Options
// ------------------------------------------------------------
var radioOpenOptionDefault = document.getElementById("openoption-default");
radioOpenOptionDefault.addEventListener("change", function () {
saveSettings(settingsEnum.TABOPTION);
});
var radioOpenOptionNew = document.getElementById("openoption-new");
radioOpenOptionNew.addEventListener("change", function () {
saveSettings(settingsEnum.TABOPTION);
});
var radioOpenOptionCurrent = document.getElementById("openoption-current");
radioOpenOptionCurrent.addEventListener("change", function () {
saveSettings(settingsEnum.TABOPTION);
});
// Automatic Refresh
// -------------------------------------------------------------
var checkboxAutomaticRefresh = document.getElementById("disableAutomaticRefresh");
checkboxAutomaticRefresh.addEventListener("change", function () {
saveSettings(settingsEnum.DISABLEAUTOMTICREFRESH);
});
// Bookmark History
// -------------------------------------------------------------
var checkboxRandomizeHistory = document.getElementById("randomizeHistory");
checkboxRandomizeHistory.addEventListener("change", function () {
saveSettings(settingsEnum.RANDOMIZEHISTORY);
});
// Context Options
// -------------------------------------------------------------
var checkboxContextMenu = document.getElementById("showContextMenu");
checkboxContextMenu.addEventListener("change", function () {
saveSettings(settingsEnum.CONTEXTMENU);
});
var checkboxContextOpenCountMenu = document.getElementById("showContextOpenCountMenu");
checkboxContextOpenCountMenu.addEventListener("change", function () {
saveSettings(settingsEnum.CONTEXTOPENCOUNT);
});
// Helper Options
// -------------------------------------------------------------
var checkboxActionNotice = document.getElementById("showActionNotice");
checkboxActionNotice.addEventListener("change", function () {
saveSettings(settingsEnum.SHOWACTIONNOTICE);
});
// Bookmark Option
// -------------------------------------------------------------
var bookmarkGroups = document.getElementById("bookmark-groups");
var addBookmarkGroup = document.getElementById("action-add-group");
var editBookmarkGroup = document.getElementById("action-edit-group");
var deleteBookmarkGroup = document.getElementById("action-delete-group");
var previousSelectedGroup = "nothing";
bookmarkGroups.onchange = function () {
var selected = bookmarkGroups.options[bookmarkGroups.selectedIndex].value;
editBookmarkGroup.disabled = selected === "default";
deleteBookmarkGroup.disabled = selected === "default";
if (selected !== previousSelectedGroup) {
previousSelectedGroup = selected;
loadSelectedBookmarks(selected);
}
};
addBookmarkGroup.onclick = function () {
var name = prompt("Name of new bookmark group");
if (name && name.trim() !== "") {
var ticks = 621355968e9 + new Date().getTime() * 1e4;
var hash = "bookmarks_" + (name + ticks.toString()).hashCode().toString();
// Save current bookmark group
saveBookmarks();
// Add new bookmark group to select dropdown
// And select it
var newOption = document.createElement("option");
newOption.value = hash;
newOption.text = name.trim();
bookmarkGroups.add(newOption);
bookmarkGroups.value = hash;
var newGroupInfo = {
name: name.trim(),
id: hash.toString(),
selected: [],
reload: true,
};
bookmarkGroupSettings.push(newGroupInfo);
saveBookmarks();
// Deselect any checkboxes
var allCheckboxes = document.getElementsByName("selected-folder");
for (var i = 0, n = allCheckboxes.length; i < n; i++) {
allCheckboxes[i].checked = false;
}
// Enable buttons
editBookmarkGroup.disabled = false;
deleteBookmarkGroup.disabled = false;
groupsChanged();
}
};
editBookmarkGroup.onclick = function () {
var selected = bookmarkGroups.options[bookmarkGroups.selectedIndex].value;
var text = bookmarkGroups.options[bookmarkGroups.selectedIndex].text;
if (selected !== "default") {
var nameEdit = prompt("Edit name of bookmark group", text);
if (nameEdit && nameEdit.trim() !== "") {
var editGroupInfo = bookmarkGroupSettings.find((obj) => {
return obj.id === selected;
});
editGroupInfo.name = nameEdit.trim();
saveBookmarks();
bookmarkGroups.options[bookmarkGroups.selectedIndex].textContent = nameEdit;
groupsChanged();
}
}
};
deleteBookmarkGroup.onclick = function () {
var selected = bookmarkGroups.options[bookmarkGroups.selectedIndex].value;
if (selected !== "default") {
if (confirm("Please confirm you want to delete this group")) {
for (var i = 0; i < bookmarkGroupSettings.length; i++) {
if (bookmarkGroupSettings[i].id === selected) {
bookmarkGroupSettings.splice(i, 1);
// Also remove from local storage if it was sync'd
browser.storage.local.remove(selected);
browser.storage.local.remove(`${selected}_index`);
break;
}
}
saveBookmarks();
// Go back to default drop down
bookmarkGroups.value = "default";
// Disable buttons
editBookmarkGroup.disabled = true;
deleteBookmarkGroup.disabled = true;
// Remove from options
for (var i = 0; i < bookmarkGroups.options.length; i++) {
if (bookmarkGroups.options[i].value === selected) {
bookmarkGroups.remove(i);
break;
}
}
loadSelectedBookmarks("default");
groupsChanged();
}
}
};
async function saveSettings(option) {
if (loading === false) {
switch (option) {
case settingsEnum.RANDOMIZEMETHOD:
var randomOption = "default";
var forceReload = false;
if (document.getElementById("randomoption-bybookmark").checked) {
randomOption = "bybookmark";
forceReload = true;
} else if (document.getElementById("randomoption-alphabetical").checked) {
randomOption = "alphabetical";
forceReload = true;
}
browser.storage.sync.set({
randomOption: randomOption,
});
pluginSettings.randomOption = randomOption;
if (forceReload) {
// Bookmarks shuffle method was changed, if it's bybookmark or alphabetical
// Set all bookmark groups to reload
var userSyncOptions = await browser.storage.sync.get();
if (userSyncOptions.groups) {
var bookmarkGroups = userSyncOptions.groups;
for (var i = 0; i < bookmarkGroups.length; i++) {
// Force reload of bookmarks in storage
bookmarkGroups[i].reload = true;
// Reset the selected group index back to zero
var groupIndexName = bookmarkGroups[i].id + "_index";
browser.storage.local.set({
[groupIndexName]: 0,
});
}
browser.storage.sync.set({
groups: bookmarkGroups,
});
preloadBookmarksIntoLocalStorage("randomizeMethodChanged");
}
} else {
preloadBookmarksIntoLocalStorage("saveSettings");
}
break;
case settingsEnum.TABACTIVE:
browser.storage.sync.set({
setActive: document.getElementById("activeoption").checked,
});
break;
case settingsEnum.TABOPTION:
var tabOption = "default";
if (document.getElementById("openoption-new").checked) {
tabOption = "newTab";
} else if (document.getElementById("openoption-current").checked) {
tabOption = "currentTab";
}
browser.storage.sync.set({
tabOption: tabOption,
});
break;
case settingsEnum.DISABLEAUTOMTICREFRESH:
disableAutomaticRefresh = document.getElementById("disableAutomaticRefresh").checked;
browser.storage.sync.set({
disableAutomaticRefresh: disableAutomaticRefresh,
});
break;
case settingsEnum.RANDOMIZEHISTORY:
randomizedHistoryTracking = document.getElementById("randomizeHistory").checked;
browser.storage.sync.set({
randomizeHistory: randomizedHistoryTracking,
});
document.getElementById("history-list-wrapper").style.display = randomizedHistoryTracking ? "block" : "none";
if (!randomizedHistoryTracking) {
browser.storage.local.remove("randomized-history");
loadRandomizeHistory([]);
}
break;
case settingsEnum.CONTEXTMENU:
browser.storage.sync.set({
showContextMenu: document.getElementById("showContextMenu").checked,
});
loadContextMenus();
break;
case settingsEnum.CONTEXTOPENCOUNT:
browser.storage.sync.set({
showContextOpenCountMenu: document.getElementById("showContextOpenCountMenu").checked,
});
loadContextMenus();
break;
case settingsEnum.SHOWACTIONNOTICE:
browser.storage.sync.set({
showActionNotice: document.getElementById("showActionNotice").checked,
});
break;
}
showSavedMessage();
}
}
function showSavedMessage() {
document.getElementById("save-message").style.display = "block";
setTimeout(function () {
document.getElementById("save-message").style.display = "none";
}, 1500);
}
async function loadSavedOptions() {
var syncRes = await browser.storage.sync.get();
if (syncRes.randomOption === "bybookmark") {
document.getElementById("randomoption-bybookmark").checked = true;
randomizeMethod = "bybookmark";
} else if (syncRes.randomOption === "alphabetical") {
document.getElementById("randomoption-alphabetical").checked = true;
randomizeMethod = "alphabetical";
}
document.getElementById("activeoption").checked = syncRes.setActive ?? true;
if (syncRes.tabOption === "newTab") {
document.getElementById("openoption-new").checked = true;
} else if (syncRes.tabOption === "currentTab") {
document.getElementById("openoption-current").checked = true;
}
document.getElementById("disableAutomaticRefresh").checked = syncRes.disableAutomaticRefresh;
document.getElementById("randomizeHistory").checked = syncRes.randomizeHistory;
randomizedHistoryTracking = syncRes.randomizeHistory;
document.getElementById("history-list-wrapper").style.display = randomizedHistoryTracking ? "block" : "none";
if (randomizedHistoryTracking) {
const storageCollection = await browser.storage.local.get("randomized-history");
const historyCollection = storageCollection.hasOwnProperty("randomized-history") ? JSON.parse(storageCollection["randomized-history"]) : [];
loadRandomizeHistory(historyCollection);
}
document.getElementById("showContextMenu").checked = syncRes.showContextMenu;
document.getElementById("showContextOpenCountMenu").checked = syncRes.showContextOpenCountMenu;
document.getElementById("showActionNotice").checked = syncRes.showActionNotice;
// Port over selectedFolders to groups json
if (syncRes.selectedFolders && syncRes.selectedFolders.length) {
bookmarkGroupSettings = changeToGroups(syncRes.selectedFolders);
} else if (syncRes.groups) {
bookmarkGroupSettings = syncRes.groups;
}
// Load bookmark groups
bookmarkGroupSettings.sort(compareBookmarkGroup);
for (var i = 0; i < bookmarkGroupSettings.length; i++) {
if (bookmarkGroupSettings[i].id !== "default") {
var newOption = document.createElement("option");
newOption.value = bookmarkGroupSettings[i].id;
newOption.text = bookmarkGroupSettings[i].name;
bookmarkGroups.add(newOption);
}
}
loadSelectedBookmarks("default");
loading = false;
}
function selectCheckbox(checkbox) {
var currentGroupID = bookmarkGroups.options[bookmarkGroups.selectedIndex].value;
var selectedGroup = bookmarkGroupSettings.find((obj) => {
return obj.id === currentGroupID;
});
if (selectedGroup) {
if (selectedGroup.selected.filter((e) => e === checkbox.value).length > 0) {
if (checkbox.checked === false) {
// Remove it from the bookmarks
var bookmarkIndex = selectedGroup.selected.indexOf(checkbox.value);
if (bookmarkIndex !== -1) {
selectedGroup.selected.splice(bookmarkIndex, 1);
}
}
} else if (checkbox.checked) {
selectedGroup.selected.push(checkbox.value);
}
selectedGroup.reload = true;
saveBookmarks();
}
}
function selectChildren(bookmarkId) {
var currentGroupID = bookmarkGroups.options[bookmarkGroups.selectedIndex].value;
var selectedGroup = bookmarkGroupSettings.find((obj) => {
return obj.id === currentGroupID;
});
if (selectedGroup) {
var parentCheckbox = document.getElementById(bookmarkId);
var childCheckboxes = document.body.querySelectorAll('[data-parent="' + bookmarkId + '"]');
for (var i = 0, n = childCheckboxes.length; i < n; i++) {
childCheckboxes[i].checked = true;
if (selectedGroup.selected.filter((e) => e === childCheckboxes[i].value).length > 0) {
if (childCheckboxes[i].checked === false) {
// Remove it from the bookmarks
var bookmarkIndex = selectedGroup.selected.indexOf(childCheckboxes[i].value);
if (bookmarkIndex !== -1) {
selectedGroup.selected.splice(bookmarkIndex, 1);
}
}
} else if (childCheckboxes[i].checked) {
selectedGroup.selected.push(childCheckboxes[i].value);
}
}
selectedGroup.reload = true;
saveBookmarks();
}
}
function loadSelectedBookmarks(groupID) {
// Deselect all the checkboxes
var allCheckboxes = document.getElementsByName("selected-folder");
for (var i = 0, n = allCheckboxes.length; i < n; i++) {
allCheckboxes[i].checked = false;
}
// Load bookmark group selected options
var groupInfo = bookmarkGroupSettings.find((obj) => {
return obj.id === groupID;
});
if (groupInfo) {
for (var i = 0; i < groupInfo.selected.length; i++) {
if (document.getElementById(groupInfo.selected[i]) !== null) {
document.getElementById(groupInfo.selected[i]).checked = true;
}
}
}
}
function options_processBookmarks(bookmarkItem, indent, parentID) {
if (bookmarkItem.type === "folder" && bookmarkItem.title !== "") {
var countOfBookmarks = 0;
for (var i = 0; i < bookmarkItem.children.length; i++) {
if (bookmarkItem.children[i].type === "bookmark") countOfBookmarks++;
}
var tbody = document.getElementById("bookmarks-folders");
var tr = document.createElement("tr");
var tdInput = document.createElement("td");
tdInput.style.textAlign = "center";
var tdCheckbox = document.createElement("input");
tdCheckbox.type = "checkbox";
tdCheckbox.name = "selected-folder";
tdCheckbox.value = bookmarkItem.id;
tdCheckbox.id = bookmarkItem.id;
tdCheckbox.setAttribute("data-parent", parentID);
tdCheckbox.onclick = function () {
selectCheckbox(this);
};
tdInput.appendChild(tdCheckbox);
tr.appendChild(tdInput);
var tdInfo = document.createElement("td");
var labelTitle = document.createElement("label");
labelTitle.htmlFor = bookmarkItem.id;
labelTitle.appendChild(document.createTextNode(makeIndent(indent) + " " + escapeHTML(bookmarkItem.title)));
if (indent === 0) {
labelTitle.style.fontWeight = "bold";
}
tdInfo.appendChild(labelTitle);
if (bookmarkItem.children) {
var showToggle = false;
for (var i = 0; i < bookmarkItem.children.length; i++) {
if (bookmarkItem.children[i].type === "folder") {
showToggle = true;
break;
}
}
if (showToggle) {
var btnSelectChildren = document.createElement("button");
btnSelectChildren.textContent = "Select direct sub-folders";
btnSelectChildren.style.fontSize = "12px";
btnSelectChildren.style.color = "#555";
btnSelectChildren.style.float = "right";
btnSelectChildren.style.marginTop = "5px";
btnSelectChildren.type = "button";
btnSelectChildren.onclick = function () {
selectChildren(bookmarkItem.id);
};
tdInfo.appendChild(btnSelectChildren);
}
}
tr.appendChild(tdInfo);
var tdCount = document.createElement("td");
tdCount.style.textAlign = "right";
tdCount.appendChild(document.createTextNode(escapeHTML(countOfBookmarks.toString())));
tr.appendChild(tdCount);
tbody.appendChild(tr);
indent++;
}
if (bookmarkItem.children) {
for (child of bookmarkItem.children) {
options_processBookmarks(child, indent, bookmarkItem.id);
}
}
indent--;
}
function makeIndent(indentLength) {
//return ' '.repeat(indentLength);
return " \u00A0\u00A0\u00A0\u00A0 ".repeat(indentLength);
}
function escapeHTML(str) {
return str.replace(/[&"'<>]/g, (m) => replacements[m]);
}
function saveBookmarks() {
browser.storage.sync.set({
groups: bookmarkGroupSettings,
});
showSavedMessage();
}
function groupsChanged() {}
async function loadUsedSpaceSize() {
var gettingSpace = await browser.storage.sync.getBytesInUse(null);
document.getElementById("used-storage-sync").appendChild(document.createTextNode(gettingSpace));
}
async function loadRandomizeHistory(items) {
const listContainer = document.getElementById("randomize-history-list");
listContainer.innerHTML = "";
// Need to handle the list when a user deletes a bookmark
const bookmarkIds = items.map((item) => item.bookmark?.id);
const bookmarks = [];
for (const id of bookmarkIds) {
try {
const bookmarkInfo = await browser.bookmarks.get(id);
bookmarks.push(bookmarkInfo[0]);
} catch (error) {}
}
// No items found
document.getElementById("history-list-none").style.display = bookmarks.length === 0 ? "block" : "none";
for (const item of items) {
if (bookmarks.some((bm) => bm.id === item.bookmark.id)) {
const listItem = document.createElement("li");
listItem.className = "list-group-item";
const path = await getBookmarkPath(item.bookmark.id);
const linkElement = document.createElement("a");
linkElement.href = item.bookmark.url;
linkElement.target = "_blank";
linkElement.className = "fw-bold";
linkElement.textContent = item.bookmark.title;
listItem.appendChild(linkElement);
listItem.appendChild(document.createElement("br"));
const savePathSmall = document.createElement("small");
savePathSmall.textContent = `Save Path: ${path}`;
listItem.appendChild(savePathSmall);
listItem.appendChild(document.createElement("br"));
const dateRandomizedSmall = document.createElement("small");
dateRandomizedSmall.textContent = `Date Randomized: ${new Date(item.dateRandomized).toLocaleString()}`;
listItem.appendChild(dateRandomizedSmall);
listContainer.appendChild(listItem);
}
}
}
async function setup() {
var bookmarksTree = await browser.bookmarks.getTree();
options_processBookmarks(bookmarksTree[0], 0, "root");
loadSavedOptions();
}
document.addEventListener("DOMContentLoaded", setup);
/**
* Watches for changes to the randomized history local storage and updates
* the listing of randomized history
*/
browser.storage.onChanged.addListener((changes, area) => {
if (area === "local" && changes["randomized-history"] && randomizedHistoryTracking) {
const historyArray = JSON.parse(changes["randomized-history"].newValue);
loadRandomizeHistory(historyArray);
}
});
// Accordion
document.querySelectorAll(".accordion-button").forEach((button) => {
button.addEventListener("click", function () {
// Identify the target collapse element (from data-bs-target)
const collapseId = button.getAttribute("data-bs-target");
const collapseEl = document.querySelector(collapseId);
// If we want to close other open accordions in the same group:
const parentSelector = collapseEl.getAttribute("data-bs-parent");
if (parentSelector) {
// Close any other .show elements under the same parent
const parentEl = document.querySelector(parentSelector);
parentEl.querySelectorAll(".accordion-collapse.show").forEach((openEl) => {
if (openEl !== collapseEl) {
openEl.classList.remove("show");
// Mark the corresponding button as collapsed
parentEl.querySelector(`[data-bs-target="#${openEl.id}"]`).classList.add("collapsed");
parentEl.querySelector(`[data-bs-target="#${openEl.id}"]`).setAttribute("aria-expanded", "false");
}
});
}
// Toggle this one
collapseEl.classList.toggle("show");
button.classList.toggle("collapsed");
// Update aria-expanded attribute
const isExpanded = !button.classList.contains("collapsed");
button.setAttribute("aria-expanded", isExpanded.toString());
});
});