feat(search): add segmented universal results
Deploy Canina / deploy (push) Successful in 2m7s

This commit is contained in:
devops committed 2026-10-17 12:33:00 +00:00
1 parent 297aaadbe6
commit 570f0acc66
4 files changed
+72 -5

No files matched your search

@@ -168,7 +168,7 @@ export default function MobileBottomNav({
if (searchQuery.trim()) {
const q = searchQuery.trim();
closeSheet(false);
router.push(`/shop?search=${encodeURIComponent(q)}`);
router.push(`/search?q=${encodeURIComponent(q)}`);
} else {
closeSheet(false);
router.push("/shop");
@@ -249,7 +249,11 @@ export default function SearchResultsPage({ query }: { query: string }) {
</div>
{/* Multi-Content Filter Tabs */}
<div className="flex items-center gap-1.5 sm:gap-2 overflow-x-auto pb-3 mb-6 micro-hscroll select-none">
<div
role="tablist"
aria-label="فیلتر نوع محتوای نتایج جستجو"
className="flex items-center gap-1.5 sm:gap-2 overflow-x-auto pb-3 mb-6 micro-hscroll select-none"
>
{[
{ id: "all", label: "همه نتایج", count: totalResults, icon: <Sparkles className="w-3.5 h-3.5" /> },
{ id: "products", label: "محصولات و داروها", count: filteredProducts.length, icon: <ShoppingBag className="w-3.5 h-3.5" /> },
@@ -260,6 +264,10 @@ export default function SearchResultsPage({ query }: { query: string }) {
<button
key={tab.id}
type="button"
role="tab"
id={`search-tab-${tab.id}`}
aria-selected={activeTab === tab.id}
aria-controls={`search-panel-${tab.id}`}
onClick={() => setActiveTab(tab.id as SearchTab)}
className={`flex items-center gap-1.5 px-3 py-1.5 sm:px-4 sm:py-2 rounded-xl text-xs font-black transition-all shrink-0 cursor-pointer border ${
activeTab === tab.id
@@ -279,7 +287,16 @@ export default function SearchResultsPage({ query }: { query: string }) {
</div>
{/* RESULTS AREA */}
{cleanQuery && totalResults === 0 && !isLoading ? (
{isLoading ? (
<div
role="status"
aria-live="polite"
className="bg-white border border-medical-gray-200 rounded-3xl p-8 sm:p-12 text-center shadow-xs"
>
<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>
) : cleanQuery && totalResults === 0 ? (
/* Empty State - Mobile-Optimized with direct suggestion cards */
<div className="space-y-8">
<div className="bg-white border border-medical-gray-200 rounded-3xl p-6 sm:p-10 text-center shadow-xs">
@@ -497,7 +514,7 @@ export default function SearchResultsPage({ query }: { query: string }) {
{(activeTab === "all" ? filteredWiki.slice(0, 4) : filteredWiki).map((wiki) => (
<Link
key={wiki.id}
href={`/wiki?search=${encodeURIComponent(wiki.nameFa || wiki.name || '')}`}
href={`/wiki?term=${encodeURIComponent(wiki.slug || wiki.id)}`}
className="group bg-white rounded-2xl p-3 border border-medical-gray-200 hover:border-amber-500 shadow-2xs hover:shadow-md transition-all flex items-start gap-3"
>
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0">
@@ -8,6 +8,7 @@ import { useUserStore } from '../../lib/store/userStore';
import { useUIStore } from '../../lib/store/uiStore';
import { useSettingsStore } from '../../lib/store/settingsStore';
import { useCatalogMode } from '../../lib/useCatalogMode';
import { productService } from '../../lib/services/productService';
vi.mock('next/navigation', () => ({
usePathname: vi.fn(),
@@ -34,6 +35,10 @@ vi.mock('../../lib/useCatalogMode', () => ({
useCatalogMode: vi.fn(),
}));
vi.mock('../../lib/services/productService', () => ({
productService: { getProducts: vi.fn() },
}));
describe('MobileBottomNav Component', () => {
const mockRouterPush = vi.fn();
const mockSetAuthModalOpen = vi.fn();
@@ -80,6 +85,7 @@ describe('MobileBottomNav Component', () => {
isCatalogOnly: false,
allowCart: true,
} as any);
vi.mocked(productService.getProducts).mockResolvedValue({ data: [] } as any);
});
it('renders all default 5 navigation tabs', () => {
@@ -182,6 +188,14 @@ describe('MobileBottomNav Component', () => {
expect(screen.getByText('مشاهده کاتالوگ و همه محصولات')).toBeInTheDocument();
});
it('routes mobile search submissions to universal search', () => {
render(<MobileBottomNav />);
fireEvent.click(screen.getByText('فروشگاه').closest('button')!);
fireEvent.change(screen.getByPlaceholderText(/جستجوی دارو، ترکیب یا علامت بالینی/i), { target: { value: 'joint care' } });
fireEvent.submit(screen.getByPlaceholderText(/جستجوی دارو، ترکیب یا علامت بالینی/i).closest('form')!);
expect(mockRouterPush).toHaveBeenCalledWith('/search?q=joint%20care');
});
it('opens menu bottom sheet when menu tab is clicked', () => {
render(<MobileBottomNav />);
@@ -16,7 +16,9 @@ import { toast } from 'sonner';
afterEach(cleanup);
import SearchResultsPage from '../SearchResultsPage';
import { productService } from '../../lib/services/productService';
import api from '../../lib/services/api';
vi.mock('../../lib/services/productService',()=>({productService:{getProducts:vi.fn()}}));
vi.mock('../../lib/services/api',()=>({default:{get:vi.fn()}}));
const pet=vi.hoisted(()=>({active:null as any}));
vi.mock('../../lib/store/usePetStore',()=>({usePetStore:()=>({getActivePet:()=>pet.active})}));
const products=[
@@ -24,8 +26,42 @@ const products=[
{id:'b',name:'Coat Beta',description:'Shiny fur',main_ingredients:['Biotin'],symptoms:['itch'],suitableFor:'گربه',image:'/b.png',price:'200',category:'skin',benefits:'coat'},
{id:'c',name:'Both Gamma',description:'Daily care',main_ingredients:[],symptoms:[],suitableFor:'هر دو',image:'/c.png',price:'300',category:'care',benefits:'health'},
{id:'d',name:'Fourth',description:'Daily',main_ingredients:[],symptoms:[],suitableFor:'سگ',image:'/d.png',price:'400',category:'care',benefits:'health'}];
beforeEach(()=>{vi.clearAllMocks();pet.active=null;vi.mocked(productService.getProducts).mockResolvedValue({data:products} as any);});
beforeEach(()=>{
vi.clearAllMocks();pet.active=null;
vi.mocked(productService.getProducts).mockResolvedValue({data:products} as any);
vi.mocked(api.get).mockImplementation(async (url: string) => {
if (url.startsWith('/blogs')) return {data:{data:[{id:'blog-1',slug:'care-guide',title:'Care article',excerpt:'Daily care'}]}} as any;
if (url.startsWith('/ingredients')) return {data:[{id:'wiki-1',slug:'care',nameFa:'ماده مراقبت',description:'Daily care'}]} as any;
if (url.startsWith('/videos')) return {data:{videos:[{id:'video-1',title:'Care video',description:'Daily care'}]}} as any;
throw new Error(`Unexpected URL: ${url}`);
});
});
describe('SearchResultsPage',()=>{
it('announces loading before all search datasets settle',()=>{
vi.mocked(productService.getProducts).mockReturnValue(new Promise(()=>{}) as any);
vi.mocked(api.get).mockReturnValue(new Promise(()=>{}) as any);
render(<SearchResultsPage query="care"/>);
expect(screen.getByRole('status')).toHaveTextContent('در حال جستجو');
});
it('exposes accessible segmented tabs with live counts and filters each content type',async()=>{
render(<SearchResultsPage query="care"/>);
const allTab=await screen.findByRole('tab',{name:/همه نتایج.*۴/});
const productTab=screen.getByRole('tab',{name:/محصولات و داروها.*۱/});
const blogTab=screen.getByRole('tab',{name:/مقالات وبلاگ.*۱/});
const wikiTab=screen.getByRole('tab',{name:/دانشنامه ترکیبات.*۱/});
const videoTab=screen.getByRole('tab',{name:/ویدیوهای بالینی.*۱/});
expect(allTab).toHaveAttribute('aria-selected','true');
fireEvent.click(blogTab);
expect(blogTab).toHaveAttribute('aria-selected','true');
expect(screen.getByRole('link',{name:/Care article/})).toBeInTheDocument();
expect(screen.queryByRole('link',{name:/Both Gamma/})).not.toBeInTheDocument();
fireEvent.click(wikiTab);
expect(screen.getByRole('link',{name:/ماده مراقبت/})).toBeInTheDocument();
fireEvent.click(videoTab);
expect(screen.getByRole('link',{name:/Care video/})).toBeInTheDocument();
fireEvent.click(productTab);
expect(screen.getByRole('link',{name:/Both Gamma/})).toBeInTheDocument();
});
it.each(['JOINT','mobility','glucosamine','pain'])('searches field %s',async query=>{render(<SearchResultsPage query={query}/>);expect(await screen.findByRole('link',{name:/Joint Alpha/})).toHaveAttribute('href','/shop/alpha');expect(screen.getAllByRole('link')).toHaveLength(1);expect(productService.getProducts).toHaveBeenCalledWith({limit:999});});
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();});