feat(ux-27): normalize persian text, add persistent error/retry state and accessible aria empty-state to search
This commit is contained in:
1 parent
21f7768cce
commit
23724df4e4
3 files changed
+132
-65
No files matched your search
@@ -26,7 +26,7 @@ import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { useRouter } from 'next/navigation';
|
||||
import api from "../lib/services/api";
|
||||
import { toPersian } from "../lib/utils";
|
||||
import { toPersian, normalizePersianText } from "../lib/utils";
|
||||
|
||||
type SearchTab = "all" | "products" | "blogs" | "wiki" | "videos";
|
||||
|
||||
@@ -72,79 +72,82 @@ export default function SearchResultsPage({ query }: { query: string }) {
|
||||
const [wikiItems, setWikiItems] = useState<WikiItem[]>([]);
|
||||
const [videos, setVideos] = useState<VideoItem[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [searchError, setSearchError] = useState<string | null>(null);
|
||||
|
||||
// Sync input when prop changes
|
||||
useEffect(() => {
|
||||
setSearchInput(query);
|
||||
}, [query]);
|
||||
|
||||
// Fetch all searchable datasets in parallel
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
const loadAll = async () => {
|
||||
setIsLoading(true);
|
||||
setSearchError(null);
|
||||
try {
|
||||
const [prodRes, blogRes, wikiRes, videoRes] = await Promise.allSettled([
|
||||
productService.getProducts({ limit: 999 }),
|
||||
api.get("/blogs?limit=50"),
|
||||
api.get("/ingredients?limit=100"),
|
||||
api.get("/videos?limit=50")
|
||||
]);
|
||||
|
||||
const loadAll = async () => {
|
||||
try {
|
||||
const [prodRes, blogRes, wikiRes, videoRes] = await Promise.allSettled([
|
||||
productService.getProducts({ limit: 999 }),
|
||||
api.get("/blogs?limit=50"),
|
||||
api.get("/ingredients?limit=100"),
|
||||
api.get("/videos?limit=50")
|
||||
]);
|
||||
|
||||
if (!isMounted) return;
|
||||
|
||||
if (prodRes.status === "fulfilled" && prodRes.value?.data) {
|
||||
setProducts(prodRes.value.data);
|
||||
} else if (prodRes.status === "rejected") {
|
||||
console.error("Error fetching products in SearchResultsPage:", prodRes.reason);
|
||||
}
|
||||
|
||||
if (blogRes.status === "fulfilled" && blogRes.value?.data) {
|
||||
const list = Array.isArray(blogRes.value.data.data)
|
||||
? blogRes.value.data.data
|
||||
: Array.isArray(blogRes.value.data)
|
||||
? blogRes.value.data
|
||||
: [];
|
||||
setBlogs(list);
|
||||
}
|
||||
|
||||
if (wikiRes.status === "fulfilled" && wikiRes.value?.data) {
|
||||
const list = Array.isArray(wikiRes.value.data.data)
|
||||
? wikiRes.value.data.data
|
||||
: Array.isArray(wikiRes.value.data)
|
||||
? wikiRes.value.data
|
||||
: [];
|
||||
setWikiItems(list);
|
||||
}
|
||||
|
||||
if (videoRes.status === "fulfilled" && videoRes.value?.data) {
|
||||
const vList = videoRes.value.data.videos || videoRes.value.data.data || videoRes.value.data;
|
||||
setVideos(Array.isArray(vList) ? vList : []);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error loading search datasets:", err);
|
||||
} finally {
|
||||
if (isMounted) setIsLoading(false);
|
||||
// If products or all datasets fail critically
|
||||
if (prodRes.status === "rejected") {
|
||||
setSearchError("خطا در برقراری ارتباط با سرور. لطفاً اتصال اینترنت خود را بررسی کنید.");
|
||||
console.error("Critical failure fetching search datasets:", prodRes.reason);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if (prodRes.status === "fulfilled" && prodRes.value?.data) {
|
||||
setProducts(prodRes.value.data);
|
||||
}
|
||||
|
||||
if (blogRes.status === "fulfilled" && blogRes.value?.data) {
|
||||
const list = Array.isArray(blogRes.value.data.data)
|
||||
? blogRes.value.data.data
|
||||
: Array.isArray(blogRes.value.data)
|
||||
? blogRes.value.data
|
||||
: [];
|
||||
setBlogs(list);
|
||||
}
|
||||
|
||||
if (wikiRes.status === "fulfilled" && wikiRes.value?.data) {
|
||||
const list = Array.isArray(wikiRes.value.data.data)
|
||||
? wikiRes.value.data.data
|
||||
: Array.isArray(wikiRes.value.data)
|
||||
? wikiRes.value.data
|
||||
: [];
|
||||
setWikiItems(list);
|
||||
}
|
||||
|
||||
if (videoRes.status === "fulfilled" && videoRes.value?.data) {
|
||||
const vList = videoRes.value.data.videos || videoRes.value.data.data || videoRes.value.data;
|
||||
setVideos(Array.isArray(vList) ? vList : []);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error loading search datasets:", err);
|
||||
setSearchError("بارگذاری اطلاعات با مشکل مواجه شد.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
return () => { isMounted = false; };
|
||||
}, []);
|
||||
|
||||
const cleanQuery = (query || "").trim().toLowerCase();
|
||||
const normalizedQuery = normalizePersianText(query || "");
|
||||
|
||||
// 1. Filtered Products
|
||||
const filteredProducts = useMemo(() => {
|
||||
if (!cleanQuery) return products;
|
||||
return products.filter(p =>
|
||||
(p.name || '').toLowerCase().includes(cleanQuery) ||
|
||||
(p.description || '').toLowerCase().includes(cleanQuery) ||
|
||||
(Array.isArray(p.main_ingredients) && p.main_ingredients.some(ing => ing.toLowerCase().includes(cleanQuery))) ||
|
||||
(Array.isArray(p.symptoms) && p.symptoms.some(sym => sym.toLowerCase().includes(cleanQuery))) ||
|
||||
(p.nameFa || '').toLowerCase().includes(cleanQuery) ||
|
||||
(p.nameEn || '').toLowerCase().includes(cleanQuery)
|
||||
normalizePersianText(p.name || '').includes(normalizedQuery) ||
|
||||
normalizePersianText(p.description || '').includes(normalizedQuery) ||
|
||||
(Array.isArray(p.main_ingredients) && p.main_ingredients.some(ing => normalizePersianText(ing || '').includes(normalizedQuery))) ||
|
||||
(Array.isArray(p.symptoms) && p.symptoms.some(sym => normalizePersianText(sym || '').includes(normalizedQuery))) ||
|
||||
normalizePersianText(p.nameFa || '').includes(normalizedQuery) ||
|
||||
normalizePersianText(p.nameEn || '').includes(normalizedQuery)
|
||||
);
|
||||
}, [products, cleanQuery]);
|
||||
|
||||
@@ -152,8 +155,8 @@ export default function SearchResultsPage({ query }: { query: string }) {
|
||||
const filteredBlogs = useMemo(() => {
|
||||
if (!cleanQuery) return blogs;
|
||||
return blogs.filter(b =>
|
||||
(b.title || '').toLowerCase().includes(cleanQuery) ||
|
||||
(b.excerpt || '').toLowerCase().includes(cleanQuery)
|
||||
normalizePersianText(b.title || '').includes(normalizedQuery) ||
|
||||
normalizePersianText(b.excerpt || '').includes(normalizedQuery)
|
||||
);
|
||||
}, [blogs, cleanQuery]);
|
||||
|
||||
@@ -161,10 +164,10 @@ export default function SearchResultsPage({ query }: { query: string }) {
|
||||
const filteredWiki = useMemo(() => {
|
||||
if (!cleanQuery) return wikiItems;
|
||||
return wikiItems.filter(w =>
|
||||
(w.name || '').toLowerCase().includes(cleanQuery) ||
|
||||
(w.nameFa || '').toLowerCase().includes(cleanQuery) ||
|
||||
(w.scientificName || '').toLowerCase().includes(cleanQuery) ||
|
||||
(w.description || '').toLowerCase().includes(cleanQuery)
|
||||
normalizePersianText(w.name || '').includes(normalizedQuery) ||
|
||||
normalizePersianText(w.nameFa || '').includes(normalizedQuery) ||
|
||||
normalizePersianText(w.scientificName || '').includes(normalizedQuery) ||
|
||||
normalizePersianText(w.description || '').includes(normalizedQuery)
|
||||
);
|
||||
}, [wikiItems, cleanQuery]);
|
||||
|
||||
@@ -172,9 +175,9 @@ export default function SearchResultsPage({ query }: { query: string }) {
|
||||
const filteredVideos = useMemo(() => {
|
||||
if (!cleanQuery) return videos;
|
||||
return videos.filter(v =>
|
||||
(v.title || '').toLowerCase().includes(cleanQuery) ||
|
||||
(v.doctor || '').toLowerCase().includes(cleanQuery) ||
|
||||
(v.description || '').toLowerCase().includes(cleanQuery)
|
||||
normalizePersianText(v.title || '').includes(normalizedQuery) ||
|
||||
normalizePersianText(v.doctor || '').includes(normalizedQuery) ||
|
||||
normalizePersianText(v.description || '').includes(normalizedQuery)
|
||||
);
|
||||
}, [videos, cleanQuery]);
|
||||
|
||||
@@ -296,9 +299,28 @@ export default function SearchResultsPage({ query }: { query: string }) {
|
||||
<div className="w-10 h-10 rounded-full border-4 border-canina-blue/20 border-t-canina-blue animate-spin mx-auto mb-4" aria-hidden="true" />
|
||||
<p className="text-sm font-black text-medical-gray-700">در حال جستجو در همه بخشهای کنینا...</p>
|
||||
</div>
|
||||
) : searchError ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="bg-white border border-red-200 rounded-3xl p-8 sm:p-12 text-center shadow-xs"
|
||||
>
|
||||
<div className="w-14 h-14 bg-red-50 text-red-500 rounded-2xl flex items-center justify-center mx-auto mb-4 border border-red-100">
|
||||
<AlertCircle className="w-7 h-7" />
|
||||
</div>
|
||||
<h3 className="text-lg font-black text-medical-gray-900 mb-2">خطا در بارگذاری نتایج جستجو</h3>
|
||||
<p className="text-xs text-medical-gray-500 max-w-md mx-auto mb-6">{searchError}</p>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="search-retry-button"
|
||||
onClick={() => loadAll()}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 bg-canina-blue text-white rounded-xl text-xs font-black hover:bg-canina-dark transition-all cursor-pointer shadow-xs"
|
||||
>
|
||||
<span>تلاش مجدد</span>
|
||||
</button>
|
||||
</div>
|
||||
) : cleanQuery && totalResults === 0 ? (
|
||||
/* Empty State - Mobile-Optimized with direct suggestion cards */
|
||||
<div className="space-y-8">
|
||||
<div className="space-y-8" role="status" aria-label="عدم یافت نتیجه جستجو">
|
||||
<div className="bg-white border border-medical-gray-200 rounded-3xl p-6 sm:p-10 text-center shadow-xs">
|
||||
<div className="w-14 h-14 bg-medical-gray-50 rounded-2xl flex items-center justify-center mx-auto text-medical-gray-300 mb-3 border border-medical-gray-100">
|
||||
<Search className="w-7 h-7" />
|
||||
|
||||
@@ -70,4 +70,29 @@ describe('SearchResultsPage',()=>{
|
||||
it('recomputes query without fetching and limits fallback suggestions',async()=>{const view=render(<SearchResultsPage query="Joint"/>);await screen.findByText('Joint Alpha');view.rerender(<SearchResultsPage query="missing"/>);expect(screen.getByText('نتیجهای یافت نشد')).toBeInTheDocument();expect(screen.getAllByRole('link')).toHaveLength(3);expect(screen.queryByText('Fourth')).not.toBeInTheDocument();expect(productService.getProducts).toHaveBeenCalledTimes(1);fireEvent.click(screen.getByRole('button',{name:'بازگشت'}));expect(h.back).toHaveBeenCalled();});
|
||||
it('handles service failure',async()=>{const err=vi.spyOn(console,'error').mockImplementation(()=>{});vi.mocked(productService.getProducts).mockRejectedValueOnce(new Error('offline'));render(<SearchResultsPage query="Joint"/>);await waitFor(()=>expect(err).toHaveBeenCalled());expect(screen.queryAllByRole('link')).toHaveLength(0);err.mockRestore();});
|
||||
it('shows recommendation, species mismatch and neutral compatibility',async()=>{pet.active={type:'سگ',name:'Rex',medicalConditions:['pain']};render(<SearchResultsPage query=""/>);await screen.findByText('Joint Alpha');expect(screen.getByText('توصیه شده برای Rex')).toBeInTheDocument();expect(screen.getByText('مخصوص گربه')).toBeInTheDocument();expect(screen.getAllByText('مناسب برای Rex')).toHaveLength(2);});
|
||||
|
||||
it('matches Persian queries with arabic letters, half-space, and different diacritics via normalization', async () => {
|
||||
render(<SearchResultsPage query="مادهٔ مراقبت" />);
|
||||
expect(await screen.findByRole('link', { name: /ماده مراقبت/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays error state and recovers upon clicking retry', async () => {
|
||||
vi.mocked(productService.getProducts).mockRejectedValueOnce(new Error('Network error'));
|
||||
vi.mocked(api.get).mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
render(<SearchResultsPage query="Joint" />);
|
||||
|
||||
const alertBox = await screen.findByRole('alert');
|
||||
expect(alertBox).toHaveTextContent('خطا در بارگذاری نتایج جستجو');
|
||||
|
||||
vi.mocked(productService.getProducts).mockResolvedValueOnce({ data: products } as any);
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: { data: [] } } as any);
|
||||
|
||||
const retryBtn = screen.getByTestId('search-retry-button');
|
||||
fireEvent.click(retryBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -25,3 +25,23 @@ export function isProductOutOfStock(product?: {
|
||||
if (product.packageSize !== undefined && product.packageSize !== null && Number(product.packageSize) <= 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function normalizePersianText(input: string | undefined | null): string {
|
||||
if (!input) return "";
|
||||
return input
|
||||
.toString()
|
||||
.toLowerCase()
|
||||
.replace(/[\u200B-\u200D\uFEFF]/g, "")
|
||||
.replace(/[\u200C]/g, " ")
|
||||
.replace(/[يیى]/g, "ی")
|
||||
.replace(/[ك]/g, "ک")
|
||||
.replace(/[ة]/g, "ه")
|
||||
.replace(/[أإآ]/g, "ا")
|
||||
.replace(/[ؤ]/g, "و")
|
||||
.replace(/[ء]/g, "")
|
||||
.replace(/[\u064B-\u065F]/g, "")
|
||||
.replace(/[۰-۹]/g, d => "0123456789"["۰۱۲۳۴۵۶۷۸۹".indexOf(d)])
|
||||
.replace(/[٠-٩]/g, d => "0123456789"["٠١٢٣٤٥٦٧٨٩".indexOf(d)])
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
Reference in new issue
Block a user