-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathims.js
1008 lines (808 loc) · 25.6 KB
/
ims.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
// See the file COPYRIGHT for copyright information.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Apply the HTML theme, light or dark or default.
//
// Adapted from https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript
// Under Creative Commons Attribution 3.0 Unported License
const getStoredTheme = () => localStorage.getItem("theme");
const setStoredTheme = theme => localStorage.setItem("theme", theme);
const getPreferredTheme = () => {
const storedTheme = getStoredTheme();
if (storedTheme) {
return storedTheme;
}
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
};
const setTheme = theme => {
if (theme === "auto") {
document.documentElement.setAttribute("data-bs-theme", (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"));
} else {
document.documentElement.setAttribute("data-bs-theme", theme);
}
};
function applyTheme() {
"use strict";
setTheme(getPreferredTheme());
const showActiveTheme = (theme, focus = false) => {
const themeSwitcher = document.querySelector("#bd-theme");
if (!themeSwitcher) {
return;
}
const themeSwitcherText = document.querySelector("#bd-theme-text");
const activeThemeIcon = document.querySelector(".theme-icon-active use");
const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`);
const svgOfActiveBtn = btnToActive.querySelector("svg use").getAttribute("href");
document.querySelectorAll("[data-bs-theme-value]").forEach(element => {
element.classList.remove("active");
element.setAttribute("aria-pressed", "false");
})
btnToActive.classList.add("active");
btnToActive.setAttribute("aria-pressed", "true");
activeThemeIcon.setAttribute('href', svgOfActiveBtn);
const themeSwitcherLabel = `${themeSwitcherText.textContent} (${btnToActive.dataset.bsThemeValue})`;
themeSwitcher.setAttribute("aria-label", themeSwitcherLabel);
if (focus) {
themeSwitcher.focus();
}
};
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
const storedTheme = getStoredTheme();
if (storedTheme !== "light" && storedTheme !== "dark") {
setTheme(getPreferredTheme());
}
});
showActiveTheme(getPreferredTheme());
document.querySelectorAll("[data-bs-theme-value]").forEach(toggle => {
toggle.addEventListener("click", () => {
const theme = toggle.getAttribute("data-bs-theme-value");
setStoredTheme(theme);
setTheme(theme);
showActiveTheme(theme, true);
});
});
}
// Set the theme immediately, before the rest of the page loads. We need to come back later
// to invoke applyTheme(), as that will only work once the navbar has been drawn (with its
// dropdown theme selector.
setTheme(getPreferredTheme());
//
// HTML encoding
//
// It seems ridiculous that this isn't standard in JavaScript
// It is certainly ridiculous to involve the DOM, but on the other hand, the
// browser will implement this correctly, and any solution using .replace()
// will be buggy. And this will be fast. But still, this is weak.
let _domTextAreaForHaxxors = document.createElement("textarea")
// Convert text to HTML.
function textAsHTML(text) {
_domTextAreaForHaxxors.textContent = text;
return _domTextAreaForHaxxors.innerHTML;
}
// Convert HTML to text.
function htmlAsText(html) {
_domTextAreaForHaxxors.innerHTML = html;
return _domTextAreaForHaxxors.textContent;
}
const integerRegExp = /^\d+$/;
//
// URL substitution
//
function urlReplace(url) {
if (eventID) {
url = url.replace("<event_id>", eventID);
}
return url;
}
//
// Errors
///
function ValueError(message) {
this.name = "ValueError";
this.message = message || "Invalid Value";
this.stack = (new Error()).stack;
}
ValueError.prototype = Object.create(Error.prototype);
ValueError.prototype.constructor = ValueError;
//
// Arrays
//
// Build an array from a range.
function range(start, end, step) {
if (step == null) {
step = 1;
} else if (step === 0) {
throw new ValueError("step = 0");
}
return Array(end - start)
.join(0)
.split(0)
.map(function(val, i) { return (i * step) + start} )
;
}
function compareReportEntries(a, b) {
if (a.created < b.created) { return -1; }
if (a.created > b.created) { return 1; }
if (a.system_entry && ! b.system_entry) { return -1; }
if (! a.system_entry && b.system_entry) { return 1; }
if (a.text < b.text) { return -1; }
if (a.text > b.text) { return 1; }
return 0;
}
//
// Request making
//
function jsonRequest(url, jsonOut, success, error) {
function ok(data, status, xhr) {
if (success) {
success(data, status, xhr);
}
}
function fail(xhr, status, requestError) {
// Intentionally empty response is not an error.
if (
status === "parsererror" &&
xhr.status === 201 &&
xhr.responseText === ""
) {
ok("", "", xhr);
return;
}
if (error) {
error(requestError, status, xhr);
}
}
const args = {
"url": url,
"method": "GET",
"dataType": "json",
"success": ok,
"error": fail,
};
if (jsonOut) {
const jsonText = JSON.stringify(jsonOut);
args["method"] = "POST";
args["contentType"] = "application/json";
args["data"] = jsonText;
}
$.ajax(args);
}
//
// Generic string formatting
//
// Pad a string representing an integer to two digits.
function padTwo(value) {
if (value == null) {
return "?";
}
value = value.toString();
if (value.length === 1) {
return "0" + value;
}
return value;
}
// Convert a minute (0-60) into a value used by IMS form inputs.
// That is: round to the nearest multiple of 5 and pad to two digits.
function normalizeMinute(minute) {
minute = Math.round(minute / 5) * 5;
while (minute > 60) {
minute -= 60;
}
return padTwo(minute);
}
// Apparently some implementations of Number.parseInt don't reliably use base
// 10 by default (eg. when encountering leading zeroes).
function parseInt(stringInt) {
return Number.parseInt(stringInt, 10);
}
//
// Elements
//
// Create a <time> element from a date.
function timeElement(date) {
const timeStampContainer = jQuery(
"<time />", {"datetime": date.toISOString()}
);
timeStampContainer.text(fullDateTime.format(date));
return timeStampContainer;
}
// Disable an element
function disable(element) {
element.attr("disabled", "");
}
// Enable an element
function enable(element) {
element.removeAttr("disabled");
}
// Disable editing for an element
function disableEditing() {
disable($(".form-control"));
enable($(":input[type=search]")); // Don't disable search fields
$(document.documentElement).addClass("no-edit");
}
// Enable editing for an element
function enableEditing() {
enable($(".form-control"));
$(document.documentElement).removeClass("no-edit");
}
// Add an error indication to a control
function controlHasError(element) {
element.parent().addClass("is-invalid");
}
// Add a success indication to a control
function controlHasSuccess(element, clearTimeout) {
element.addClass("is-valid");
if (clearTimeout != null) {
element.delay("1000").queue(function(next) {
controlClear(element);
next();
});
}
}
// Clear error/success indication from a control
function controlClear(element) {
element.removeClass("is-invalid");
element.removeClass("is-valid");
}
//
// Load HTML body template.
//
function loadBody(success) {
function complete() {
applyTheme();
if (typeof eventID !== "undefined") {
$(".event-id").text(eventID);
$(".event-id").addClass("active-event");
}
if (success) {
success();
}
}
detectTouchDevice();
$("body").load(pageTemplateURL, complete);
}
//
// Touch device detection
//
// Add .touch or .no-touch class to top-level element if the browser is or is
// not on a touch device, respectively.
function detectTouchDevice() {
if ("ontouchstart" in document.documentElement) {
$(document.documentElement).addClass("touch");
} else {
$(document.documentElement).addClass("no-touch");
}
}
//
// Controls
//
// Select an option element with a given value from a given select element.
function selectOptionWithValue(select, value) {
select
.children("option")
.prop("selected", false)
;
select
.children("option[value='" + value + "']")
.prop("selected", true)
;
}
//
// Incident data
//
// Look up the name of a priority given its number (1-5).
function priorityNameFromNumber(number) {
switch (number) {
case 1: return "High";
case 2: return "High";
case 3: return "Normal";
case 4: return "Low";
case 5: return "Low︎";
default:
console.warn("Unknown incident priority number: " + number);
return undefined;
}
}
// Look up the glyph for a priority given its number (1-5).
function priorityIconFromNumber(number) {
switch (number) {
case 1: return '↑';
case 2: return '↑';
case 3: return '';
case 4: return '↓';
case 5: return '↓';
default:
console.warn("Unknown incident priority number: " + number);
return undefined;
}
}
// Look up a state's name given its ID.
function stateNameFromID(stateID) {
switch (stateID) {
case "new" : return "New";
case "on_hold" : return "On Hold";
case "dispatched": return "Dispatched";
case "on_scene" : return "On Scene";
case "closed" : return "Closed";
default:
console.warn("Unknown incident state ID: " + stateID);
return undefined;
}
}
// Look up a state's sort key given its ID.
function stateSortKeyFromID(stateID) {
switch (stateID) {
case "new" : return 1;
case "on_hold" : return 2;
case "dispatched": return 3;
case "on_scene" : return 4;
case "closed" : return 5;
default:
console.warn("Unknown incident state ID: " + stateID);
return undefined;
}
}
// Look up a concentric street's name given its ID.
function concentricStreetFromID(streetID) {
if (streetID == null) {
return undefined;
}
const name = concentricStreetNameByID[streetID];
if (name == null) {
console.warn("Unknown street ID: " + streetID);
return undefined;
}
return name;
}
// Return the state ID for a given incident.
function stateForIncident(incident) {
// Data from 2014+ should have incident.state set.
if (incident.state !== undefined) {
return incident.state;
}
console.warn("Unknown state for incident: " + incident);
return undefined;
}
// Return a summary for a given incident.
function summarizeIncident(incident) {
const summary = incident.summary;
const reportEntries = incident.report_entries;
if (!summary) {
if (!reportEntries) {
return "";
}
// Get the first line of the first report entry.
for (const reportEntry of reportEntries) {
if (reportEntry.system_entry) {
// Don't use a system-generated entry in the summary
continue;
}
const lines = reportEntry.text.split("\n");
for (const line of lines) {
if (line) {
return line;
}
}
}
return "";
}
return summary;
}
// Return a summary for a given field report.
function summarizeFieldReport(report) {
return summarizeIncident(report);
}
// Get author for incident
function incidentAuthor(incident) {
for (const entry of incident.report_entries??[]) {
if (entry.author) {
return entry.author;
}
}
return undefined;
}
// Get author for field report
function fieldReportAuthor(report) {
return incidentAuthor(report);
}
// Render incident as a string
function incidentAsString(incident) {
if (incident.number == null) {
return "New Incident";
}
return (
"IMS #" + incident.number + ": " +
summarizeIncident(incident)
);
}
// Render field report as a string
function fieldReportAsString(report) {
if (report.number == null) {
return "New Field Report";
}
return (
"FR #" + report.number +
" (" + fieldReportAuthor(report) + "): " +
summarizeFieldReport(report)
);
}
// Return all user-entered report text for a given incident.
function reportTextFromIncident(incident) {
const texts = [];
if (incident.summary != null) {
texts.push(incident.summary);
}
for (const reportEntry of incident.report_entries??[]) {
// Skip system entries
if (reportEntry.system_entry) {
continue;
}
const text = reportEntry.text;
if (text != null) {
texts.push(text);
}
}
// Incidents page loads all field reports for the event
if (typeof eventFieldReports !== "undefined" && incident.field_reports) {
for (const reportNumber of incident.field_reports) {
const report = eventFieldReports[reportNumber];
const reportText = reportTextFromIncident(report);
texts.push(reportText);
}
}
return texts.join("");
}
// Return a short description for a given location.
function shortDescribeLocation(location) {
if (location == null) {
return undefined;
}
const locationBits = [];
if (location.name != null) {
locationBits.push(location.name);
}
switch (location.type) {
case undefined:
// Fall through to "text" case
case "text":
if (location.description != null) {
locationBits.push(" ");
locationBits.push(location.description);
}
break;
case "garett":
if (location.radial_hour || location.radial_minute || location.concentric) {
locationBits.push(" (");
locationBits.push(padTwo(location.radial_hour));
locationBits.push(":");
locationBits.push(padTwo(location.radial_minute));
locationBits.push("@");
locationBits.push(concentricStreetFromID(location.concentric));
locationBits.push(")");
}
break;
default:
locationBits.push(
"Unknown location type:" + location.type
);
break;
}
return locationBits.join("");
}
//
// DataTables rendering
//
function renderSafeSorted(strings) {
const safe = strings.map(s => textAsHTML(s));
const copy = safe.toSorted((a, b) => a.localeCompare(b));
return copy.join(", ")
}
function renderIncidentNumber(incidentNumber, type, incident) {
switch (type) {
case "display":
return incidentNumber;
case "filter":
return incidentNumber;
case "type":
case "sort":
return incidentNumber;
}
return undefined;
}
function renderPriority(priorityNumber, type, incident) {
switch (type) {
case "display":
return priorityIconFromNumber(priorityNumber);
case "filter":
return priorityNameFromNumber(priorityNumber);
case "type":
case "sort":
return priorityNumber;
}
return undefined;
}
// e.g. "Wed, 8/28"
const shortDate = new Intl.DateTimeFormat(undefined, {
weekday: "short",
month: "numeric",
day: "2-digit",
// timeZone not specified; will use user's timezone
});
// e.g. "19:21"
const shortTime = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
hour12: false,
minute: "numeric",
// timeZone not specified; will use user's timezone
});
// e.g. "Thu, Aug 29, 2024, 19:11:04 EDT"
const fullDateTime = new Intl.DateTimeFormat(undefined, {
weekday: "short",
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
hour12: false,
minute: "numeric",
second: "numeric",
timeZoneName: "short",
// timeZone not specified; will use user's timezone
});
function renderDate(date, type, incident) {
const d = Date.parse(date);
switch (type) {
case "display":
return shortDate.format(d) + "<wbr />@" + shortTime.format(d);
case "filter":
return shortDate.format(d) + " " + shortTime.format(d);
case "type":
case "sort":
return d;
}
return undefined;
}
function renderState(state, type, incident) {
if (state == null) {
state = stateForIncident(incident);
}
switch (type) {
case "display":
return textAsHTML(stateNameFromID(state));
case "filter":
return stateNameFromID(state);
case "type":
return state;
case "sort":
return stateSortKeyFromID(state);
}
return undefined;
}
function renderLocation(data, type, incident) {
if (data == null) {
data = "";
}
switch (type) {
case "display":
return textAsHTML(shortDescribeLocation(data));
case "filter":
case "sort":
return shortDescribeLocation(data);
case "type":
return "";
}
return undefined;
}
function renderSummary(data, type, incident) {
switch (type) {
case "display":
return textAsHTML(summarizeIncident(incident));
case "sort":
return summarizeIncident(incident);
case "filter":
return reportTextFromIncident(incident);
case "type":
return "";
}
return undefined;
}
//
// Populate report entry text
//
function reportEntryElement(entry) {
// Build a container for the entry
const entryContainer = $("<div />", {"class": "report_entry"});
if (entry.system_entry) {
entryContainer.addClass("report_entry_system");
} else {
entryContainer.addClass("report_entry_user");
}
if (entry.merged) {
entryContainer.addClass("report_entry_merged");
}
// Add the timestamp and author
const metaDataContainer = $("<p />", {"class": "report_entry_metadata"})
const timeStampContainer = timeElement(new Date(entry.created));
timeStampContainer.addClass("report_entry_timestamp");
metaDataContainer.append([timeStampContainer, ", "]);
let author = entry.author;
if (author == null) {
author = "(unknown)";
}
const authorContainer = $("<span />");
authorContainer.text(entry.author);
authorContainer.addClass("report_entry_author");
metaDataContainer.append(author);
if (entry.merged) {
metaDataContainer.append(" ");
const link = $("<a />");
link.text("field report #" + entry.merged);
link.attr("href", urlReplace(url_viewFieldReports) + entry.merged)
metaDataContainer.append("(via ");
metaDataContainer.append(link);
metaDataContainer.append(")");
metaDataContainer.addClass("report_entry_source");
}
metaDataContainer.append(":");
entryContainer.append(metaDataContainer);
// Add report text
const lines = entry.text.split("\n");
for (const line of lines) {
const textContainer = $("<p />", {"class": "report_entry_text"});
textContainer.text(line);
entryContainer.append(textContainer);
}
// Add a horizontal line after each entry
entryContainer.append( $("<hr />", {"class": "m-1"}) );
// Return container
return entryContainer;
}
function drawReportEntries(entries) {
const container = $("#report_entries");
container.empty();
if (entries) {
for (const entry of entries) {
container.append(reportEntryElement(entry));
}
container.parent().parent().removeClass("hidden");
} else {
container.parent().parent().addClass("hidden");
}
}
function reportEntryEdited() {
const text = $("#report_entry_add").val().trim();
const submitButton = $("#report_entry_submit");
submitButton.removeClass("btn-default");
submitButton.removeClass("btn-warning");
submitButton.removeClass("btn-danger");
if (!text) {
submitButton.addClass("disabled");
submitButton.addClass("btn-default");
} else {
submitButton.removeClass("disabled");
submitButton.addClass("btn-warning");
}
}
function submitReportEntry() {
const text = $("#report_entry_add").val().trim();
if (!text) {
return;
}
console.log("New report entry:\n" + text);
function ok() {
const $textArea = $("#report_entry_add");
// Clear the report entry
$textArea.val("");
controlHasSuccess($textArea, 1000);
// Reset the submit button
reportEntryEdited();
}
function fail() {
const submitButton = $("#report_entry_submit");
submitButton.removeClass("btn-default");
submitButton.removeClass("btn-warning");
submitButton.addClass("btn-danger");
controlHasError($("#report_entry_add"), 1000);
}
sendEdits({"report_entries": [{"text": text}]}, ok, fail);
}
function editFromElement(element, jsonKey, transform) {
let value = element.val();
if (transform != null) {
value = transform(value);
}
// Build a JSON object representing the requested edits
const edits = {};
const keyPath = jsonKey.split(".");
const lastKey = keyPath.pop();
let current = edits;
for (const path of keyPath) {
const next = {};
current[path] = next;
current = next;
}
current[lastKey] = value;
// Location must include type
if (edits.location != null) {
edits.location.type = "garett"; // UI only supports one type
}
// Send request to server
function ok() {
controlHasSuccess(element, 1000);
}
function fail() {
controlHasError(element);
}
sendEdits(edits, ok, fail);
}
//
// EventSource
//
const incidentChannelName = "incident_update";
const fieldReportChannelName= "field_report_update";
const reattemptMinTimeMillis = 10000;
// Call this from each browsing context, so that it can queue up to become a leader
// to manage the EventSource.
async function requestEventSourceLock() {
// Infinitely attempt to reconnect to the EventSource.
// This addresses the following issue for when IMS lives on AWS:
// https://github.com/burningmantech/ranger-ims-server/issues/1364
while (true) {
const start = Date.now();
// Acquire the lock, set up the EventSource, and start
// broadcasting events to other browsing contexts.
await navigator.locks.request("ims_eventsource_lock", () => {
const {promise, resolve} = Promise.withResolvers();
subscribeToUpdates(resolve);
return promise;
});
const millisSinceStart = Date.now() - start;
await new Promise(r => setTimeout(r, Math.max(0, reattemptMinTimeMillis-millisSinceStart)));
}
}
// This starts the EventSource call and configures event listeners to propagate
// updates to BroadcastChannels. The idea is that only one browsing context should
// have an EventSource connection at any given time.
//
// The "closed" param is a callback to notify the caller that the EventSource has
// been closed.
function subscribeToUpdates(closed) {
const eventSource = new EventSource(
url_eventSource, { withCredentials: true }
);
eventSource.addEventListener("open", function() {
console.log("Event listener opened");
}, true);
eventSource.addEventListener("error", function() {
if (eventSource.readyState === EventSource.CLOSED) {
console.log("Event listener closed");
eventSource.close();
closed();
} else {
// This is likely a retriable error, and EventSource will automatically
// attempt reconnection.
console.log("Event listener error");
}
}, true);
eventSource.addEventListener("Incident", function(e) {
const send = new BroadcastChannel(incidentChannelName);
send.postMessage(JSON.parse(e.data));
}, true);