Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
7198 lines (6196 loc) · 232 KB
/
Copy pathscript.js
File metadata and controls
7198 lines (6196 loc) · 232 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
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
// Government Stuff New Tab Extension
// Main application logic
const CALENDAR_SOURCE_LABELS = {
milwaukee: "City of Milwaukee",
milwaukeecounty: "Milwaukee County",
}
const CALENDAR_SOURCE_COLORS = {
milwaukee: "#0077be",
milwaukeecounty: "#ffc107",
}
const CALENDAR_STORAGE_KEY = "govtab_calendar_events_v2"
const CALENDAR_STORAGE_TTL_MS = 24 * 60 * 60 * 1000 // 24 hours
// Background image shown when the "Milwaukee flag" background mode is active
const FLAG_BACKGROUND_IMAGE = "Peoples-Flag-of-Milwaukee.svg"
const DEFAULT_BACKGROUND_COLOR = "#0077be"
// How long a rotating photo stays before the next one is picked, keyed by
// the settings.backgroundCycle value. "every" (0) means a fresh random pick
// on every new tab instead of a time-based rotation.
const BACKGROUND_CYCLE_INTERVALS_MS = {
every: 0,
hourly: 60 * 60 * 1000,
daily: 24 * 60 * 60 * 1000,
weekly: 7 * 24 * 60 * 60 * 1000,
}
// Background photos sourced from images/photo-cred.csv (Unsplash attribution
// links open in a new tab so they don't navigate away from the new tab page)
const BACKGROUND_PHOTOS = [
{
file: "wei-zeng-6KffRaLsClk-unsplash.jpg",
credit:
'Photo by <a href="https://unsplash.com/@fotowei?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Wei Zeng</a> on <a href="https://unsplash.com/photos/cityscape-during-nighttime-6KffRaLsClk?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Unsplash</a>',
},
{
file: "federico-ramirez-ij1r1T28DX4-unsplash.jpg",
credit:
'Photo by <a href="https://unsplash.com/@peryco?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Federico Ramirez</a> on <a href="https://unsplash.com/photos/a-view-of-a-city-from-across-the-water-ij1r1T28DX4?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Unsplash</a>',
},
{
file: "casey-lovegrove-kIQbHBWtQA4-unsplash.jpg",
credit:
'Photo by <a href="https://unsplash.com/@clovegrove7?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Casey Lovegrove</a> on <a href="https://unsplash.com/photos/a-large-orange-sculpture-in-a-city-kIQbHBWtQA4?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Unsplash</a>',
},
{
file: "runde-imaging-YS1MJEF1z0s-unsplash.jpg",
credit:
'Photo by <a href="https://unsplash.com/@rundeimaging?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Runde Imaging</a> on <a href="https://unsplash.com/photos/white-concrete-building-YS1MJEF1z0s?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Unsplash</a>',
},
{
file: "mark-rohan-vN7Cpe2MSf8-unsplash.jpg",
credit:
'Photo by <a href="https://unsplash.com/@wackomac007?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Mark Rohan</a> on <a href="https://unsplash.com/photos/red-and-black-unk-neon-signage-vN7Cpe2MSf8?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Unsplash</a>',
},
{
file: "tom-barrett-hoA7e2HRr70-unsplash.jpg",
credit:
'Photo by <a href="https://unsplash.com/@wistomsin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Tom Barrett</a> on <a href="https://unsplash.com/photos/water-mirror-reflection-of-concrete-high-rise-buildings-hoA7e2HRr70?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Unsplash</a>',
},
{
file: "kellie-klumb-GV5touJMTaw-unsplash.jpg",
credit:
'Photo by <a href="https://unsplash.com/@kklumb?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Kellie Klumb</a> on <a href="https://unsplash.com/photos/landscape-photography-of-cityscape-GV5touJMTaw?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Unsplash</a>',
},
{
file: "wes-lewis-uBsM4cHFSH0-unsplash.jpg",
credit:
'Photo by <a href="https://unsplash.com/@westhmus?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">wes lewis</a> on <a href="https://unsplash.com/photos/city-skyline-during-night-time-uBsM4cHFSH0?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" target="_blank" rel="noopener noreferrer">Unsplash</a>',
},
]
class NewTabApp {
constructor() {
this.favorites = []
this.currentAddress = ""
this.civicData = null
this.lastAddress = "" // Cache for last used address
this.milwaukeeCache = new Map() // Smart cache for Milwaukee data
this.cacheExpiry = 7 * 24 * 60 * 60 * 1000 // 7 days in milliseconds
this.faviconCacheExpiry = 30 * 24 * 60 * 60 * 1000 // 30 days in milliseconds
this.faviconMemoryCache = new Map() // domain -> data URL, avoids re-hitting storage within a session
this.settings = {
// This is the sticky, persisted preference used on wide/desktop
// layouts. Narrow/mobile layouts never read it directly - they use
// this.narrowSidebarOpen instead (see isSidebarOpen()), which
// always starts closed and is never saved.
showSidebar: true,
// User-dragged sidebar width in px, or null to use the CSS default.
// Only meaningful on wide/desktop layouts - the mobile bottom sheet
// always spans the full viewport width regardless of this value.
sidebarWidth: null,
autoLocation: false,
theme: "light", // Default theme
apiKey: "",
propublicaApiKey: "",
// Background: "photo" (rotating Unsplash photos), "solid" (a flat
// color), or "flag" (the Milwaukee flag SVG)
backgroundMode: "photo",
backgroundColor: DEFAULT_BACKGROUND_COLOR,
// How often the rotating photo changes: "every", "hourly", "daily",
// or "weekly" - see BACKGROUND_CYCLE_INTERVALS_MS
backgroundCycle: "daily",
// Tracks which rotating photo is showing and when it was last
// changed, so the same photo persists across new tabs until its
// cycle interval elapses
backgroundPhotoState: null,
}
// Ephemeral, session-only "is the bottom sheet open" state for
// narrow/mobile layouts - intentionally not part of this.settings so
// it's never persisted. Always starts closed.
this.narrowSidebarOpen = false
this.sidebarDetailView = {
listSection: null,
detailSection: null,
detailContent: null,
detailSubtitle: null,
backButton: null,
}
this.activeOfficialDetail = null
this.calendarViewDate = new Date() // Start with current month
console.log(
"[Calendar Init] calendarViewDate set to:",
this.calendarViewDate.toDateString(),
)
this.calendarContainer = null
this.officialsToggleControls = null
this.officialsListExpandedBySearch = false
this.calendarEvents = []
this.calendarEventIndex = new Map()
this.selectedCalendarDate = null
this.calendarEventsMeta = {
fetchedAt: null,
stale: false,
}
this.calendarDetailView = {
listContainer: null,
detailSection: null,
detailContent: null,
detailSubtitle: null,
backButton: null,
activeTrigger: null,
activeButton: null,
}
this.activeCalendarEvent = null
// Initialize theme early
this.initializeTheme()
// Google Civic Information API endpoints
this.civicApiEndpoint =
"https://www.googleapis.com/civicinfo/v2/representatives"
this.electionsApiEndpoint =
"https://www.googleapis.com/civicinfo/v2/elections"
this.divisionsApiEndpoint =
"https://www.googleapis.com/civicinfo/v2/divisionsByAddress"
this.propublicaApi = new ProPublicaApi(this.settings.propublicaApiKey)
this.milwaukeeApi = new MilwaukeeApi()
this.governmentOfficials = new GovernmentOfficials()
this.milwaukeeCouncil = new MilwaukeeCouncil()
this.milwaukeeCountyBoard = new MilwaukeeCountyBoard()
this.milwaukeeSchoolBoard = new MilwaukeeSchoolBoard()
// Track whether user is currently editing the address
this.editingAddress = false
this.init()
}
// Get the Monday of the previous week
getPreviousWeekMonday() {
const today = new Date()
const currentDay = today.getDay()
// Calculate days back to last Monday (1-7 days)
const daysToLastMonday = currentDay === 0 ? 6 : currentDay - 1
// Then go back another 7 days to get previous week's Monday
const daysToSubtract = daysToLastMonday + 7
const previousMonday = new Date(today)
previousMonday.setDate(today.getDate() - daysToSubtract)
previousMonday.setHours(0, 0, 0, 0)
console.log(
"[Frontend] getPreviousWeekMonday: today =",
today.toDateString(),
"(day",
currentDay + ") result =",
previousMonday.toDateString(),
)
return previousMonday
}
// Picks which rotating background photo should show right now, based on
// settings.backgroundCycle. "every" always re-rolls; the timed intervals
// keep the same photo (persisted in settings.backgroundPhotoState) until
// their interval elapses, then advance to the next one.
getBackgroundPhotoIndex() {
const total = BACKGROUND_PHOTOS.length
const cycle = this.settings.backgroundCycle || "daily"
const intervalMs =
BACKGROUND_CYCLE_INTERVALS_MS[cycle] ??
BACKGROUND_CYCLE_INTERVALS_MS.daily
if (intervalMs <= 0) {
return Math.floor(Math.random() * total)
}
const state = this.settings.backgroundPhotoState
const now = Date.now()
if (
state &&
typeof state.index === "number" &&
state.index >= 0 &&
state.index < total &&
typeof state.changedAt === "number" &&
now - state.changedAt < intervalMs
) {
return state.index
}
const previousIndex = state && typeof state.index === "number" ? state.index : -1
const nextIndex =
total > 1 ? (previousIndex + 1 + total) % total : 0
this.settings.backgroundPhotoState = { index: nextIndex, changedAt: now }
this.saveSettings()
return nextIndex
}
// Applies the current background settings (rotating photo, solid color,
// or the Milwaukee flag), fading it in once ready (avoids a jarring
// pop-in) and rendering the Unsplash credit only in photo mode.
applyBackground() {
const bgEl = document.querySelector(".page-bg")
const creditEl = document.getElementById("photo-credit")
if (!bgEl || !creditEl) return
bgEl.classList.remove("loaded")
creditEl.innerHTML = ""
const mode = this.settings.backgroundMode || "photo"
if (mode === "solid") {
bgEl.style.backgroundImage = "none"
bgEl.style.backgroundColor =
this.settings.backgroundColor || DEFAULT_BACKGROUND_COLOR
requestAnimationFrame(() => bgEl.classList.add("loaded"))
return
}
bgEl.style.backgroundColor = ""
if (mode === "flag") {
const preload = new Image()
preload.onload = () => {
bgEl.style.backgroundImage = `linear-gradient(to bottom, rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0.35)), url("${FLAG_BACKGROUND_IMAGE}")`
requestAnimationFrame(() => bgEl.classList.add("loaded"))
}
preload.src = FLAG_BACKGROUND_IMAGE
return
}
// Default: rotating photo mode
const photo = BACKGROUND_PHOTOS[this.getBackgroundPhotoIndex()]
const imageUrl = `images/${photo.file}`
const preload = new Image()
preload.onload = () => {
bgEl.style.backgroundImage = `linear-gradient(to bottom, rgba(0, 0, 0, 0.25), rgba(0, 0, 0, 0.45)), url("${imageUrl}")`
requestAnimationFrame(() => bgEl.classList.add("loaded"))
}
preload.src = imageUrl
creditEl.innerHTML = photo.credit
}
// Initialize theme before DOM is fully loaded
initializeTheme() {
// Check for system preference
const prefersDark =
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
// Try to get saved theme from localStorage immediately
try {
const saved = localStorage.getItem("govtab_settings")
if (saved) {
const settings = JSON.parse(saved)
this.settings.theme = settings.theme || (prefersDark ? "dark" : "light")
} else {
this.settings.theme = prefersDark ? "dark" : "light"
}
} catch (error) {
this.settings.theme = prefersDark ? "dark" : "light"
}
// Apply theme immediately
document.documentElement.setAttribute("data-theme", this.settings.theme)
console.log("Theme initialized:", this.settings.theme)
}
async init() {
try {
console.log("Government Tab App initializing...")
await this.loadSettings()
console.log("Settings loaded:", this.settings)
this.propublicaApi.apiKey = this.settings.propublicaApiKey
await this.loadFavorites()
console.log("Favorites loaded:", this.favorites.length, "items")
await this.loadLastAddress()
console.log("Last address loaded:", this.lastAddress)
this.initializeUI()
this.applyBackground()
console.log("UI initialized")
await this.updateVersionDisplay()
this.bindEvents()
console.log("Events bound")
if (this.settings.autoLocation) {
this.getUserLocation()
} else if (!this.lastAddress) {
// Show welcome message only when no saved address exists
this.renderNoAddressMessage()
}
console.log("Government Tab App ready!")
} catch (error) {
console.error("Error initializing app:", error)
}
}
// Search functionality using Chrome Search API
handleSearch(query) {
if (!query.trim()) return
// Use Chrome Search API to respect user's default search provider
if (typeof chrome !== "undefined" && chrome.search) {
chrome.search.query(
{
text: query.trim(),
disposition: "CURRENT_TAB",
},
() => {
// Announce to screen reader
this.announceToScreenReader(
`Searching for "${query.trim()}" using your default search provider`,
)
},
)
} else {
// Fallback for testing environment - use Google
const searchUrl =
"https://www.google.com/search?q=" + encodeURIComponent(query.trim())
window.location.href = searchUrl
// Announce to screen reader
this.announceToScreenReader(`Searching for "${query.trim()}"`)
}
}
// Settings and Storage Management
async loadSettings() {
try {
if (typeof chrome !== "undefined" && chrome.storage) {
const result = await chrome.storage.sync.get(["settings"])
if (result.settings) {
this.settings = { ...this.settings, ...result.settings }
}
} else {
// Fallback to localStorage for testing
const stored = localStorage.getItem("govtab_settings")
if (stored) {
this.settings = { ...this.settings, ...JSON.parse(stored) }
}
}
} catch (error) {
console.log("Using default settings:", error)
}
}
async saveSettings() {
try {
if (typeof chrome !== "undefined" && chrome.storage) {
await chrome.storage.sync.set({ settings: this.settings })
} else {
// Fallback to localStorage for testing
localStorage.setItem("govtab_settings", JSON.stringify(this.settings))
}
} catch (error) {
console.error("Error saving settings:", error)
}
}
async loadFavorites() {
try {
if (typeof chrome !== "undefined" && chrome.storage) {
const result = await chrome.storage.sync.get(["favorites"])
this.favorites = result.favorites || this.getDefaultFavorites()
} else {
// Fallback to localStorage for testing
const stored = localStorage.getItem("govtab_favorites")
this.favorites = stored
? JSON.parse(stored)
: this.getDefaultFavorites()
}
} catch (error) {
console.log("Using default favorites:", error)
this.favorites = this.getDefaultFavorites()
}
}
async saveFavorites() {
try {
if (typeof chrome !== "undefined" && chrome.storage) {
await chrome.storage.sync.set({ favorites: this.favorites })
} else {
// Fallback to localStorage for testing
localStorage.setItem("govtab_favorites", JSON.stringify(this.favorites))
}
} catch (error) {
console.error("Error saving favorites:", error)
}
}
async loadLastAddress() {
try {
if (typeof chrome !== "undefined" && chrome.storage) {
const result = await chrome.storage.sync.get(["lastAddress"])
this.lastAddress = result.lastAddress || ""
} else {
// Fallback to localStorage for testing
const stored = localStorage.getItem("govtab_lastAddress")
this.lastAddress = stored || ""
}
} catch (error) {
console.log("Using default address:", error)
this.lastAddress = ""
}
}
async saveLastAddress(address) {
this.lastAddress = address
try {
if (typeof chrome !== "undefined" && chrome.storage) {
await chrome.storage.sync.set({ lastAddress: address })
} else {
// Fallback to localStorage for testing
localStorage.setItem("govtab_lastAddress", address)
}
} catch (error) {
console.error("Error saving last address:", error)
}
}
// Smart Caching System
getCacheKey(address) {
return `milwaukee_${address.toLowerCase().replace(/[^a-z0-9]/g, "_")}`
}
async getCachedData(address) {
const cacheKey = this.getCacheKey(address)
try {
let cachedData
if (typeof chrome !== "undefined" && chrome.storage) {
const result = await chrome.storage.local.get([cacheKey])
cachedData = result[cacheKey]
} else {
// Fallback to localStorage for testing
const stored = localStorage.getItem(cacheKey)
cachedData = stored ? JSON.parse(stored) : null
}
if (cachedData) {
const now = Date.now()
const cacheAge = now - cachedData.timestamp
console.log(
`Cache found for "${address}", age: ${Math.round(
cacheAge / 1000 / 60,
)} minutes`,
)
if (cacheAge < this.cacheExpiry) {
console.log("Using cached data")
return cachedData.data
} else {
console.log("Cache expired, removing old data")
await this.removeCachedData(address)
}
}
return null
} catch (error) {
console.error("Error reading cache:", error)
return null
}
}
async setCachedData(address, data) {
const cacheKey = this.getCacheKey(address)
const cachedItem = {
data: data,
timestamp: Date.now(),
address: address,
}
try {
if (typeof chrome !== "undefined" && chrome.storage) {
await chrome.storage.local.set({ [cacheKey]: cachedItem })
} else {
// Fallback to localStorage for testing
localStorage.setItem(cacheKey, JSON.stringify(cachedItem))
}
console.log(`Data cached for "${address}"`)
} catch (error) {
console.error("Error saving to cache:", error)
}
}
async removeCachedData(address) {
const cacheKey = this.getCacheKey(address)
try {
if (typeof chrome !== "undefined" && chrome.storage) {
await chrome.storage.local.remove([cacheKey])
} else {
// Fallback to localStorage for testing
localStorage.removeItem(cacheKey)
}
} catch (error) {
console.error("Error removing from cache:", error)
}
}
async clearAllCache() {
try {
if (typeof chrome !== "undefined" && chrome.storage) {
const allData = await chrome.storage.local.get(null)
const cacheKeys = Object.keys(allData).filter((key) =>
key.startsWith("milwaukee_"),
)
if (cacheKeys.length > 0) {
await chrome.storage.local.remove(cacheKeys)
console.log(`Cleared ${cacheKeys.length} cached items`)
}
} else {
// Fallback for localStorage
const keys = Object.keys(localStorage)
const cacheKeys = keys.filter((key) => key.startsWith("milwaukee_"))
cacheKeys.forEach((key) => localStorage.removeItem(key))
console.log(`Cleared ${cacheKeys.length} cached items`)
}
} catch (error) {
console.error("Error clearing cache:", error)
}
}
getDefaultFavorites() {
return [
{
id: "1",
name: "MKE Gov",
url: "https://www.milwaukee.gov/",
icon: "Peoples-Flag-of-Milwaukee.svg",
},
{
id: "2",
name: "YouTube",
url: "https://youtube.com",
},
{
id: "3",
name: "Gmail",
url: "https://gmail.com",
},
{
id: "4",
name: "GitHub",
url: "https://github.com",
},
{
id: "5",
name: "Bluesky",
url: "https://bsky.app",
},
{
id: "6",
name: "Reddit",
url: "https://reddit.com",
},
]
}
// UI Initialization
initializeUI() {
this.applyTheme()
this.setupSidebarDetailView()
this.setupCalendar()
this.setupSimplifiedCalendar() // Initialize simplified calendar weeks
this.setupOfficialsToggle()
this.loadCalendarEvents()
this.renderFavorites()
this.updateSidebarVisibility()
this.applySidebarWidth()
this.updateSettingsUI()
this.populateLastAddress()
}
// Sidebar min/max drag-resize bounds, in px.
SIDEBAR_MIN_WIDTH = 280
SIDEBAR_MAX_WIDTH = 640
clampSidebarWidth(width) {
const viewportMax = Math.round(window.innerWidth * 0.7)
const max = Math.min(this.SIDEBAR_MAX_WIDTH, viewportMax)
return Math.min(Math.max(width, this.SIDEBAR_MIN_WIDTH), max)
}
// Applies the persisted custom sidebar width (if any) to the layout.
// Safe to call on every resize/orientation change since it re-clamps
// against the current viewport width.
applySidebarWidth() {
const container = document.querySelector(".container")
if (!container) return
if (this.settings.sidebarWidth) {
const width = this.clampSidebarWidth(this.settings.sidebarWidth)
container.style.setProperty("--sidebar-width", `${width}px`)
} else {
container.style.removeProperty("--sidebar-width")
}
}
// Lets the user drag the handle on the sidebar's left edge to resize it.
// Desktop-only: on narrow/mobile layouts the sidebar becomes a full-width
// bottom sheet, so horizontal resizing doesn't apply there.
setupSidebarResize() {
const handle = document.getElementById("sidebar-resize-handle")
const container = document.querySelector(".container")
if (!handle || !container) return
let dragging = false
const onPointerMove = (e) => {
if (!dragging) return
// Sidebar sits on the right edge of the viewport, so its width is
// the distance from the pointer to the right edge.
const width = this.clampSidebarWidth(window.innerWidth - e.clientX)
container.style.setProperty("--sidebar-width", `${width}px`)
}
const onPointerUp = (e) => {
if (!dragging) return
dragging = false
handle.classList.remove("dragging")
document.body.classList.remove("sidebar-resizing")
try {
handle.releasePointerCapture(e.pointerId)
} catch (err) {
// no-op: pointer capture may already be released
}
const width = this.clampSidebarWidth(window.innerWidth - e.clientX)
this.settings.sidebarWidth = width
this.saveSettings()
document.removeEventListener("pointermove", onPointerMove)
document.removeEventListener("pointerup", onPointerUp)
}
handle.addEventListener("pointerdown", (e) => {
if (this.isNarrowViewport()) return
dragging = true
handle.classList.add("dragging")
document.body.classList.add("sidebar-resizing")
try {
handle.setPointerCapture(e.pointerId)
} catch (err) {
// no-op: some browsers restrict capture on non-primary pointers
}
document.addEventListener("pointermove", onPointerMove)
document.addEventListener("pointerup", onPointerUp)
e.preventDefault()
})
// Keyboard resizing for accessibility: arrow keys nudge the width.
handle.addEventListener("keydown", (e) => {
if (this.isNarrowViewport()) return
const step = 24
let delta = 0
if (e.key === "ArrowLeft") delta = step
else if (e.key === "ArrowRight") delta = -step
else return
e.preventDefault()
const current =
this.settings.sidebarWidth ||
document.getElementById("civic-sidebar")?.offsetWidth ||
380
const width = this.clampSidebarWidth(current + delta)
container.style.setProperty("--sidebar-width", `${width}px`)
this.settings.sidebarWidth = width
this.saveSettings()
})
window.addEventListener("resize", () => {
this.applySidebarWidth()
})
}
applyTheme() {
console.log("Applying theme:", this.settings.theme)
// Set the data-theme attribute
document.documentElement.setAttribute("data-theme", this.settings.theme)
// DEBUG: Also set it on body for testing
document.body.setAttribute("data-theme", this.settings.theme)
// Update page title for debugging
document.title = `New Tab - MKE`
// Log the current attribute for debugging
console.log(
"HTML data-theme attribute:",
document.documentElement.getAttribute("data-theme"),
)
console.log(
"Body data-theme attribute:",
document.body.getAttribute("data-theme"),
)
const themeButton = document.getElementById("theme-toggle")
if (themeButton) {
themeButton.textContent = this.settings.theme === "dark" ? "☀️" : "🌙"
console.log("Theme button updated:", themeButton.textContent)
} else {
console.error("Theme toggle button not found during applyTheme")
}
// Force a repaint
document.body.style.display = "none"
document.body.offsetHeight // Trigger reflow
document.body.style.display = ""
}
setupSidebarDetailView() {
const listSection = document.querySelector(".sidebar .officials-section")
const detailSection = document.getElementById("official-detail-section")
const detailContent = document.getElementById("official-detail-content")
const detailSubtitle = document.getElementById("official-detail-subtitle")
const backButton = document.getElementById("official-detail-back")
this.sidebarDetailView = {
listSection,
detailSection,
detailContent,
detailSubtitle,
backButton,
activeTrigger: null,
activeButton: null,
}
if (detailSection && !detailSection.hasAttribute("tabindex")) {
detailSection.setAttribute("tabindex", "-1")
}
if (backButton) {
backButton.addEventListener("click", () => {
this.closeOfficialDetail()
})
}
if (detailSection) {
detailSection.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
this.closeOfficialDetail()
}
})
}
// Ensure the list is visible by default
this.closeOfficialDetail({ silent: true })
}
// Narrow/mobile layouts switch the sidebar to an on-demand bottom
// sheet (see the max-width: 768px rules in styles.css)
isNarrowViewport() {
return Boolean(
window.matchMedia && window.matchMedia("(max-width: 768px)").matches,
)
}
// Whether the sidebar/bottom-sheet should currently be visible. Wide
// layouts follow the persisted, sticky settings.showSidebar preference;
// narrow layouts always use the ephemeral, never-persisted
// narrowSidebarOpen state instead, so opening the bottom sheet on
// mobile never overwrites (or is overwritten by) the desktop setting.
isSidebarOpen() {
return this.isNarrowViewport()
? this.narrowSidebarOpen
: this.settings.showSidebar
}
// Opens/closes the sidebar, writing to whichever state backs the
// current layout (see isSidebarOpen). Use this from click handlers
// instead of setting settings.showSidebar directly.
setSidebarOpen(open) {
if (this.isNarrowViewport()) {
this.narrowSidebarOpen = open
this.updateSidebarVisibility()
} else {
this.settings.showSidebar = open
this.updateSidebarVisibility()
this.updateSettingsUI()
this.saveSettings()
}
}
updateSidebarVisibility() {
const container = document.querySelector(".container")
const sidebar = document.getElementById("civic-sidebar")
const showSidebarBtn = document.getElementById("show-sidebar-btn")
const showSidebarHeaderBtn = document.getElementById(
"show-sidebar-header-btn",
)
const toggleSidebarBtn = document.getElementById("toggle-sidebar")
if (this.isSidebarOpen()) {
container.classList.remove("sidebar-collapsed")
sidebar.classList.remove("collapsed")
showSidebarBtn.classList.add("hidden")
if (showSidebarHeaderBtn) showSidebarHeaderBtn.classList.add("hidden")
if (toggleSidebarBtn) toggleSidebarBtn.classList.remove("rotated")
} else {
container.classList.add("sidebar-collapsed")
sidebar.classList.add("collapsed")
showSidebarBtn.classList.remove("hidden")
if (showSidebarHeaderBtn)
showSidebarHeaderBtn.classList.remove("hidden")
if (toggleSidebarBtn) toggleSidebarBtn.classList.add("rotated")
}
}
// Keeps the bottom sheet's open/closed state correct as the window
// crosses the narrow/wide breakpoint: shrinking into narrow always
// hides it (ignoring whatever was showing), and widening back out
// restores the persisted desktop preference.
setupResponsiveSidebarBehavior() {
const query = window.matchMedia && window.matchMedia("(max-width: 768px)")
if (!query) return
const handleChange = (event) => {
if (event.matches) {
// Just became narrow: always start hidden here
this.narrowSidebarOpen = false
}
this.updateSidebarVisibility()
}
if (query.addEventListener) {
query.addEventListener("change", handleChange)
} else if (query.addListener) {
// Safari <14 fallback
query.addListener(handleChange)
}
}
updateSettingsUI() {
document.getElementById("show-sidebar").checked = this.isSidebarOpen()
document.getElementById("auto-location").checked =
this.settings.autoLocation
// Update search placeholder
this.updateSearchPlaceholder()
}
updateSearchPlaceholder() {
const searchInput = document.getElementById("search-input")
if (searchInput) {
searchInput.placeholder = "Search the web..."
searchInput.setAttribute(
"aria-label",
"Search the web using your default search provider",
)
}
}
setupCalendar() {
const grid = document.getElementById("calendar-grid")
const label = document.getElementById("calendar-month-label")
const prevBtn = document.getElementById("calendar-prev")
const nextBtn = document.getElementById("calendar-next")
const eventsContainer = document.getElementById("calendar-events")
const header = document.querySelector(".calendar-header")
const detailSection = document.getElementById("calendar-detail")
const detailContent = document.getElementById("calendar-detail-content")
const detailSubtitle = document.getElementById("calendar-detail-subtitle")
const detailBackButton = document.getElementById("calendar-detail-back")
const legend = document.getElementById("calendar-legend")
if (!grid || !label || !prevBtn || !nextBtn) {
console.warn("Calendar elements not found; skipping calendar setup")
return
}
this.calendarContainer = document.querySelector(".officials-calendar")
this.calendarGridElement = grid
this.calendarLabelElement = label
this.calendarEventsContainer = eventsContainer
this.calendarLegendElement = legend
this.calendarHeaderElement = header
this.calendarDetailView = {
listContainer: eventsContainer,
detailSection,
detailContent,
detailSubtitle,
backButton: detailBackButton,
activeTrigger: null,
activeButton: null,
}
if (detailBackButton) {
detailBackButton.addEventListener("click", () =>
this.closeCalendarEventDetail(),
)
}
if (eventsContainer && !eventsContainer.innerHTML.trim()) {
eventsContainer.innerHTML = this.buildCalendarPlaceholder()
eventsContainer.setAttribute("aria-busy", "true")
}
const handlePrev = () => this.changeCalendarMonth(-1)
const handleNext = () => this.changeCalendarMonth(1)
prevBtn.addEventListener("click", handlePrev)
nextBtn.addEventListener("click", handleNext)
prevBtn.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") {
event.preventDefault()
handlePrev()
}
})
nextBtn.addEventListener("keydown", (event) => {
if (event.key === "ArrowRight") {
event.preventDefault()
handleNext()
}
})
this.renderCalendar()
this.setCalendarVisibility(true)
}
renderCalendar() {
const grid =
this.calendarGridElement || document.getElementById("calendar-grid")
const label =
this.calendarLabelElement ||
document.getElementById("calendar-month-label")
if (!grid || !label) return
if (!this.calendarViewDate) {
this.calendarViewDate = new Date()
}
const today = new Date()
today.setHours(0, 0, 0, 0)
// Calculate start of current week (MONDAY, not Sunday)
const currentWeekStart = new Date(today)
currentWeekStart.setDate(today.getDate() - 7) // Start from 7 days ago
const dayOfWeek = currentWeekStart.getDay()
// Convert Sunday (0) to 7, so Monday becomes 0
const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1
currentWeekStart.setDate(currentWeekStart.getDate() - daysFromMonday)
// Calculate previous week start (7 days before current week Monday)
const previousWeekStart = new Date(currentWeekStart)
previousWeekStart.setDate(currentWeekStart.getDate() - 7)
// Calculate next week start (7 days after current week Monday)
const nextWeekStart = new Date(currentWeekStart)
nextWeekStart.setDate(currentWeekStart.getDate() + 7)
// Display date range in label
const startDate = previousWeekStart
const endDate = new Date(nextWeekStart)
endDate.setDate(endDate.getDate() + 6) // End of next week (Sunday)