From 1b54ef6a7da4b2d356a2a33abf98cbb7bf39df2f Mon Sep 17 00:00:00 2001
From: Ariel Costas Guerrero <ariel@costas.dev>
Date: Mon, 12 May 2025 17:57:33 +0200
Subject: Fix bugs, add new setting, make app great again

---
 src/pages/StopList.tsx | 51 +++++++++++++++++++++++++++++++++-----------------
 1 file changed, 34 insertions(+), 17 deletions(-)

(limited to 'src/pages/StopList.tsx')

diff --git a/src/pages/StopList.tsx b/src/pages/StopList.tsx
index a2269ec..b965456 100644
--- a/src/pages/StopList.tsx
+++ b/src/pages/StopList.tsx
@@ -1,35 +1,54 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
 import StopDataProvider, { Stop } from "../data/StopDataProvider";
 import StopItem from "../components/StopItem";
 import Fuse from "fuse.js";
 
 const placeholders = [
-  "Urzaiz",
-  "Gran Vía",
-  "Castelao",
-  "García Barbón",
-  "Valladares",
-  "Florida",
-  "Pizarro",
-  "Estrada Madrid",
-  "Sanjurjo Badía"
+	"Urzaiz",
+	"Gran Vía",
+	"Castelao",
+	"García Barbón",
+	"Valladares",
+	"Florida",
+	"Pizarro",
+	"Estrada Madrid",
+	"Sanjurjo Badía"
 ];
 
 export function StopList() {
 	const [data, setData] = useState<Stop[] | null>(null)
 	const [searchResults, setSearchResults] = useState<Stop[] | null>(null);
+	const searchTimeout = useRef<NodeJS.Timeout | null>(null);
+
+	const randomPlaceholder = useMemo(() => placeholders[Math.floor(Math.random() * placeholders.length)], []);
+	const fuse = useMemo(() => new Fuse(data || [], { threshold: 0.3, keys: ['name.original'] }), [data]);
 
 	useEffect(() => {
 		StopDataProvider.getStops().then((stops: Stop[]) => setData(stops))
 	}, []);
 
 	const handleStopSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
-		const stopName = event.target.value;
-		if (data) {
-			const fuse = new Fuse(data, { keys: ['name'], threshold: 0.3 });
-			const results = fuse.search(stopName).map(result => result.item);
-			setSearchResults(results);
+		const stopName = event.target.value || "";
+
+		if (searchTimeout.current) {
+			clearTimeout(searchTimeout.current);
 		}
+
+		searchTimeout.current = setTimeout(() => {
+			if (stopName.length === 0) {
+				setSearchResults(null);
+				return;
+			}
+
+			if (!data) {
+				console.error("No data available for search");
+				return;
+			}
+
+			const results = fuse.search(stopName);
+			const items = results.map(result => result.item);
+			setSearchResults(items);
+		}, 300);
 	}
 
 	const favouritedStops = useMemo(() => {
@@ -50,8 +69,6 @@ export function StopList() {
 
 	if (data === null) return <h1 className="page-title">Loading...</h1>
 
-	const randomPlaceholder = placeholders[Math.floor(Math.random() * placeholders.length)];
-
 	return (
 		<div className="page-container">
 			<h1 className="page-title">UrbanoVigo Web</h1>
-- 
cgit v1.3

