-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
587 lines (522 loc) · 33.5 KB
/
Copy pathindex.html
File metadata and controls
587 lines (522 loc) · 33.5 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="bb.svg" type="image/svg+xml">
<meta name="apple-mobile-web-app-title" content="Bluebikes Nearby">
<link rel="apple-touch-icon" sizes="180x180" href="bb.png">
<title>Bluebikes Nearby</title>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap" rel="stylesheet">
<!-- Tailwind CSS via CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* Define the Inter font family for Tailwind to use */
body {
font-family: Inter, -apple-system, "system-ui", "Segoe UI", Helvetica, Arial, sans-serif;
color: #333;
}
h2 {
color: #162F77;
}
.dropdown-scroll {
scrollbar-width: thin;
scrollbar-color: #cbd5e1 #f1f5f9;
}
.dropdown-scroll::-webkit-scrollbar {
width: 6px;
}
.dropdown-scroll::-webkit-scrollbar-track {
background: #f1f5f9;
border-radius: 3px;
}
.dropdown-scroll::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 3px;
}
.dropdown-scroll::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
/* Icon styling */
.dropdown-icon {
width: 1.25rem; /* 20px */
height: 1.25rem; /* 20px */
margin-right: 0.5rem; /* 8px */
}
.title-icon {
width: 2.25rem; /* 36px */
height: 2.25rem; /* 36px */
margin-right: 0.75rem; /* 12px */
}
/* --- FIX FOR IOS ZOOM --- */
#station-search {
font-size: 16px !important;
}
@media (max-width: 768px) {
#location-button {
font-size: 27px;
}
}
@media (max-width: 640px) {
#at {
display: none;
}
}
</style>
</head>
<body class="bg-gray-100 flex flex-col items-center min-h-screen p-4">
<div class="container w-full max-w-5xl bg-white rounded-xl shadow-lg p-6 sm:p-8 my-8">
<!-- Header Section -->
<header class="text-center pb-6 mb-6 border-b border-gray-200">
<div class="flex flex-col sm:flex-row justify-center items-center gap-2 sm:gap-4">
<img src="bb-logo.svg" alt="Bluebikes Logo" class="h-6 sm:h-8">
<div class="flex items-center gap-1 sm:gap-2">
<p id="at" class="text-2xl sm:text-[32px] font-medium">@</p>
<!-- Dropdown Menu for Locations -->
<div class="relative" id="location-menu">
<button id="location-button" class="text-2xl sm:text-[32px] font-semibold text-gray-800 flex items-center gap-1 sm:gap-2 p-2 rounded-lg hover:bg-gray-100 transition-colors">
<span id="location-name-display"></span>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-500 transition-transform dropdown-arrow" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</button>
<div style="margin-top:3px;" id="location-dropdown" class="hidden absolute z-10 mt-2 w-[90vw] max-w-xs left-1/2 -translate-x-1/2 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none max-h-80 sm:max-h-96 overflow-hidden" role="menu">
<!-- Search Input -->
<div class="p-3 border-b border-gray-200">
<div class="relative">
<input
type="text"
id="station-search"
placeholder="Search stations..."
class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
>
<svg class="absolute left-3 top-2.5 h-4 w-4 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
</div>
<!-- Dropdown Options Container -->
<div class="overflow-y-auto dropdown-scroll" style="max-height: 300px;">
<!-- Preset Locations Section -->
<div id="preset-locations-section">
<div class="px-3 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wide bg-gray-50">
Destinations
</div>
<div id="location-options">
<!-- Preset location options will be injected here by JavaScript -->
</div>
</div>
<!-- Search Results Section -->
<div id="search-results-section" class="hidden">
<!-- Search results will be injected here by JavaScript -->
</div>
<!-- No Results Message -->
<div id="no-results" class="hidden px-4 py-8 text-center text-gray-500 text-sm">
No stations or destinations found.
</div>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content for Station Cards -->
<main id="station-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<!-- Station cards will be injected here by JavaScript -->
</main>
<!-- Status Footer -->
<div class="status-footer mt-6 pt-6 border-t border-gray-200 flex justify-between items-center text-sm text-gray-600">
<span class="refresh-countdown italic text-gray-500" id="global-refresh-countdown"></span>
<span id="global-last-updated"><span class="font-semibold">Last updated</span> at <span id="time" class="font-medium">--</span></span>
</div>
</div>
<!-- External Logo Footer -->
<footer class="text-center py-4">
<a href="https://www.boston.gov/transportation/boston-bikes" target="_blank" rel="noopener noreferrer">
<!-- LOGO SIZE INCREASED HERE -->
<img src="https://assets.boston.gov/icons/dept_icons/boston_bikes_icon.svg" alt="Boston Bikes Logo" class="h-24 mx-auto">
</a>
</footer>
<script>
document.addEventListener('DOMContentLoaded', () => {
const ICONS = {
cityHall: `<svg viewBox="0 0 144 144" xmlns="http://www.w3.org/2000/svg"><path d="m51.96 83.7h22.67v36.4h-22.67z" fill="#fff" stroke="#0f1f2d" stroke-miterlimit="10" stroke-width="3"/><path d="m39.27 65.48h65.4v20.82h-65.4z" fill="#fff" stroke="#0f1f2d" stroke-miterlimit="10" stroke-width="3"/><path d="m27.76 64.11h13.76v56.01h-13.76z" fill="#fff" stroke="#0f1f2d" stroke-miterlimit="10" stroke-width="3"/><path d="m102.77 64.09h13.76v56.01h-13.76z" fill="#fff" stroke="#0f1f2d" stroke-miterlimit="10" stroke-width="3"/><path d="m13.06 23.87h117.87v20.82h-117.87z" fill="#fff" stroke="#0f1f2d" stroke-miterlimit="10" stroke-width="3"/><path d="m27.98 44.69h87.99v20.82h-87.99z" fill="#fff" stroke="#0f1f2d" stroke-miterlimit="10" stroke-width="3"/><g fill="#0f1f2d"><path d="m21.11 30.23h8.1v8.1h-8.1z"/><path d="m34.5 30.23h8.1v8.1h-8.1z"/><path d="m47.86 30.23h8.1v8.1h-8.1z"/><path d="m61.24 30.23h8.1v8.1h-8.1z"/><path d="m74.63 30.23h8.1v8.1h-8.1z"/><path d="m101.37 30.23h8.1v8.1h-8.1z"/><path d="m88.02 30.23h8.1v8.1h-8.1z"/><path d="m114.76 30.23h8.1v8.1h-8.1z"/><path d="m34.5 50.35h8.1v8.1h-8.1z"/><path d="m47.86 50.35h8.1v8.1h-8.1z"/><path d="m61.24 50.35h8.1v8.1h-8.1z"/><path d="m74.63 50.35h8.1v8.1h-8.1z"/><path d="m88.02 50.35h8.1v8.1h-8.1z"/><path d="m101.37 50.35h8.1v8.1h-8.1z"/><path d="m61.24 71.84h8.1v8.1h-8.1z"/><path d="m74.63 71.84h8.1v8.1h-8.1z"/><path d="m74.58 71.84h8.1v8.1h-8.1z"/><path d="m87.96 71.84h8.1v8.1h-8.1z"/><path d="m47.91 71.84h8.1v8.1h-8.1z"/></g><path d="m41.53 106.58h46.46v13.52h-46.46z" fill="#fff" stroke="#0f1f2d" stroke-miterlimit="10" stroke-width="3"/></svg>`,
building: '<img src="building.svg" alt="Building Icon">',
community: '<img src="community.svg" alt="Community Icon">',
library: '<img src="library.svg" alt="Library Icon">',
police: '<img src="police.svg" alt="Police Icon">',
pw: '<img src="pw.svg" alt="Public Works Icon">',
water: '<img src="water.svg" alt="Water Dept Icon">',
fire: '<img src="fire.svg" alt="Fire Dept Icon">',
stadium: '<img src="stadium.svg" alt="Stadium Icon">',
medical: '<img src="medical.svg" alt="Medical Icon">',
art: '<img src="art.svg" alt="Art Icon">',
t: '<img src="t.svg" alt="T Icon">',
park: '<img src="park.svg" alt="Park Icon">',
};
// --- DATA & STATE ---
const locations = [
{ name: "Boston City Hall", stationIds: ['B32008', 'D32009', 'B32032'], icon: 'cityHall' },
{ name: "1010 Massachusetts Ave.", stationIds: ['C32022'], icon: 'building' },
{ name: "BPS HQ / Bolling Building", stationIds: ['B32017', 'B32026'], icon: 'building' },
{ name: "BCYF/Tobin Community Center", stationIds: ['B32063', 'C32001'], icon: 'community' },
{ name: "Boston Public Library Central", stationIds: ['B32005', 'D32055', 'D32045', 'D32046', 'D32047'], icon: 'library'},
{ name: "BPD Headquarters", stationIds: ['B32002', 'B32064', 'B32059'], icon: 'police'},
{ name: "BHA Headquarters", stationIds: ['D32030', 'D32004', 'D32019'], icon: 'building'},
{ name: "Frontage Road", stationIds: ['C32061','C32035'], icon: 'pw'},
{ name: "12 Channel Street", stationIds: ['C32021','C32020', 'C32011'], icon: 'building'},
{ name: "MassDOT / 10 Park Plaza", stationIds: ['D32042','D32011','D32025','D32062'], icon: 'building'},
{ name: "Boston Water and Sewer", stationIds: ['C32005', 'C32068', 'C32072', 'B32026'], icon: 'water' },
{ name: "Oak Square", stationIds: ['D32076', 'D32031', 'D32077'], icon: 'community'},
{ name: "Audubon Circle", stationIds: ['A32008', 'K32007'], icon: 'community'},
{ name: "Maverick Square", stationIds: ['A32030', 'A32031'], icon: 't'},
{ name: "Roslindale Village", stationIds: ['C32046', 'C32047', 'C32059'], icon: 't'},
{ name: "Forest Hills", stationIds: ['E32010'], icon: 't'},
{ name: "South Station", stationIds: ['A32010','A32042','A32059'], icon: 't'},
{ name: "Ashmont / Peabody Square", stationIds: ['C32062'], icon: 't'},
{ name: "Coolidge Corner", stationIds: ['K32001', 'K32012', 'K32017', 'K32004'], icon: 't'},
{ name: "Boston Common", stationIds: ['B32068', 'B32056', 'D32014', 'D32024'], icon: 'park'},
{ name: "Franklin Park", stationIds: ['C32030', 'C32027', 'C32102', 'C32099'], icon: 'park'},
{ name: "Brighton Medical Center", stationIds: ['D32028', 'D32054'], icon: 'medical'},
{ name: "MGH", stationIds: ['D32016', 'D32050', 'D32000'], icon: 'medical'},
{ name: "Beth Israel", stationIds: ['A32004', 'A32056', 'B32003'], icon: 'medical'},
{ name: "BFD Headquarters", stationIds: ['C32068', 'C32022'], icon: 'fire' },
{ name: "Cambridge City Hall", stationIds: ['M32012', 'M32011'], icon: 'building' },
{ name: "Brookline Town Hall", stationIds:['K32003','K32005'], icon: 'building'},
{ name: "Somerville City Hall", stationIds:['S32001','S32048', 'S32046'], icon: 'building'},
{ name: "Chelsea City Hall", stationIds:['H32002','H320010'], icon: 'building'},
{ name: "Fenway Park", stationIds: ['B32058', 'B32020', 'B32034'], icon: 'stadium' },
{ name: "TD Garden", stationIds: ['A32046', 'A32021', 'A32025', 'A32053'], icon: 'stadium' },
{ name: "Museum of Fine Arts", stationIds: ['B32021', 'B32033', 'Z32997'], icon: 'art'},
{ name: "Institute of Contemporary Art", stationIds: ['A32000', 'B32007', 'C32034'], icon: 'art'},
{ name: "Isabella Stewart Gardner Museum", stationIds: ['B32021', 'B32033', 'B32006'], icon: 'art'}
];
let currentStationIds = [];
let allStations = []; // Will store all available stations for search
const stationDataCache = {};
const REFRESH_INTERVAL_SECONDS = 20;
let countdownInterval;
// --- DOM ELEMENTS ---
const stationContainer = document.getElementById('station-container');
const locationButton = document.getElementById('location-button');
const locationNameDisplay = document.getElementById('location-name-display');
const locationDropdown = document.getElementById('location-dropdown');
const locationOptionsContainer = document.getElementById('location-options');
const searchInput = document.getElementById('station-search');
const searchResultsSection = document.getElementById('search-results-section');
const presetLocationsSection = document.getElementById('preset-locations-section');
const noResultsMessage = document.getElementById('no-results');
const globalCountdownEl = document.getElementById('global-refresh-countdown');
const globalLastUpdatedEl = document.getElementById('time');
// --- FUNCTIONS ---
/**
* *** NEW ***
* Creates a URL-friendly slug from a string.
* e.g., "1010 Massachusetts Ave." becomes "1010-massachusetts-ave"
* @param {string} text - The string to convert.
* @returns {string} The slugified string.
*/
function createSlug(text) {
if (!text) return '';
return text
.toLowerCase()
.replace(/[.'’]/g, '') // Remove periods, apostrophes, etc.
.replace(/[^a-z0-9]+/g, '-') // Replace any non-alphanumeric sequence with a hyphen
.replace(/^-+|-+$/g, ''); // Trim leading/trailing hyphens
}
/**
* Renders the station placeholder cards into the main container.
*/
function renderStationCards(stationIds) {
stationContainer.innerHTML = ''; // Clear existing cards
// Add centering class for 1-2 tiles
if (stationIds.length <= 2) {
stationContainer.className = 'flex justify-center flex-wrap gap-6';
} else {
stationContainer.className = 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6';
}
stationIds.forEach(id => {
const stationHTML = `
<div class="station bg-gray-50 border border-gray-200 rounded-lg p-5 flex flex-col justify-between ${stationIds.length <= 2 ? 'w-80' : ''}" id="${id}">
<h2 class="text-2xl font-semibold text-center min-h-[3.5rem] flex items-center justify-center">Loading...</h2>
<div class="stats grid grid-cols-3 gap-4 text-center my-6">
<div class="stat">
<span class="count block text-5xl font-bold" id="classic-${id}">--</span>
<span class="label text-lg text-gray-600">Classic</span>
</div>
<div class="stat">
<span class="count block text-5xl font-bold" id="ebikes-${id}">--</span>
<span class="label text-lg text-gray-600 flex items-center justify-center gap-1">
<svg class="w-5 h-5 text-yellow-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M11.3 1.046A1 1 0 0112 2v5h4a1 1 0 01.82 1.573l-7 10A1 1 0 018 18v-5H4a1 1 0 01-.82-1.573l7-10a1 1 0 011.12-.38z" clip-rule="evenodd" /></svg>
Ebikes
</span>
</div>
<div class="stat">
<span class="count block text-5xl font-bold" id="docks-${id}">--</span>
<span class="label text-lg text-gray-600">Docks</span>
</div>
</div>
</div>`;
stationContainer.insertAdjacentHTML('beforeend', stationHTML);
});
}
/**
* Populates the preset location dropdown menu from the locations data.
*/
function populateDropdown() {
locationOptionsContainer.innerHTML = '';
locations.forEach((location, index) => {
const iconHTML = location.icon && ICONS[location.icon]
? ICONS[location.icon].replace('<svg', '<svg class="dropdown-icon"').replace('<img', '<img class="dropdown-icon"')
: '';
const optionHTML = `
<a href="#" class="text-gray-700 block px-4 py-2 text-sm hover:bg-gray-100 transition-colors flex items-center" role="menuitem" tabindex="-1" data-type="preset" data-index="${index}">
${iconHTML}
<span>${location.name}</span>
</a>`;
locationOptionsContainer.insertAdjacentHTML('beforeend', optionHTML);
});
}
/**
* Searches through destinations and stations, then displays the results.
* @param {string} query - The search query.
*/
function searchStations(query) {
if (!query.trim()) {
presetLocationsSection.classList.remove('hidden');
searchResultsSection.classList.add('hidden');
noResultsMessage.classList.add('hidden');
return;
}
const normalizedQuery = query.toLowerCase().trim();
// Filter both destinations and individual stations
const matchingLocations = locations.map((location, index) => ({...location, originalIndex: index}))
.filter(location => location.name.toLowerCase().includes(normalizedQuery));
const matchingStations = allStations.filter(station =>
station.name.toLowerCase().includes(normalizedQuery) ||
station.short_name.toLowerCase().includes(normalizedQuery)
).slice(0, 10);
// Clear previous results and hide everything initially
searchResultsSection.innerHTML = '';
presetLocationsSection.classList.add('hidden');
if (matchingLocations.length > 0 || matchingStations.length > 0) {
let resultsHTML = '';
// Display matching destinations
if (matchingLocations.length > 0) {
resultsHTML += `<div class="px-3 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wide bg-gray-50">Matching Destinations</div>`;
matchingLocations.forEach(location => {
const iconHTML = location.icon && ICONS[location.icon]
? ICONS[location.icon].replace('<svg', '<svg class="dropdown-icon"').replace('<img', '<img class="dropdown-icon"')
: '';
resultsHTML += `
<a href="#" class="text-gray-700 block px-4 py-2 text-sm hover:bg-gray-100 transition-colors flex items-center" role="menuitem" tabindex="-1" data-type="preset" data-index="${location.originalIndex}">
${iconHTML}
<span>${location.name}</span>
</a>`;
});
}
// Display matching stations
if (matchingStations.length > 0) {
resultsHTML += `<div class="px-3 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wide bg-gray-50 ${matchingLocations.length > 0 ? 'mt-2' : ''}">Station Results</div>`;
matchingStations.forEach(station => {
resultsHTML += `
<a href="#" class="text-gray-700 block px-4 py-2 text-sm hover:bg-gray-100 transition-colors" role="menuitem" tabindex="-1" data-type="search" data-station-id="${station.short_name}" data-station-name="${station.name}">
<div class="font-medium">${station.name}</div>
<div class="text-xs text-gray-500">ID: ${station.short_name}</div>
</a>`;
});
}
searchResultsSection.innerHTML = resultsHTML;
searchResultsSection.classList.remove('hidden');
noResultsMessage.classList.add('hidden');
} else {
// No results found
searchResultsSection.classList.add('hidden');
noResultsMessage.classList.remove('hidden');
}
}
/**
* Sets the current location, updates the URL hash, and triggers a re-render.
*/
function setLocation(index = null, customStationId = null, customStationName = null) {
let displayName = '';
let iconHTML = '';
if (index !== null) {
const newLocation = locations[index];
currentStationIds = newLocation.stationIds;
displayName = newLocation.name;
// *** MODIFIED ***
// Create a URL-friendly slug and update the hash
const hashSlug = createSlug(newLocation.name);
if (window.location.hash !== `#${hashSlug}`) {
history.replaceState(null, '', `#${hashSlug}`);
}
if (newLocation.icon && ICONS[newLocation.icon]) {
iconHTML = ICONS[newLocation.icon].replace('<svg', '<svg class="title-icon"').replace('<img', '<img class="title-icon"');
}
} else if (customStationId && customStationName) {
currentStationIds = [customStationId];
displayName = customStationName;
// Clear the hash if a custom station is selected
history.replaceState(null, '', window.location.pathname + window.location.search);
}
if (iconHTML) {
locationNameDisplay.innerHTML = `${iconHTML}<span>${displayName}</span>`;
locationNameDisplay.classList.add('flex', 'items-center');
} else {
locationNameDisplay.innerHTML = `<span>${displayName}</span>`;
locationNameDisplay.classList.remove('flex', 'items-center');
}
renderStationCards(currentStationIds);
fetchAndDisplayData();
startCountdown();
// Reset dropdown and search input
searchInput.value = '';
searchStations(''); // Resets the search view to the default preset list
locationDropdown.classList.add('hidden');
locationButton.querySelector('svg').classList.remove('rotate-180');
}
/**
* Starts or restarts the refresh countdown timer.
*/
function startCountdown() {
if (countdownInterval) clearInterval(countdownInterval);
let secondsRemaining = REFRESH_INTERVAL_SECONDS;
const updateTimer = () => {
if (secondsRemaining > 0) {
const displaySeconds = Math.ceil(secondsRemaining / 5) * 5;
globalCountdownEl.textContent = `Refreshing in ${displaySeconds}s...`;
secondsRemaining--;
} else {
globalCountdownEl.textContent = `Refreshing...`;
clearInterval(countdownInterval);
}
};
updateTimer();
countdownInterval = setInterval(updateTimer, 1000);
}
/**
* Loads all stations for search functionality
*/
async function loadAllStations() {
try {
const gbfsResponse = await fetch('https://gbfs.bluebikes.com/gbfs/gbfs.json');
if (!gbfsResponse.ok) throw new Error(`GBFS discovery file not found.`);
const gbfsData = await gbfsResponse.json();
const stationInfoURL = gbfsData.data.en.feeds.find(feed => feed.name === 'station_information').url;
const infoResponse = await fetch(stationInfoURL);
if (!infoResponse.ok) throw new Error(`Station info not found.`);
const infoData = await infoResponse.json();
allStations = infoData.data.stations.filter(station => station.short_name);
} catch (error) {
console.error('Error loading stations for search:', error);
}
}
/**
* Fetches station information and status, then updates the UI.
*/
async function fetchAndDisplayData() {
try {
const gbfsResponse = await fetch('https://gbfs.bluebikes.com/gbfs/gbfs.json');
if (!gbfsResponse.ok) throw new Error(`GBFS discovery file not found.`);
const gbfsData = await gbfsResponse.json();
const stationInfoURL = gbfsData.data.en.feeds.find(feed => feed.name === 'station_information').url;
const statusURL = gbfsData.data.en.feeds.find(feed => feed.name === 'station_status').url;
const infoResponse = await fetch(stationInfoURL);
if (!infoResponse.ok) throw new Error(`Station info not found.`);
const infoData = await infoResponse.json();
Object.keys(stationDataCache).forEach(key => delete stationDataCache[key]);
infoData.data.stations.forEach(station => {
if (currentStationIds.includes(station.short_name)) {
stationDataCache[station.short_name] = { id: station.station_id, name: station.name };
}
});
const statusResponse = await fetch(statusURL);
if (!statusResponse.ok) throw new Error(`Station status not found.`);
const statusData = await statusResponse.json();
const lastUpdatedTime = new Date(statusData.last_updated * 1000).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
globalLastUpdatedEl.textContent = lastUpdatedTime;
statusData.data.stations.forEach(station => {
const stationInfo = Object.values(stationDataCache).find(s => s.id === station.station_id);
const shortName = Object.keys(stationDataCache).find(key => stationDataCache[key].id === station.station_id);
if (stationInfo && currentStationIds.includes(shortName)) {
const ebikes = station.num_ebikes_available || 0;
const classicBikes = (station.num_bikes_available || 0) - ebikes;
const docks = station.num_docks_available || 0;
const stationElement = document.getElementById(shortName);
if (stationElement) {
stationElement.querySelector('h2').textContent = stationInfo.name;
stationElement.querySelector(`#classic-${shortName}`).textContent = classicBikes;
stationElement.querySelector(`#ebikes-${shortName}`).textContent = ebikes;
stationElement.querySelector(`#docks-${shortName}`).textContent = docks;
}
}
});
} catch (error) {
console.error('Error fetching Bluebikes data:', error);
currentStationIds.forEach(id => {
const el = document.getElementById(id);
if (el) el.querySelector('h2').textContent = `Could not load data`;
});
}
}
/**
* Reads the URL hash on load and sets the initial location.
*/
function initializeApp() {
const hash = window.location.hash.substring(1);
let startingIndex = 0; // Default to the first location
if (hash) {
try {
// *** MODIFIED ***
// Find the location by comparing its generated slug to the hash
const locationIndex = locations.findIndex(location => createSlug(location.name) === hash);
if (locationIndex !== -1) {
startingIndex = locationIndex;
}
} catch (e) {
console.error("Error processing URL hash:", e);
}
}
setLocation(startingIndex);
}
// --- INITIALIZATION & EVENT LISTENERS ---
populateDropdown();
loadAllStations();
locationButton.addEventListener('click', () => {
locationDropdown.classList.toggle('hidden');
locationButton.querySelector('.dropdown-arrow').classList.toggle('rotate-180');
if (!locationDropdown.classList.contains('hidden')) {
searchInput.focus();
}
});
searchInput.addEventListener('input', (e) => searchStations(e.target.value));
searchInput.addEventListener('click', (e) => e.stopPropagation());
locationDropdown.addEventListener('click', (e) => {
const target = e.target.closest('a[data-type]');
if (target) {
e.preventDefault();
if (target.getAttribute('data-type') === 'preset') {
setLocation(parseInt(target.getAttribute('data-index'), 10));
} else if (target.getAttribute('data-type') === 'search') {
setLocation(null, target.getAttribute('data-station-id'), target.getAttribute('data-station-name'));
}
}
});
document.addEventListener('click', (e) => {
if (!document.getElementById('location-menu').contains(e.target)) {
locationDropdown.classList.add('hidden');
locationButton.querySelector('.dropdown-arrow').classList.remove('rotate-180');
}
});
initializeApp();
setInterval(() => {
fetchAndDisplayData();
startCountdown();
}, REFRESH_INTERVAL_SECONDS * 1000);
});
</script>
</body>
</html>