Skip to content

Commit 46e79c9

Browse files
committed
feat: use fuse.js
1 parent 9616ed6 commit 46e79c9

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

index.html

+30-7
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@
128128
<script
129129
src="https://unpkg.com/protomaps-leaflet/dist/protomaps-leaflet.js"
130130
></script>
131+
<script src="https://unpkg.com/[email protected]"></script>
131132

132133
<link rel="preconnect" href="https://unpkg.com">
133134
<link rel="preconnect" href="https://api.protomaps.com">
@@ -848,18 +849,40 @@ <h3>Loading Error</h3>
848849
// Cities search functionality
849850
let citiesData = [];
850851
let searchTimeout = null;
852+
let fuse = null;
851853

852854
// Load cities data
853855
async function loadCitiesData() {
854856
try {
855857
const response = await fetch(
856-
"https://unpkg.com/[email protected]/cities.json",
858+
"https://unpkg.com/[email protected]/cities.json"
857859
);
858860
citiesData = await response.json();
861+
862+
// Initialize Fuse instance with loaded data
863+
fuse = new Fuse(citiesData, {
864+
keys: [
865+
{ name: 'name', weight: 2 }, // Give more weight to city name
866+
{ name: 'country', weight: 0.3 } // Also search by country but with lower weight
867+
],
868+
includeScore: true,
869+
threshold: 0.4, // Slightly more lenient threshold
870+
distance: 100, // Allow more errors for longer strings
871+
minMatchCharLength: 2,
872+
shouldSort: true, // Ensure results are sorted by score
873+
ignoreLocation: true, // Ignore where the match occurs in the string
874+
useExtendedSearch: true, // Enable extended search features
875+
getFn: (obj, path) => {
876+
// Custom getter to handle both exact and fuzzy matches
877+
const value = Fuse.config.getFn(obj, path);
878+
return typeof value === 'string' ? value.normalize('NFD').replace(/[\u0300-\u036f]/g, '') : value;
879+
}
880+
});
881+
859882
console.log(
860883
"Cities data loaded:",
861884
citiesData.length,
862-
"cities",
885+
"cities"
863886
);
864887
} catch (error) {
865888
console.error("Error loading cities data:", error);
@@ -869,14 +892,14 @@ <h3>Loading Error</h3>
869892

870893
// Search cities function
871894
function searchCities(query) {
872-
if (!query || query.length < 2) {
895+
if (!query || query.length < 2 || !fuse) {
873896
return [];
874897
}
875898

876-
query = query.toLowerCase();
877-
return citiesData
878-
.filter((city) => city.name.toLowerCase().includes(query))
879-
.slice(0, 10); // Limit to 10 results
899+
const results = fuse.search(query);
900+
return results
901+
.slice(0, 10) // Limit to 10 results
902+
.map(result => result.item);
880903
}
881904

882905
// Display search results

0 commit comments

Comments
 (0)