-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
697 lines (605 loc) · 25.7 KB
/
Copy pathapp.js
File metadata and controls
697 lines (605 loc) · 25.7 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
const DEFAULT_LOCATION = { lat: 33.9425, lng: -117.2297, label: "Moreno Valley, California" };
const SEARCH_RADIUS_METERS = 12000;
const NOMINATIM_ENDPOINT = "https://nominatim.openstreetmap.org/search";
const OVERPASS_ENDPOINT = "https://overpass-api.de/api/interpreter";
const MODE_CONTENT = {
plan: {
eyebrow: "Pet-care preparedness for the road",
title: "Make a pet-care plan before you travel.",
description:
"Search a campground, destination, city, or ZIP code. Review nearby veterinary care now so you know where to call and where to go before your trip begins.",
inputLabel: "Where are you going?",
placeholder: "Campground, city, state, or ZIP code",
searchButton: "Explore destination",
locationButton: "Use current location instead",
guidance: "Start with where you will stay. PawPath will show care options near that destination.",
resultsEyebrow: "Trip planning",
emptySearchMessage: "Enter a campground, destination, city, state, or ZIP code to search.",
announcement: "Plan a Trip selected. Search a destination to prepare veterinary care options before you leave.",
},
now: {
eyebrow: "When your pet needs care away from home",
title: "Find nearby pet care now.",
description:
"Use your current location to quickly find veterinary and likely emergency care. Review the options, call ahead, and open directions when you are ready to go.",
inputLabel: "Where should we search?",
placeholder: "City, state, or ZIP code",
searchButton: "Search this area",
locationButton: "Find care near me",
guidance: "For the fastest nearby search, use your current location. Location access stays in your browser.",
resultsEyebrow: "Nearby care",
emptySearchMessage: "Enter a city, state, or ZIP code, or use your current location.",
announcement: "Find Care Now selected. Use your current location or search an area for nearby veterinary care.",
},
};
const CARE_TYPE_LABELS = {
emergency: "Emergency care",
urgent: "Urgent care",
routine: "Routine veterinary care",
unknown: "Care type unknown",
};
const CONFIDENCE_CONTENT = {
"demo-verified": {
label: "Demo verified",
explanation: "This demonstration record was manually reviewed on the date shown in its source notes.",
},
"source-listed": {
label: "Source listed",
explanation: "This information is shown as supplied by the listed data source. Contact the facility to confirm current services and availability.",
},
"likely-emergency": {
label: "Likely emergency",
explanation: "Emergency or urgent capability is inferred from the facility name or listing details and has not been independently verified by PawPath.",
},
"needs-confirmation": {
label: "Needs confirmation",
explanation: "Important listing details are missing or uncertain. Call the facility before relying on it for your trip plan.",
},
};
let map;
let markerLayer;
let clinics = [];
let activeFilter = "all";
let activeMode = "plan";
let currentSearchLabel = DEFAULT_LOCATION.label;
let selectedClinicId = null;
let lastDetailTrigger = null;
const markersById = new Map();
const elements = {};
document.addEventListener("DOMContentLoaded", initApp);
function initApp() {
cacheElements();
initializeMap();
bindEvents();
setMode("plan");
elements.currentYear.textContent = new Date().getFullYear();
searchNearby(DEFAULT_LOCATION, DEFAULT_LOCATION.label);
}
function cacheElements() {
elements.heroPanel = document.getElementById("hero-panel");
elements.modeButtons = [...document.querySelectorAll(".mode-option[data-mode]")];
elements.modeStatus = document.getElementById("mode-status");
elements.heroEyebrow = document.getElementById("hero-eyebrow");
elements.pageTitle = document.getElementById("page-title");
elements.heroDescription = document.getElementById("hero-description");
elements.locationLabel = document.getElementById("location-label");
elements.searchForm = document.getElementById("search-form");
elements.locationInput = document.getElementById("location-input");
elements.searchButton = document.getElementById("search-btn");
elements.searchButtonLabel = document.getElementById("search-button-label");
elements.locationButton = document.getElementById("loc-btn");
elements.locationButtonLabel = document.getElementById("location-button-label");
elements.modeGuidance = document.getElementById("mode-guidance");
elements.formMessage = document.getElementById("form-message");
elements.clinicList = document.getElementById("clinic-list");
elements.resultCount = document.getElementById("result-count");
elements.resultsEyebrow = document.getElementById("results-eyebrow");
elements.resultsTitle = document.getElementById("results-title");
elements.emptyTemplate = document.getElementById("empty-state-template");
elements.filterButtons = [...document.querySelectorAll("[data-filter]")];
elements.currentYear = document.getElementById("current-year");
elements.facilityDetail = document.getElementById("facility-detail");
elements.facilityDetailClose = document.getElementById("facility-detail-close");
elements.detailTitle = document.getElementById("facility-detail-title");
elements.detailCareType = document.getElementById("detail-care-type");
elements.detailConfidence = document.getElementById("detail-confidence");
elements.detailConfidenceExplanation = document.getElementById("detail-confidence-explanation");
elements.detailAddress = document.getElementById("detail-address");
elements.detailDistance = document.getElementById("detail-distance");
elements.detailPhone = document.getElementById("detail-phone");
elements.detailHours = document.getElementById("detail-hours");
elements.detailWebsiteValue = document.getElementById("detail-website-value");
elements.detailSource = document.getElementById("detail-source");
elements.detailSourceNotes = document.getElementById("detail-source-notes");
elements.detailCall = document.getElementById("detail-call");
elements.detailDirections = document.getElementById("detail-directions");
elements.detailWebsite = document.getElementById("detail-website");
}
function initializeMap() {
map = L.map("map", {
center: [DEFAULT_LOCATION.lat, DEFAULT_LOCATION.lng],
zoom: 11,
zoomControl: false,
});
L.control.zoom({ position: "topright" }).addTo(map);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);
markerLayer = L.layerGroup().addTo(map);
}
function bindEvents() {
elements.searchForm.addEventListener("submit", handleSearchSubmit);
elements.locationButton.addEventListener("click", handleGeolocation);
elements.facilityDetailClose.addEventListener("click", closeFacilityDetail);
elements.facilityDetail.addEventListener("click", (event) => {
if (event.target === elements.facilityDetail) closeFacilityDetail();
});
elements.facilityDetail.addEventListener("close", restoreDetailFocus);
elements.modeButtons.forEach((button, index) => {
button.addEventListener("click", () => setMode(button.dataset.mode, true));
button.addEventListener("keydown", (event) => handleModeKeydown(event, index));
});
elements.filterButtons.forEach((button) => {
button.addEventListener("click", () => {
activeFilter = button.dataset.filter;
elements.filterButtons.forEach((item) => {
const isActive = item === button;
item.classList.toggle("is-active", isActive);
item.setAttribute("aria-pressed", String(isActive));
});
renderClinics();
});
});
}
function handleModeKeydown(event, currentIndex) {
if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) return;
event.preventDefault();
let nextIndex = currentIndex;
if (event.key === "Home") nextIndex = 0;
if (event.key === "End") nextIndex = elements.modeButtons.length - 1;
if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
nextIndex = (currentIndex - 1 + elements.modeButtons.length) % elements.modeButtons.length;
}
if (event.key === "ArrowRight" || event.key === "ArrowDown") {
nextIndex = (currentIndex + 1) % elements.modeButtons.length;
}
const nextButton = elements.modeButtons[nextIndex];
nextButton.focus();
setMode(nextButton.dataset.mode, true);
}
function setMode(mode, announce = false) {
if (!MODE_CONTENT[mode]) return;
activeMode = mode;
const content = MODE_CONTENT[mode];
elements.heroPanel.dataset.mode = mode;
elements.modeButtons.forEach((button) => {
const isActive = button.dataset.mode === mode;
button.classList.toggle("is-active", isActive);
button.setAttribute("aria-pressed", String(isActive));
});
elements.heroEyebrow.textContent = content.eyebrow;
elements.pageTitle.textContent = content.title;
elements.heroDescription.textContent = content.description;
elements.locationLabel.textContent = content.inputLabel;
elements.locationInput.placeholder = content.placeholder;
elements.searchButtonLabel.textContent = content.searchButton;
elements.locationButtonLabel.textContent = content.locationButton;
elements.modeGuidance.textContent = content.guidance;
elements.resultsEyebrow.textContent = content.resultsEyebrow;
updateResultsHeading();
setMessage("");
if (announce) {
elements.modeStatus.textContent = content.announcement;
}
}
async function handleSearchSubmit(event) {
event.preventDefault();
const query = elements.locationInput.value.trim();
if (!query) {
setMessage(MODE_CONTENT[activeMode].emptySearchMessage, true);
elements.locationInput.focus();
return;
}
setLoadingState(`Finding ${query}`);
try {
const location = await geocodeLocation(query);
await searchNearby(location, location.label || query);
} catch (error) {
console.error("Location search failed:", error);
showSearchError(error.message || "We could not find that location. Try a nearby city or ZIP code.");
}
}
function handleGeolocation() {
if (!navigator.geolocation) {
setMessage("This browser does not support location access.", true);
return;
}
setLoadingState("Finding your location");
navigator.geolocation.getCurrentPosition(
async ({ coords }) => {
try {
await searchNearby(
{ lat: coords.latitude, lng: coords.longitude },
"your current location"
);
} catch (error) {
console.error("Nearby search failed:", error);
showSearchError("We found your location but could not load nearby clinics. Please try again.");
}
},
(error) => {
const message = error.code === error.PERMISSION_DENIED
? "Location access was denied. Search by city or ZIP code instead."
: "Your location is unavailable right now. Search by city or ZIP code instead.";
showSearchError(message);
},
{ enableHighAccuracy: true, timeout: 10000, maximumAge: 300000 }
);
}
async function geocodeLocation(query) {
const url = new URL(NOMINATIM_ENDPOINT);
url.searchParams.set("format", "jsonv2");
url.searchParams.set("countrycodes", "us");
url.searchParams.set("limit", "1");
url.searchParams.set("q", query);
const response = await fetch(url, {
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error("The location service is temporarily unavailable.");
}
const [result] = await response.json();
if (!result) {
throw new Error("We could not find that location. Try including the state or using a ZIP code.");
}
return {
lat: Number(result.lat),
lng: Number(result.lon),
label: result.display_name.split(",").slice(0, 3).join(","),
};
}
async function searchNearby(center, label) {
setLoadingState(`Finding veterinary care near ${label}`);
map.setView([center.lat, center.lng], 12);
try {
clinics = await fetchVeterinaryClinics(center);
currentSearchLabel = label || "this area";
selectedClinicId = null;
activeFilter = "all";
resetFilters();
updateResultsHeading();
renderClinics();
setMessage(
activeMode === "plan"
? `Showing care options near ${label}. Review these choices before your trip and call ahead to confirm services.`
: `Showing veterinary care near ${label}. Call ahead before you travel.`
);
} catch (error) {
console.error("Clinic lookup failed:", error);
showSearchError("Clinic data is temporarily unavailable. Please try again in a moment.");
}
}
function updateResultsHeading() {
if (!elements.resultsTitle) return;
const label = shortenLabel(currentSearchLabel);
elements.resultsTitle.textContent = activeMode === "plan"
? `Care options near ${label}`
: `Care near ${label}`;
}
async function fetchVeterinaryClinics(center) {
const query = `
[out:json][timeout:25];
(
node["amenity"="veterinary"](around:${SEARCH_RADIUS_METERS},${center.lat},${center.lng});
way["amenity"="veterinary"](around:${SEARCH_RADIUS_METERS},${center.lat},${center.lng});
relation["amenity"="veterinary"](around:${SEARCH_RADIUS_METERS},${center.lat},${center.lng});
);
out center tags;
`;
const response = await fetch(OVERPASS_ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
body: new URLSearchParams({ data: query }),
});
if (!response.ok) {
throw new Error(`Overpass request failed with status ${response.status}`);
}
const data = await response.json();
return data.elements
.map((item) => normalizeClinic(item, center))
.filter(Boolean)
.sort((a, b) => a.distanceMiles - b.distanceMiles);
}
function normalizeClinic(item, searchCenter) {
const lat = item.lat ?? item.center?.lat;
const lng = item.lon ?? item.center?.lon;
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
const tags = item.tags || {};
const name = tags.name || tags.operator || "Veterinary clinic";
const address = formatAddress(tags);
const phone = tags.phone || tags["contact:phone"] || "";
const website = normalizeWebsite(tags.website || tags["contact:website"] || "");
const hours = tags.opening_hours || "";
const careType = classifyCareType(tags, name);
const confidence = classifyConfidence(tags, name, careType, phone, address);
const emergency = careType === "emergency" || careType === "urgent";
const source = "OpenStreetMap";
const sourceUrl = `https://www.openstreetmap.org/${item.type}/${item.id}`;
const sourceNotes = buildSourceNotes(confidence, careType);
return {
id: `${item.type}-${item.id}`,
name,
address,
phone,
website,
hours,
careType,
confidence,
emergency,
source,
sourceUrl,
sourceNotes,
lat,
lng,
distanceMiles: haversineMiles(searchCenter.lat, searchCenter.lng, lat, lng),
};
}
function formatAddress(tags) {
const street = [tags["addr:housenumber"], tags["addr:street"]].filter(Boolean).join(" ");
const locality = [tags["addr:city"], tags["addr:state"], tags["addr:postcode"]].filter(Boolean).join(", ");
return [street, locality].filter(Boolean).join(" • ") || "Address not listed in OpenStreetMap";
}
function normalizeWebsite(value) {
if (!value) return "";
return /^https?:\/\//i.test(value) ? value : `https://${value}`;
}
function classifyCareType(tags, name) {
const normalizedName = name.toLowerCase();
const emergencyTag = String(tags.emergency || "").toLowerCase();
const speciality = String(tags["healthcare:speciality"] || "").toLowerCase();
if (emergencyTag === "yes" || speciality.includes("emergency")) return "emergency";
if (/urgent/.test(normalizedName)) return "urgent";
if (/emergency|24 hour|24-hour|24\/7/.test(normalizedName)) return "emergency";
if (tags.amenity === "veterinary") return "routine";
return "unknown";
}
function classifyConfidence(tags, name, careType, phone, address) {
const normalizedName = name.toLowerCase();
const emergencyTag = String(tags.emergency || "").toLowerCase();
const speciality = String(tags["healthcare:speciality"] || "").toLowerCase();
const hasExplicitEmergencySignal = emergencyTag === "yes" || speciality.includes("emergency");
const hasInferredEmergencySignal = /emergency|urgent|24 hour|24-hour|24\/7/.test(normalizedName);
const missingImportantDetails = !phone || address.startsWith("Address not listed");
if ((careType === "emergency" || careType === "urgent") && !hasExplicitEmergencySignal && hasInferredEmergencySignal) {
return "likely-emergency";
}
if (missingImportantDetails) return "needs-confirmation";
return "source-listed";
}
function buildSourceNotes(confidence, careType) {
if (confidence === "likely-emergency") {
return `The ${CARE_TYPE_LABELS[careType].toLowerCase()} classification is inferred from the listing name or source details. Confirm emergency capability, hours, and availability by phone.`;
}
if (confidence === "needs-confirmation") {
return "This OpenStreetMap listing is missing important contact or address details. Use the source link and call ahead before adding it to a care plan.";
}
return "Facility information is displayed from OpenStreetMap. PawPath has not independently verified current hours, availability, or treatment capabilities.";
}
function renderClinics() {
markerLayer.clearLayers();
markersById.clear();
elements.clinicList.innerHTML = "";
const visibleClinics = clinics.filter((clinic) => {
if (activeFilter === "emergency") return clinic.emergency;
if (activeFilter === "routine") return !clinic.emergency;
return true;
});
elements.resultCount.textContent = `${visibleClinics.length} ${visibleClinics.length === 1 ? "result" : "results"}`;
if (!visibleClinics.length) {
elements.clinicList.appendChild(elements.emptyTemplate.content.cloneNode(true));
return;
}
const bounds = [];
visibleClinics.forEach((clinic) => {
const marker = createMarker(clinic).addTo(markerLayer);
markersById.set(clinic.id, marker);
bounds.push([clinic.lat, clinic.lng]);
elements.clinicList.appendChild(createClinicCard(clinic));
});
if (bounds.length === 1) {
map.setView(bounds[0], 14);
} else {
map.fitBounds(bounds, { padding: [45, 45], maxZoom: 14 });
}
}
function createMarker(clinic) {
const icon = L.divIcon({
className: "",
html: `<div class="custom-marker${clinic.emergency ? " is-emergency" : ""}"><span aria-hidden="true">✚</span></div>`,
iconSize: [34, 34],
iconAnchor: [17, 34],
popupAnchor: [0, -32],
});
const marker = L.marker([clinic.lat, clinic.lng], {
icon,
title: clinic.name,
keyboard: true,
});
marker.bindPopup(`
<strong class="popup-title">${escapeHtml(clinic.name)}</strong>
<span>${escapeHtml(clinic.address)}</span>
`);
marker.on("click", () => selectClinic(clinic.id, false, true, document.activeElement));
return marker;
}
function createClinicCard(clinic) {
const card = document.createElement("article");
card.className = "clinic-card";
card.tabIndex = 0;
card.dataset.clinicId = clinic.id;
card.setAttribute("aria-label", `View details for ${clinic.name}`);
const directionsUrl = `https://www.google.com/maps/dir/?api=1&destination=${clinic.lat},${clinic.lng}`;
card.innerHTML = `
<div class="clinic-card-header">
<div>
<h3>${escapeHtml(clinic.name)}</h3>
<p>${escapeHtml(clinic.address)}</p>
</div>
<span class="care-badge${clinic.emergency ? " is-emergency" : ""}">
${escapeHtml(CARE_TYPE_LABELS[clinic.careType])}
</span>
</div>
<div class="card-meta">
<span>${clinic.distanceMiles.toFixed(1)} mi away</span>
${clinic.phone ? `<span>☎ ${escapeHtml(clinic.phone)}</span>` : ""}
${clinic.website ? `<a href="${escapeAttribute(clinic.website)}" target="_blank" rel="noopener noreferrer">Website</a>` : ""}
</div>
<div class="card-actions">
<span>${escapeHtml(CONFIDENCE_CONTENT[clinic.confidence].label)} · View details</span>
<a class="directions-link" href="${directionsUrl}" target="_blank" rel="noopener noreferrer">Directions ↗</a>
</div>
`;
card.addEventListener("click", (event) => {
if (event.target.closest("a")) return;
selectClinic(clinic.id, true, true, card);
});
card.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
selectClinic(clinic.id, true, true, card);
}
});
return card;
}
function selectClinic(id, focusMap, openDetail = true, triggerElement = null) {
selectedClinicId = id;
document.querySelectorAll(".clinic-card").forEach((card) => {
card.classList.toggle("is-selected", card.dataset.clinicId === id);
});
const clinic = clinics.find((item) => item.id === id);
const marker = markersById.get(id);
if (!clinic || !marker) return;
if (focusMap) {
map.flyTo([clinic.lat, clinic.lng], Math.max(map.getZoom(), 14), { duration: 0.6 });
}
marker.openPopup();
const card = document.querySelector(`[data-clinic-id="${CSS.escape(id)}"]`);
card?.scrollIntoView({ behavior: "smooth", block: "nearest" });
if (openDetail) {
openFacilityDetail(clinic, triggerElement || card || document.activeElement);
}
}
function openFacilityDetail(clinic, triggerElement) {
const confidenceContent = CONFIDENCE_CONTENT[clinic.confidence] || CONFIDENCE_CONTENT["needs-confirmation"];
lastDetailTrigger = triggerElement instanceof HTMLElement ? triggerElement : null;
elements.detailTitle.textContent = clinic.name;
elements.detailCareType.textContent = CARE_TYPE_LABELS[clinic.careType] || CARE_TYPE_LABELS.unknown;
elements.detailCareType.dataset.careType = clinic.careType;
elements.detailConfidence.textContent = confidenceContent.label;
elements.detailConfidence.dataset.confidence = clinic.confidence;
elements.detailConfidenceExplanation.textContent = confidenceContent.explanation;
elements.detailAddress.textContent = clinic.address || "Not listed";
elements.detailDistance.textContent = Number.isFinite(clinic.distanceMiles)
? `${clinic.distanceMiles.toFixed(1)} miles from the search location`
: "Not available";
elements.detailPhone.textContent = clinic.phone || "Not listed";
elements.detailHours.textContent = clinic.hours || "Not listed — call to confirm";
elements.detailWebsiteValue.textContent = clinic.website ? getDisplayHostname(clinic.website) : "Not listed";
elements.detailSource.innerHTML = clinic.sourceUrl
? `<a href="${escapeAttribute(clinic.sourceUrl)}" target="_blank" rel="noopener noreferrer">${escapeHtml(clinic.source)} listing ↗</a>`
: escapeHtml(clinic.source || "Source not listed");
elements.detailSourceNotes.textContent = clinic.sourceNotes;
const directionsUrl = `https://www.google.com/maps/dir/?api=1&destination=${clinic.lat},${clinic.lng}`;
elements.detailDirections.href = directionsUrl;
configureOptionalAction(elements.detailCall, clinic.phone ? `tel:${normalizePhoneHref(clinic.phone)}` : "", "Call facility");
configureOptionalAction(elements.detailWebsite, clinic.website, "Website ↗");
if (!elements.facilityDetail.open) {
elements.facilityDetail.showModal();
}
requestAnimationFrame(() => elements.facilityDetailClose.focus());
}
function configureOptionalAction(element, href, label) {
element.textContent = href ? label : `${label.replace(" ↗", "")} unavailable`;
element.classList.toggle("is-disabled", !href);
element.setAttribute("aria-disabled", String(!href));
if (href) {
element.href = href;
element.removeAttribute("tabindex");
} else {
element.removeAttribute("href");
element.setAttribute("tabindex", "-1");
}
}
function closeFacilityDetail() {
if (elements.facilityDetail.open) elements.facilityDetail.close();
}
function restoreDetailFocus() {
if (lastDetailTrigger?.isConnected) lastDetailTrigger.focus();
lastDetailTrigger = null;
}
function normalizePhoneHref(phone) {
return phone.replace(/[^+\d]/g, "");
}
function getDisplayHostname(website) {
try {
return new URL(website).hostname.replace(/^www\./, "");
} catch {
return website;
}
}
function resetFilters() {
elements.filterButtons.forEach((button) => {
const isActive = button.dataset.filter === "all";
button.classList.toggle("is-active", isActive);
button.setAttribute("aria-pressed", String(isActive));
});
}
function setLoadingState(message) {
elements.clinicList.innerHTML = `
<div class="loading-state">
<p><strong>${escapeHtml(message)}</strong><span class="loading-dots"></span></p>
</div>
`;
elements.resultCount.textContent = "Searching…";
setMessage(message);
}
function showSearchError(message) {
elements.clinicList.innerHTML = `
<div class="empty-state">
<span aria-hidden="true">⚠</span>
<h3>We could not complete the search</h3>
<p>${escapeHtml(message)}</p>
</div>
`;
elements.resultCount.textContent = "Unavailable";
setMessage(message, true);
}
function setMessage(message, isError = false) {
elements.formMessage.textContent = message;
elements.formMessage.classList.toggle("is-error", isError);
}
function shortenLabel(label) {
return label.split(",").slice(0, 2).join(",").trim();
}
function haversineMiles(lat1, lon1, lat2, lon2) {
const toRadians = (degrees) => (degrees * Math.PI) / 180;
const earthRadiusMiles = 3958.8;
const deltaLat = toRadians(lat2 - lat1);
const deltaLon = toRadians(lon2 - lon1);
const a =
Math.sin(deltaLat / 2) ** 2 +
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) * Math.sin(deltaLon / 2) ** 2;
return earthRadiusMiles * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
function escapeHtml(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function escapeAttribute(value) {
return escapeHtml(value).replaceAll("`", "`");
}