59 lines
2.1 KiB
JavaScript
59 lines
2.1 KiB
JavaScript
document.addEventListener('DOMContentLoaded', () => {
|
|
const searchInput = document.getElementById('search-input');
|
|
const searchForm = document.getElementById('search-form');
|
|
|
|
if (searchInput && searchForm) {
|
|
const performSearch = async (e) => {
|
|
if (e) e.preventDefault();
|
|
const query = searchInput.value.trim();
|
|
if (!query) return;
|
|
|
|
// Show loading state if possible, or just proceed
|
|
|
|
// 1. Search Notes (Backend)
|
|
let notes = [];
|
|
try {
|
|
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
|
|
if (res.ok) {
|
|
notes = await res.json();
|
|
} else {
|
|
console.error("Search API failed:", res.status);
|
|
}
|
|
} catch (e) {
|
|
console.error("Search error:", e);
|
|
}
|
|
|
|
// If notes found, display them and stop (don't geocode)
|
|
if (notes.length > 0) {
|
|
if (window.displaySearchResults) {
|
|
window.displaySearchResults(notes, null, query);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// 2. Fallback: Search Location (Nominatim) if no notes found
|
|
let location = null;
|
|
try {
|
|
// Use local proxy to avoid CORS and set User-Agent
|
|
const nomRes = await fetch(`/api/geocode?q=${encodeURIComponent(query)}`);
|
|
const nomData = await nomRes.json();
|
|
if (nomData && nomData.length > 0) {
|
|
location = {
|
|
lat: parseFloat(nomData[0].lat),
|
|
lng: parseFloat(nomData[0].lon)
|
|
};
|
|
}
|
|
} catch (e) {
|
|
console.error("Geocoding error:", e);
|
|
}
|
|
|
|
// 3. Update UI via index.js helper
|
|
if (window.displaySearchResults) {
|
|
window.displaySearchResults(notes, location, query);
|
|
}
|
|
};
|
|
|
|
// Handle Enter key on input & Search Button click
|
|
searchForm.addEventListener('submit', performSearch);
|
|
}
|
|
});
|