-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
1137 lines (1039 loc) · 38.6 KB
/
scripts.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
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 WEBURL = "https://main.d1zpg4kxj2c98i.amplifyapp.com"; // Local development
//const WEBURL = "https://beta.volr.cc"; // Online
const interchangeStationsRennes = ["Sainte-Anne", "Gares"];
const interchangeStationsMarseille = ["Saint-Charles", "Castellane"];
const interchangeStationsParis = [
"Arts et Métiers",
"Aulnay-sous-Bois",
"Balard",
"Barbès-Rochechouart",
"Basilique de Saint-Denis",
"Bastille",
"Belleville",
"Bercy",
"Bibliothèque François Mitterrand",
"Bobigny Pablo Picasso",
"Bondy",
"Bonne Nouvelle",
"Champs-Élysées – Clemenceau",
"Charles De Gaulle-Étoile",
"Chaussée d'Antin - La Fayette",
"Châtelet",
"Châtelet-Les Halles",
"Châtillon-Montrouge",
"Cité Universitaire",
"Concorde",
"Daumesnil",
"Denfert-Rochereau",
"Duroc",
"Franklin D. Roosevelt",
"Gambetta",
"Gare d'Austerlitz",
"Gare de Lyon",
"Gare de l'Est",
"Gare du Nord",
"Garges-Sarcelles",
"Gennevilliers",
"Grands Boulevards",
"Havre-Caumartin",
"Hôpital Béclère",
"Hôtel de Ville",
"Invalides",
"Issy-Val-de-Seine",
"Jaurès",
"Jussieu",
"Juvisy",
"La Courneuve 8 Mai 1945",
"La Défense",
"La Motte Picquet-Grenelle",
"Le Bourget",
"Les Courtilles",
"Les Saules",
"Louis Blanc",
"Madeleine",
"Mairie de Saint-Ouen",
"Maison Blanche",
"Malesherbes",
"Marcadet-Poissonniers",
"Marché de Saint-Denis",
"Massy-Palaiseau",
"Massy-Verrières",
"Michel Ange-Auteuil",
"Michel Ange-Molitor",
"Miromesnil",
"Montparnasse-Bienvenüe",
"Nation",
"Noisy-le-Sec",
"Oberkampf",
"Odéon",
"Opéra",
"Palais Royal - Musée du Louvre",
"Pasteur",
"Pereire-Levallois",
"Pierrefitte Stains",
"Pigalle",
"Place d'Italie",
"Place de Clichy",
"Place des Fêtes",
"Pont du Garigliano",
"Porte Dorée",
"Porte d'Italie",
"Porte d'Ivry",
"Porte d'Orléans",
"Porte de Bagnolet",
"Porte de Charenton",
"Porte de Choisy",
"Porte de Clichy",
"Porte de Clignancourt",
"Porte de Montreuil",
"Porte de Pantin",
"Porte de Saint-Ouen",
"Porte de Vanves",
"Porte de Versailles",
"Porte de Vincennes",
"Porte de la Chapelle",
"Porte de la Villette",
"Porte des Lilas",
"Pyramides",
"Père Lachaise",
"Raspail",
"Reuilly-Diderot",
"Richelieu-Drouot",
"Rosa Parks",
"Réaumur Sébastopol",
"République",
"Saint-Cyr",
"Saint-Denis",
"Saint-Denis - Pleyel",
"Saint-Denis - Porte de Paris",
"Saint-Fargeau",
"Saint-Germain-en-Laye",
"Saint-Lazare",
"Saint-Michel",
"Saint-Ouen",
"Stalingrad",
"Strasbourg-Saint-Denis",
"Sèvres-Babylone",
"Trocadéro",
"Val de Fontenay",
"Villiers",
"Viroflay Rive Gauche",
"Épinay-sur-Orge",
"Épinay-sur-Seine",
];
let isAscending = false; // Variable to keep track of sorting order
// Toggle theme mode button
function toggleDarkMode() {
const themeMode = document.documentElement.getAttribute("data-bs-theme");
const toggleButton = document.querySelector(".mode-toggle");
if (themeMode == "light") {
document.documentElement.setAttribute("data-bs-theme", "dark");
toggleButton.innerHTML = '<i class="bi bi-sun-fill"></i>';
document.cookie = "darkMode=true; path=/; max-age=31536000"; // Set cookie for dark mode
} else {
document.documentElement.setAttribute("data-bs-theme", "light");
toggleButton.innerHTML = '<i class="bi bi-moon-stars-fill"></i>';
document.cookie = "darkMode=false; path=/; max-age=31536000"; // Set cookie for light mode
}
updateButtonStyles();
}
// Check theme mode
function checkDarkModeCookie() {
let darkModeCookie = document.cookie
.split("; ")
.find((row) => row.startsWith("darkMode="));
let isDarkMode = false; // Default to light mode
const toggleButton = document.querySelector(".mode-toggle");
if (darkModeCookie) {
isDarkMode = darkModeCookie.split("=")[1] === "true";
}
if (isDarkMode) {
document.documentElement.setAttribute("data-bs-theme", "dark");
toggleButton.innerHTML = '<i class="bi bi-sun-fill"></i>';
} else {
document.documentElement.setAttribute("data-bs-theme", "light");
toggleButton.innerHTML = '<i class="bi bi-moon-stars-fill"></i>';
}
}
function setCityCookie(city) {
document.cookie = `selectedCity=${city}; path=/; max-age=31536000`; // Set cookie for one year
}
function getCityFromCookie() {
const cityCookie = document.cookie
.split("; ")
.find((row) => row.startsWith("selectedCity="));
return cityCookie ? cityCookie.split("=")[1] : null; // return the city or null if not set
}
function updateButtonStyles() {
const themeMode = document.documentElement.getAttribute("data-bs-theme");
const sortAndFilterButton = document.getElementById("sortAndFilterButton");
if (themeMode === "dark") {
sortAndFilterButton.classList.remove("text-dark");
sortAndFilterButton.classList.add("text-light");
} else {
sortAndFilterButton.classList.remove("text-light");
sortAndFilterButton.classList.add("text-dark");
}
}
// Fetch, filter, and display entries
function fetchEntries(
sortBy,
isAscending,
filterByLine = "all",
filterByState = "all",
selectedCity = document.getElementById("citySelect").value
) {
fetch(`${WEBURL}/api/entries?city=${selectedCity}`)
.then((response) => response.json())
.then((entries) => {
// Apply filters
let filteredEntries = entries.filter(
(entry) =>
(filterByLine === "all" || entry.line === filterByLine) &&
(filterByState === "all" || entry.state === filterByState)
);
if (filteredEntries.length === 0) {
// Display a message or card indicating no entries match the criteria
displayNoEntriesCard();
} else {
// Generate cards with filtered and sorted entries
generateCards(filteredEntries, sortBy, isAscending);
}
})
.catch((error) => console.error("Error fetching entries:", error));
}
function displayNoEntriesCard() {
const cardContainer = document.getElementById("cardContainer");
const noEntriesCard = `
<div class="card mb-3">
<div class="card-body p-3">
<div class="mb-0 fs-7">
<p class="card-text">Aucun danger signalé</p>
</div>
</div>
</div>
`;
cardContainer.innerHTML = noEntriesCard;
}
function populateLinesForm(
selectedCity = document.getElementById("citySelect").value
) {
fetch(`${WEBURL}/api/lines?city=${selectedCity}`)
.then((response) => response.json())
.then((lines) => {
const lineSelect = document.getElementById("line_select");
lineSelect.innerHTML =
'<option selected disabled value="">Ligne...</option>'; // Reset
lines.forEach((line) => {
const option = document.createElement("option");
option.value = line.name;
option.textContent = line.name;
lineSelect.appendChild(option);
});
})
.catch((error) => console.error("Error fetching lines:", error));
}
function populateLinesFilter(
selectedCity = document.getElementById("citySelect").value
) {
fetch(`${WEBURL}/api/lines?city=${selectedCity}`)
.then((response) => response.json())
.then((lines) => {
const lineSelect = document.getElementById("filterByLine");
lineSelect.innerHTML = '<option selected value="all">Toutes</option>'; // Reset
lines.forEach((line) => {
const option = document.createElement("option");
option.value = line.name;
option.textContent = line.name;
lineSelect.appendChild(option);
});
})
.catch((error) => console.error("Error fetching lines:", error));
}
function updateStationSelect(stations) {
const stationSelect = document.getElementById("station_select");
stationSelect.innerHTML =
'<option selected disabled value="">Arrêt...</option>'; // Add a default option
stations.forEach((station) => {
const option = new Option(station, station);
stationSelect.add(option);
});
}
function updateLocationSelect(lineType, selectedStation) {
const locationSelect = document.getElementById("location_select");
locationSelect.innerHTML =
'<option selected disabled value="">Localisation...</option>'; // Add a default option
if (lineType === "subway" || lineType === "rer") {
locationSelect.add(new Option("Quai", "Quai"));
locationSelect.add(new Option("Sortie", "Sortie"));
const isInterchangeStationRennes =
document.getElementById("citySelect").value === "Rennes" &&
interchangeStationsRennes.includes(selectedStation);
const isInterchangeStationMarseille =
document.getElementById("citySelect").value === "Marseille" &&
interchangeStationsMarseille.includes(selectedStation);
const isInterchangeStationParis =
document.getElementById("citySelect").value === "Paris" &&
interchangeStationsParis.includes(selectedStation);
if (
isInterchangeStationRennes ||
isInterchangeStationMarseille ||
isInterchangeStationParis
) {
locationSelect.add(
new Option("Couloir de correspondance", "Couloir de correspondance")
);
}
} else if (lineType === "bus" || lineType === "tramway") {
locationSelect.add(new Option("Arrêt", "Arrêt"));
locationSelect.add(new Option("Véhicule", "Véhicule"));
}
}
function updateDirectionSelect(termini) {
const directionSelect = document.getElementById("direction_select");
directionSelect.innerHTML =
'<option selected disabled value="">Direction...</option>'; // Add a default option
// Iterate over each terminus and add it as an option
termini.forEach((terminus) => {
directionSelect.add(new Option(terminus, terminus));
});
directionSelect.add(new Option("Non précisée", "Non précisée"));
}
function populateLocationSelect(
selectElement,
lineType,
currentLocation,
station
) {
selectElement.innerHTML = ""; // Reset
let locations;
if (lineType === "subway" || lineType === "rer") {
locations = ["Quai", "Sortie"];
const isInterchangeStationRennes =
document.getElementById("citySelect").value === "Rennes" &&
interchangeStationsRennes.includes(station);
const isInterchangeStationMarseille =
document.getElementById("citySelect").value === "Marseille" &&
interchangeStationsMarseille.includes(station);
const isInterchangeStationParis =
document.getElementById("citySelect").value === "Paris" &&
interchangeStationsParis.includes(station);
if (
isInterchangeStationRennes ||
isInterchangeStationMarseille ||
isInterchangeStationParis
) {
locations.push("Couloir de correspondance");
}
} else if (lineType === "bus" || lineType === "tramway") {
locations = ["Arrêt de bus", "Véhicule"];
}
locations.forEach((location) => {
const isSelected = location === currentLocation;
const option = new Option(location, location, isSelected, isSelected);
selectElement.appendChild(option);
});
}
function populateDirectionSelect(selectElement, termini, currentDirection) {
selectElement.innerHTML = ""; // Reset
// Add each terminus as an option
termini.forEach((terminus) => {
const isSelected = terminus === currentDirection;
const option = new Option(terminus, terminus, isSelected, isSelected);
selectElement.appendChild(option);
});
// Add 'Non précisée' option
const isNoPrecisionSelected = "Non précisée" === currentDirection;
selectElement.add(
new Option(
"Non précisée",
"Non précisée",
isNoPrecisionSelected,
isNoPrecisionSelected
)
);
}
function populateEditForm(entryData) {
// Populate and disable Line and Station selects
const lineSelect = document.getElementById(`line_select${entryData._id}`);
lineSelect.innerHTML = `<option selected>${entryData.line}</option>`;
lineSelect.disabled = true;
const stationSelect = document.getElementById(
`station_select${entryData._id}`
);
stationSelect.innerHTML = `<option selected>${entryData.station}</option>`;
stationSelect.disabled = true;
const selectedCity = document.getElementById("citySelect").value; // Get the selected city
// Populate Direction & Location select
fetch(`${WEBURL}/api/lines/name/${entryData.line}?city=${selectedCity}`)
.then((response) => response.json())
.then((lineData) => {
const directionSelect = document.getElementById(
`direction_select${entryData._id}`
);
populateDirectionSelect(
directionSelect,
lineData.terminus,
entryData.direction
);
const locationSelect = document.getElementById(
`location_select${entryData._id}`
);
populateLocationSelect(
locationSelect,
lineData.type,
entryData.location,
entryData.station
);
})
.catch((error) => console.error("Error fetching line details:", error));
// Populate state select
const stateSelect = document.getElementById(`state_select${entryData._id}`);
stateSelect.innerHTML = "";
const states = {
Immobile: "danger",
Mobile: "warning",
};
for (const [text, value] of Object.entries(states)) {
const isSelected = value === entryData.state;
const option = new Option(text, value, isSelected, isSelected);
stateSelect.appendChild(option);
}
}
function pageReset() {
document.getElementById("line_select").innerHTML =
'<option selected disabled value="">Ligne...</option>';
document.getElementById("station_select").innerHTML =
'<option selected disabled value="">Sélectionnez une ligne...</option>';
document.getElementById("location_select").innerHTML =
'<option selected disabled value="">Sélectionnez un arrêt...</option>';
document.getElementById("direction_select").innerHTML =
'<option selected disabled value="">Sélectionnez une ligne...</option>';
populateLinesForm();
populateLinesFilter();
}
// Danger form
document.addEventListener("DOMContentLoaded", function () {
const savedCity = getCityFromCookie();
const defaultCity = "Paris";
const initialCity = savedCity || defaultCity;
// Set initial city in select
document.getElementById("citySelect").value = initialCity;
// Initialize the page with the selected city
populateLinesForm(initialCity);
populateLinesFilter(initialCity);
fetchEntries(
document.getElementById("selectedSort").value,
isAscending,
"all",
"all",
initialCity
);
pageReset();
setupPullToRefresh();
updateButtonStyles();
document.getElementById("citySelect").addEventListener("change", function () {
const selectedCity = this.value;
setCityCookie(selectedCity);
populateLinesForm(selectedCity);
populateLinesFilter(selectedCity);
fetchEntries(
document.getElementById("selectedSort").value,
isAscending,
"all",
"all",
selectedCity
);
});
document
.getElementById("sortDirection")
.addEventListener("click", function () {
isAscending = !isAscending; // Toggle the sorting order
// Update the icon
const icon = this.querySelector("i");
if (!isAscending) {
icon.classList.remove("bi-caret-up-square");
icon.classList.add("bi-caret-down-square");
} else {
icon.classList.remove("bi-caret-down-square");
icon.classList.add("bi-caret-up-square");
}
fetchEntries(
document.getElementById("selectedSort").value,
isAscending,
document.getElementById("filterByLine").value,
document.getElementById("filterByState").value
);
});
document
.getElementById("selectedSort")
.addEventListener("change", function () {
var selectedSortCriteria = this.value;
// Assume fetchEntries() fetches your entries and then calls generateCards
fetchEntries(
selectedSortCriteria,
isAscending,
document.getElementById("filterByLine").value,
document.getElementById("filterByState").value
);
});
document
.getElementById("filterByLine")
.addEventListener("change", function () {
const selectedLine = this.value;
const selectedState = document.getElementById("filterByState").value; // Assuming there's a filterByState dropdown
fetchEntries(
document.getElementById("selectedSort").value,
isAscending,
selectedLine,
selectedState
);
});
document
.getElementById("filterByState")
.addEventListener("change", function () {
const selectedState = this.value;
const selectedLine = document.getElementById("filterByLine").value;
fetchEntries(
document.getElementById("selectedSort").value,
isAscending,
selectedLine,
selectedState
);
});
document.getElementById("line_select").addEventListener("change", function () {
const selectedLineName = this.value;
const selectedCity = document.getElementById("citySelect").value;
fetch(`${WEBURL}/api/lines/name/${selectedLineName}?city=${selectedCity}`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(lineData => {
if (!lineData) {
console.error('No line data received');
return;
}
updateStationSelect(lineData.stations);
updateDirectionSelect(lineData.terminus);
// Set up event listener for station_select
const stationSelect = document.getElementById("station_select");
stationSelect.addEventListener("change", function () {
const selectedStation = this.value;
updateLocationSelect(lineData.type, selectedStation);
});
})
.catch(error => {
console.error("Error fetching line data:", error);
// Reset selects to a valid state if there's an error
document.getElementById("station_select").innerHTML =
'<option selected disabled value="">Sélectionnez une ligne...</option>';
document.getElementById("location_select").innerHTML =
'<option selected disabled value="">Sélectionnez un arrêt...</option>';
document.getElementById("direction_select").innerHTML =
'<option selected disabled value="">Sélectionnez une ligne...</option>';
});
});
var form = document.getElementById("signalADangerForm");
if (form) {
form.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent the default form submission in all cases
const currentDate = new Date();
const isoDateString = currentDate.toISOString();
// Collect form data
const formData = {
city: document.getElementById("citySelect").value,
line: document.getElementById("line_select").value,
station: document.getElementById("station_select").value,
location: document.getElementById("location_select").value,
direction: document.getElementById("direction_select").value,
state: document.getElementById("state_select").value,
last_edit: isoDateString,
};
// Validate form data
if (!validateFormData(formData)) {
// Show validation feedback
form.classList.add("was-validated");
} else {
// If form data is valid, continue with form processing
fetch(`${WEBURL}/submit-form`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
})
.then((response) => response.json())
.then((data) => {
validateSubmissionToast();
fetchEntries(
document.getElementById("selectedSort").value,
isAscending,
document.getElementById("filterByLine").value,
document.getElementById("filterByState").value
);
})
.catch((error) => {
console.error("Error:", error);
});
// Remove validation feedback
form.classList.remove("was-validated");
form.reset();
pageReset();
}
});
}
});
// Loop through entries and generate danger cards
function generateCards(entries, sortBy, isAscending) {
var cardContainer = document.getElementById("cardContainer");
cardContainer.innerHTML = ""; // Clear existing content
// Sort entries based on sortBy and isAscending parameters
if (sortBy === "line" || sortBy === "station") {
// Invert the sort order for 'line' and 'station'
entries.sort((a, b) =>
isAscending
? b[sortBy].localeCompare(a[sortBy])
: a[sortBy].localeCompare(b[sortBy])
);
} else {
// true (ascending) results in newer to older, false (descending) results in older to newer
entries.sort((a, b) =>
isAscending
? new Date(a.last_edit) - new Date(b.last_edit)
: new Date(b.last_edit) - new Date(a.last_edit)
);
}
entries.forEach(function (entry, index) {
// Create card element
var card = document.createElement("div");
card.className = "card mb-3";
card.id = "entryCardIndex" + index;
card.innerHTML = `
<div class="card-header px-3 py-2" id="heading${index}">
<div class="row align-items-center">
<div class="col-auto d-flex align-items-center">
<span class="badge text-bg-${entry.state
} stateBadge" data-bs-toggle="tooltip" data-bs-title="${entry.state === "danger" ? "Immobile" : "Mobile"
}">
${entry.state === "warning"
? '<i class="bi bi-person-walking"></i>'
: '<i class="bi bi-person-arms-up"></i>'
}
</span>
</div>
<div class="col text-truncate px-0">
<h6 class="mb-0 text-truncate" data-bs-toggle="tooltip" data-bs-title="${entry.station
}">${entry.station}</h6>
</div>
<div class="col-auto d-flex justify-content-end">
<div class="dropdown">
<button class="btn btn-danger btn-sm dropdown-toggle" type="button" id="dropdownMenuButton${index}" data-bs-toggle="dropdown" aria-expanded="false">
Gérer
</button>
<ul class="dropdown-menu dropdown-menu-right" style="min-width: auto;" aria-labelledby="dropdownMenuButton${index}">
<li>
<a class="dropdown-item fs-7" href="#" data-bs-toggle="modal" data-bs-target="#confirmModal${index}">
<i class="bi bi-check-circle pe-2 text-success" width="13px" height="13px"></i>
Confirmer
</a>
</li>
<li>
<a class="dropdown-item fs-7" href="#" data-bs-toggle="modal" data-bs-target="#editModal${index}">
<i class="bi bi-pencil-square pe-2 text-primary" width="13px" height="13px"></i>
Modifier
</a>
</li>
<li>
<a class="dropdown-item fs-7" href="#" data-bs-toggle="modal" data-bs-target="#deleteModal${index}">
<i class="bi bi-trash3 pe-2 text-danger" width="13px" height="13px"></i>
Supprimer
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="card-body p-3">
<div class="mb-0 fs-7">
<div class="row align-items-center">
<div class="col-auto">
<img src="./assets/icons/lines/${document.getElementById("citySelect").value
}/${entry.line
}.png" alt="icon line a" width="13px" height="13px" class="d-block mx-auto" data-bs-toggle="tooltip" data-bs-title="Ligne">
</div>
<div class="col px-0">
Ligne ${entry.line}
</div>
</div>
<div class="row align-items-center">
<div class="col-auto">
<i class="bi bi-geo-alt-fill d-block mx-auto" style="font-size: 13px;" data-bs-toggle="tooltip" data-bs-title="Localisation"></i>
</div>
<div class="col px-0">
${entry.location}
</div>
</div>
<div class="row align-items-center">
<div class="col-auto">
<i class="bi bi-signpost-fill d-block mx-auto" style="font-size: 13px;" data-bs-toggle="tooltip" data-bs-title="Direction"></i>
</div>
<div class="col px-0">
${entry.direction}
</div>
</div>
<div class="row align-items-center">
<div class="col">
<div class="row align-items-center">
<div class="col-auto">
<i class="bi bi-clock-fill d-block mx-auto" style="font-size: 13px;" data-bs-toggle="tooltip" data-bs-title="Dernier signalement"></i>
</div>
<div class="col px-0" id="lastEditDisplay${index}">
Il y a ${timeSince(entry.last_edit)}
</div>
</div>
</div>
<div class="col-auto text-end">
<div class="badge numberBadge" data-bs-toggle="tooltip" data-bs-title="Nombre de contributions">${entry.edits
}</div>
</div>
</div>
</div>
</div>
</div>
`;
// Append the card to the container
cardContainer.appendChild(card);
// Modals for Confirmer, Modifier and Supprimer
var confirmModal = document.createElement("div");
confirmModal.innerHTML = `
<!-- Confirm Modal -->
<div class="modal fade" id="confirmModal${index}" tabindex="-1" role="dialog" aria-labelledby="confirmModalLabel${index}" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-6" id="confirmModalLabel${index}H1">Confirmer</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="close"></button>
</div>
<div class="modal-body fs-7">
Souhaitez-vous confirmer la présence du danger ?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal" aria-label="cancel">Annuler</button>
<button type="submit" class="btn btn-sm btn-success" data-bs-dismiss="modal" onclick="updateLastEdit('${entry._id}')">Confirmer</button>
</div>
</div>
</div>
</div>
`;
cardContainer.appendChild(confirmModal);
var editModal = document.createElement("div");
editModal.innerHTML = `
<!-- Edit Modal -->
<div class="modal fade" id="editModal${index}" tabindex="-1" role="dialog" aria-labelledby="editModalLabel${index}" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-6" id="editModalLabel${index}H1">Modifier</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="close"></button>
</div>
<div class="modal-body">
<div class="card-body">
<form id="editForm" class="needs-validation" novalidate>
<div class="input-group input-group-sm mb-2">
<label class="input-group-text" for="line_select${entry._id}">Ligne</label>
<select class="form-select col" id="line_select${entry._id}" aria-label="line" disabled>
<option selected>${entry.line}</option>
</select>
</div>
<div class="input-group input-group-sm mb-2">
<label class="input-group-text" for="station_select${entry._id}">Arrêt</label>
<select class=" form-select" id="station_select${entry._id}" aria-label="station" disabled>
<option selected>${entry.station}</option>
</select>
</div>
<div class="input-group input-group-sm mb-2">
<label class="input-group-text" for="location_select${entry._id}">Localisation</label
aria-label="location">
<select class="form-select" id="location_select${entry._id}">
<option selected>${entry.location}</option>
</select>
</div>
<div class="input-group input-group-sm mb-2">
<label class="input-group-text" for="direction_select${entry._id}">Direction</label>
<select class="form-select" id="direction_select${entry._id}" aria-label="direction">
<option selected>${entry.direction}</option>
</select>
</div>
<div class="input-group input-group-sm mb-0">
<label class="input-group-text" for="state_select${entry._id}">État</label>
<select class="form-select" id="state_select${entry._id}" aria-label="state">
<option selected>${entry.state}</option>
</select>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal" aria-label="cancel">Annuler</button>
<button type="submit" class="btn btn-sm btn-primary" data-bs-dismiss="modal" onclick="editEntry('${entry._id}')">Modifier</button>
</div>
</div>
</div>
</div>
`;
cardContainer.appendChild(editModal);
// Find the "Modifier" link and add an event listener
const editButton = document.querySelector(
`[data-bs-target="#editModal${index}"]`
);
if (editButton) {
editButton.addEventListener("click", function () {
populateEditForm(entry);
});
}
var deleteModal = document.createElement("div");
deleteModal.innerHTML = `
<!-- Delete Modal -->
<div class="modal fade" id="deleteModal${index}" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel${index}" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-6" id="deleteModalLabel${index}H1">Supprimer</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="close"></button>
</div>
<div class="modal-body fs-7">
Souhaitez-vous confirmer l'absence du danger ?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal" aria-label="cancel">Annuler</button>
<button type="submit" class="btn btn-sm btn-danger" data-bs-dismiss="modal" onclick="deleteEntry('${entry._id}')">Supprimer</button>
</div>
</div>
</div>
</div>
`;
cardContainer.appendChild(deleteModal);
initializeTooltips();
});
}
// Form validation
function validateFormData(formData) {
for (let key in formData) {
if (formData[key] === "") {
return false;
}
}
return true;
}
function validateAndEditEntry(entryId) {
// Perform Bootstrap form validation for the entire form
const form = document.getElementById("editForm");
if (form.checkValidity() === false) {
// If the form is invalid, apply Bootstrap's validation styles
form.classList.add("was-validated");
} else {
// If the form is valid, call the editEntry() function
editEntry(entryId);
// You can also remove Bootstrap's validation styles if needed
form.classList.remove("was-validated");
}
}
// Confirm entry
function updateLastEdit(entryId) {
const currentDate = new Date();
const isoDateString = currentDate.toISOString();
const updatedData = {
last_edit: isoDateString,
};
fetch(`${WEBURL}/api/entries/${entryId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updatedData),
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((updatedEntry) => {
validateSubmissionToast();
fetchEntries(
document.getElementById("selectedSort").value,
isAscending,
document.getElementById("filterByLine").value,
document.getElementById("filterByState").value
);
})
.catch((error) => console.error("Error:", error));
}
// Edit entry
function editEntry(entryId) {
const line = document.getElementById(`line_select${entryId}`).value;
const station = document.getElementById(`station_select${entryId}`).value;
const location = document.getElementById(`location_select${entryId}`).value;
const direction = document.getElementById(`direction_select${entryId}`).value;
const state = document.getElementById(`state_select${entryId}`).value;
const updatedData = {
line: line,
station: station,
location: location,
direction: direction,
state: state,
last_edit: new Date().toISOString(),
};
fetch(`${WEBURL}/api/entries/${entryId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updatedData),
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((updatedEntry) => {
validateSubmissionToast();
fetchEntries(
document.getElementById("selectedSort").value,
isAscending,
document.getElementById("filterByLine").value,
document.getElementById("filterByState").value
);
})
.catch((error) => console.error("Error:", error));
}
// Delete entry
function deleteEntry(entryId) {
fetch(`${WEBURL}/api/entries/${entryId}`, {
method: "DELETE",
})
.then((response) => response.json())
.then((data) => {
console.log("Deleted entry:", data);