Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add fuzzy search on communes #59

Merged
merged 2 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions hooks/use-debounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useCallback, useRef } from "react";

export const useDebounce = (fn: Function, ms: number = 500) => {
const timeoutRef = useRef<NodeJS.Timeout | null>(null);

return useCallback(
(...args: any[]) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
return fn(...args);
}, ms);
},
[fn, ms]
);
};
29 changes: 29 additions & 0 deletions hooks/use-fuse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import Fuse from "fuse.js";
import { useCallback } from "react";

export const useFuse = (
data: any[],
keys: string[],
setter: (values: { label: string; value: string }[]) => void
) => {
return useCallback(
(search) => {
const fuse = new Fuse(data, {
keys,
threshold: 0.4,
});
if (search.length <= 2) {
setter([]);
} else if (search.length > 2) {
const results = fuse.search(search).slice(0, 10);
setter(
results.map(({ item }) => ({
label: `${item.nom} (${item.code})`,
value: item.code,
}))
);
}
},
[data, keys, setter]
);
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"cors": "^2.8.5",
"date-fns": "^2.29.3",
"express": "^4.18.2",
"fuse.js": "6.6.2",
"got": "11.8",
"lodash": "^4.17.21",
"mongodb": "^5.6.0",
Expand Down
75 changes: 36 additions & 39 deletions pages/communes.tsx
Original file line number Diff line number Diff line change
@@ -1,59 +1,58 @@
import {useState, useEffect} from 'react'
import {useRouter} from 'next/router'
import allCommunes from '@etalab/decoupage-administratif/data/communes.json'
import {SearchBar} from '@codegouvfr/react-dsfr/SearchBar'
import { useState, useEffect } from "react";
import { useRouter } from "next/router";
import allCommunes from "@etalab/decoupage-administratif/data/communes.json";
import { SearchBar } from "@codegouvfr/react-dsfr/SearchBar";

import SearchInput from '@/components/search-input'
import SearchInput from "@/components/search-input";
import { useFuse } from "@/hooks/use-fuse";
import { useDebounce } from "@/hooks/use-debounce";

const communes = (allCommunes as Array<{nom: string; code: string; type: string}>).filter(c => ['commune-actuelle', 'arrondissement-municipal'].includes(c.type))
const communes = (
allCommunes as Array<{ nom: string; code: string; type: string }>
).filter((c) =>
["commune-actuelle", "arrondissement-municipal"].includes(c.type)
);

const Communes = () => {
const router = useRouter()
const router = useRouter();

const [value, setValue] = useState(null)
const [inputValue, setInputValue] = useState('')
const [options, setOptions] = useState([])
const [value, setValue] = useState(null);
const [inputValue, setInputValue] = useState("");
const [options, setOptions] = useState<{ label: string; value: string }[]>(
[]
);
const fuzzySearch = useFuse(communes, ["nom", "code"], setOptions);
const debouncedFuzzySearch = useDebounce(fuzzySearch, 500);

useEffect(() => {
if (inputValue.length <= 2) {
setOptions([])
} else if (inputValue.length > 2) {
const newOptions = communes
.filter(c =>
String(c.code).toLowerCase().includes(inputValue.toLowerCase())
|| c.nom.toLowerCase().includes(inputValue.toLowerCase()),
)
.map(c => ({label: `${c.nom} (${c.code})`, value: c.code}))
.slice(0, 10)
setOptions(newOptions)
}
}, [inputValue])
debouncedFuzzySearch(inputValue);
}, [debouncedFuzzySearch, inputValue]);

useEffect(() => {
if (value?.value) {
void router.push({pathname: `/communes/${(value.value as string)}`})
void router.push({ pathname: `/communes/${value.value as string}` });
}
}, [value, router])
}, [value, router]);

return (
<div className='fr-container fr-py-12v'>
<div className='fr-container--fluid'>
<div className="fr-container fr-py-12v">
<div className="fr-container--fluid">
<h3>Recherche</h3>
<div className='fr-grid-row fr-grid-row--gutters'>
<div className='fr-col'>
<div className="fr-grid-row fr-grid-row--gutters">
<div className="fr-col">
<SearchBar
renderInput={({className, id, placeholder, type}) => (
renderInput={({ className, id, placeholder, type }) => (
<SearchInput
options={options}
className={className}
id={id}
placeholder={placeholder}
type={type}
onChange={newValue => {
setValue(newValue)
onChange={(newValue) => {
setValue(newValue);
}}
onInputChange={newValue => {
setInputValue(newValue)
onInputChange={(newValue) => {
setInputValue(newValue);
}}
/>
)}
Expand All @@ -62,9 +61,7 @@ const Communes = () => {
</div>
</div>
</div>
);
};

)
}

export default Communes

export default Communes;
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2015,6 +2015,11 @@ functions-have-names@^1.2.3:
resolved "https://registry.yarnpkg.com/functions-have-names/-/functions-have-names-1.2.3.tgz#0404fe4ee2ba2f607f0e0ec3c80bae994133b834"
integrity sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==

[email protected]:
version "6.6.2"
resolved "https://registry.yarnpkg.com/fuse.js/-/fuse.js-6.6.2.tgz#fe463fed4b98c0226ac3da2856a415576dc9a111"
integrity sha512-cJaJkxCCxC8qIIcPBF9yGxY0W/tVZS3uEISDxhYIdtk8OL93pe+6Zj7LjCqVV4dzbqcriOZ+kQ/NE4RXZHsIGA==

get-intrinsic@^1.0.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.1.2.tgz#336975123e05ad0b7ba41f152ee4aadbea6cf598"
Expand Down
Loading