diff --git a/src/components/campaign/dashboard/CampaignHomeSearch.tsx b/src/components/campaign/dashboard/CampaignHomeSearch.tsx index 002c2eb7..d8fed14f 100644 --- a/src/components/campaign/dashboard/CampaignHomeSearch.tsx +++ b/src/components/campaign/dashboard/CampaignHomeSearch.tsx @@ -4,7 +4,9 @@ import type { ReactNode } from 'react' import { useHomeSearch } from '@/components/campaign/dashboard/HomeSearchContext' import { CampaignSearchInput } from '@/components/campaign/shared/CampaignSearchInput' +import { homeSearchShouldUnfocusOnBlur } from '@/lib/campaignHomeSearchContract' import { HOME_SEARCH_QUERY_MAX_LENGTH } from '@/lib/schemas/homeSearch' +import { cn } from '@/lib/utils' const HOME_SEARCH_INPUT_ID = 'homeSearchQuery' const HOME_SEARCH_LABEL = 'Buscar na campanha' @@ -15,6 +17,8 @@ export const CampaignHomeSearch = ({ resultsBusy, placeholder = HOME_SEARCH_PLACEHOLDER, showResults = true, + blurUnfocusPolicy = 'whenInactive', + compactStack = false, }: { children?: ReactNode /** When set, must already fold debounce (see `useHomeSearchResultsState.isFetching`). */ @@ -23,12 +27,19 @@ export const CampaignHomeSearch = ({ placeholder?: string /** When false, keeps the live region mounted but visually hidden (collapsed peek). */ showResults?: boolean + /** + * Início: unfocus when query inactive. Drawer (B112): unfocus only when raw + * is empty so blur-with-text keeps FULL. + */ + blurUnfocusPolicy?: 'whenInactive' | 'whenEmpty' + /** B112 — ~⅓ of the default input→results gap in the bottom drawer. */ + compactStack?: boolean }) => { const { query, setRaw, clear, isDebouncing, setInputFocused } = useHomeSearch() const ariaBusy = (resultsBusy ?? isDebouncing) || undefined return ( -
+
setRaw(event.target.value)} onFocus={() => setInputFocused(true)} onBlur={() => { - if (!query.isActive) { + if (homeSearchShouldUnfocusOnBlur(query.raw, blurUnfocusPolicy, query.isActive)) { setInputFocused(false) } }} diff --git a/src/components/campaign/dashboard/CampaignStaffGlobalSearch.tsx b/src/components/campaign/dashboard/CampaignStaffGlobalSearch.tsx index 0d7fa918..ba7f94a2 100644 --- a/src/components/campaign/dashboard/CampaignStaffGlobalSearch.tsx +++ b/src/components/campaign/dashboard/CampaignStaffGlobalSearch.tsx @@ -17,10 +17,16 @@ import { HomeSearchStateDeputyGroup } from '@/components/campaign/dashboard/Home export const CampaignStaffGlobalSearchBody = ({ placeholder, showResults = true, + blurUnfocusPolicy = 'whenInactive', + compactStack = false, }: { /** Forwarded to `CampaignHomeSearch` — empty string for collapsed discreet peek. */ placeholder?: string showResults?: boolean + /** Drawer passes `whenEmpty` (B112); Início keeps `whenInactive`. */ + blurUnfocusPolicy?: 'whenInactive' | 'whenEmpty' + /** Drawer passes true for ~⅓ gap (B112); Início keeps the default stack. */ + compactStack?: boolean }) => { const searchResultsState = useHomeSearchResultsState() @@ -29,6 +35,8 @@ export const CampaignStaffGlobalSearchBody = ({ resultsBusy={searchResultsState.isFetching} placeholder={placeholder} showResults={showResults} + blurUnfocusPolicy={blurUnfocusPolicy} + compactStack={compactStack} > diff --git a/src/components/campaign/shell/CampaignQuickActionsDrawer.tsx b/src/components/campaign/shell/CampaignQuickActionsDrawer.tsx index b5137564..107cab78 100644 --- a/src/components/campaign/shell/CampaignQuickActionsDrawer.tsx +++ b/src/components/campaign/shell/CampaignQuickActionsDrawer.tsx @@ -1,7 +1,7 @@ 'use client' import { usePathname } from 'next/navigation' -import { useCallback, useEffect } from 'react' +import { useCallback, useEffect, useRef } from 'react' import { CampaignGlobalSearchBody } from '@/components/campaign/dashboard/CampaignGlobalSearchMount' import { CampaignHomeActionStrip } from '@/components/campaign/dashboard/CampaignHomeActionStrip' @@ -11,11 +11,11 @@ import { useCampaignQuickActionContext } from '@/components/campaign/shell/Campa import { useCampaignQuickActionsSnap } from '@/components/campaign/shell/CampaignQuickActionsSnapContext' import { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/Drawer' import { - QUICK_ACTIONS_SCROLL_COLLAPSE_THRESHOLD_PX, QUICK_ACTIONS_SNAP_COLLAPSED, QUICK_ACTIONS_SNAP_DOCK, QUICK_ACTIONS_SNAP_FULL, QUICK_ACTIONS_SNAP_POINTS, + quickActionsSnapAfterDismiss, quickActionsSnapIsDock, quickActionsSnapIsFull, type QuickActionsSnapPoint, @@ -26,14 +26,6 @@ import { cn } from '@/lib/utils' const SNAP_POINTS = [...QUICK_ACTIONS_SNAP_POINTS] -const restoreSnapAfterSearch = (): QuickActionsSnapPoint => { - const scrollport = document.querySelector('[data-slot="campaign-content-scroll"]') - const scrollTop = scrollport instanceof HTMLElement ? scrollport.scrollTop : 0 - return scrollTop > QUICK_ACTIONS_SCROLL_COLLAPSE_THRESHOLD_PX - ? QUICK_ACTIONS_SNAP_COLLAPSED - : QUICK_ACTIONS_SNAP_DOCK -} - export const CampaignQuickActionsDrawer = ({ actions, }: { @@ -43,52 +35,77 @@ export const CampaignQuickActionsDrawer = ({ const { context } = useCampaignQuickActionContext() const excludeContext = resolveHomeSearchExcludeContext(pathname, context) const { snapPoint, setSnapPoint, isDock, isFull } = useCampaignQuickActionsSnap() - const { uiFocused } = useHomeSearch() + const { uiFocused, clear } = useHomeSearch() const showActions = actions.length > 0 && isDock && !isFull const showSearchResults = isDock || isFull + const skipNextPathCollapseRef = useRef(true) + const wasUiFocusedRef = useRef(false) + + const dismissToCollapsed = useCallback(() => { + // Clear first so the uiFocused→FULL effect cannot reopen on the same tick. + clear() + setSnapPoint(quickActionsSnapAfterDismiss()) + }, [clear, setSnapPoint]) const handleSnapPointChange = useCallback( (next: QuickActionsSnapPoint | string | number | null) => { - if ( - next === QUICK_ACTIONS_SNAP_COLLAPSED || - next === QUICK_ACTIONS_SNAP_DOCK || - next === QUICK_ACTIONS_SNAP_FULL - ) { + if (next === QUICK_ACTIONS_SNAP_COLLAPSED) { + dismissToCollapsed() + return + } + if (next === QUICK_ACTIONS_SNAP_DOCK || next === QUICK_ACTIONS_SNAP_FULL) { setSnapPoint(next) return } - setSnapPoint(QUICK_ACTIONS_SNAP_COLLAPSED) + dismissToCollapsed() }, - [setSnapPoint], + [dismissToCollapsed, setSnapPoint], ) const toggleSnap = useCallback(() => { - setSnapPoint((current) => { - if (quickActionsSnapIsFull(current)) return restoreSnapAfterSearch() - if (quickActionsSnapIsDock(current)) return QUICK_ACTIONS_SNAP_COLLAPSED - return QUICK_ACTIONS_SNAP_DOCK - }) - }, [setSnapPoint]) + if (uiFocused || quickActionsSnapIsFull(snapPoint)) { + dismissToCollapsed() + return + } + if (quickActionsSnapIsDock(snapPoint)) { + setSnapPoint(QUICK_ACTIONS_SNAP_COLLAPSED) + return + } + setSnapPoint(QUICK_ACTIONS_SNAP_DOCK) + }, [dismissToCollapsed, setSnapPoint, snapPoint, uiFocused]) const handleOpenChange = useCallback( (open: boolean) => { if (!open) { - setSnapPoint(QUICK_ACTIONS_SNAP_COLLAPSED) + dismissToCollapsed() } }, - [setSnapPoint], + [dismissToCollapsed], ) + useEffect(() => { + if (skipNextPathCollapseRef.current) { + skipNextPathCollapseRef.current = false + return + } + dismissToCollapsed() + }, [dismissToCollapsed, pathname]) + useEffect(() => { if (!uiFocused) return + wasUiFocusedRef.current = true if (!quickActionsSnapIsFull(snapPoint)) { setSnapPoint(QUICK_ACTIONS_SNAP_FULL) } }, [snapPoint, setSnapPoint, uiFocused]) + // Empty blur (uiFocused true→false) → collapsed. Skip the never-focused load path + // so the initial dock from B100 survives. useEffect(() => { if (uiFocused) return - setSnapPoint(restoreSnapAfterSearch()) + if (!wasUiFocusedRef.current) return + wasUiFocusedRef.current = false + setSnapPoint(quickActionsSnapAfterDismiss()) }, [setSnapPoint, uiFocused]) return ( @@ -96,8 +113,8 @@ export const CampaignQuickActionsDrawer = ({ open modal={false} swipeDirection="down" - snapPoints={uiFocused ? [QUICK_ACTIONS_SNAP_FULL] : SNAP_POINTS} - snapPoint={uiFocused ? QUICK_ACTIONS_SNAP_FULL : snapPoint} + snapPoints={SNAP_POINTS} + snapPoint={snapPoint} onSnapPointChange={handleSnapPointChange} onOpenChange={handleOpenChange} disablePointerDismissal @@ -124,10 +141,11 @@ export const CampaignQuickActionsDrawer = ({ id="quickActionContext" className={cn( 'flex min-h-0 flex-col overflow-y-auto px-4', + // B112 — dock/collapsed bottom gap ≈ ⅓ of prior gap-2 (keep safe-area). isFull - ? 'flex-1 gap-2 pb-[max(0.25rem,env(safe-area-inset-bottom,0px))]' + ? 'flex-1 gap-1 pb-[max(0.25rem,env(safe-area-inset-bottom,0px))]' : cn( - 'gap-2 pb-[max(0.25rem,env(safe-area-inset-bottom,0px))]', + 'gap-1 pb-[max(0.25rem,env(safe-area-inset-bottom,0px))]', isDock ? 'flex-1' : 'shrink-0', ), )} @@ -151,6 +169,8 @@ export const CampaignQuickActionsDrawer = ({
diff --git a/src/components/campaign/shell/CampaignQuickActionsSnapContext.tsx b/src/components/campaign/shell/CampaignQuickActionsSnapContext.tsx index d2751b40..24e3de87 100644 --- a/src/components/campaign/shell/CampaignQuickActionsSnapContext.tsx +++ b/src/components/campaign/shell/CampaignQuickActionsSnapContext.tsx @@ -1,10 +1,8 @@ 'use client' -import { usePathname } from 'next/navigation' import { createContext, useContext, - useEffect, useMemo, useState, type Dispatch, @@ -31,13 +29,9 @@ const CampaignQuickActionsSnapContext = createContext { - const pathname = usePathname() + // B112 — load = dock; pathname collapse lives in the drawer (needs `clear`). const [snapPoint, setSnapPoint] = useState(QUICK_ACTIONS_SNAP_DOCK) - useEffect(() => { - setSnapPoint(QUICK_ACTIONS_SNAP_DOCK) - }, [pathname]) - const value = useMemo( (): CampaignQuickActionsSnapContextValue => ({ snapPoint, diff --git a/src/lib/campaignHomeSearchContract.ts b/src/lib/campaignHomeSearchContract.ts index d5fd4d11..656f7748 100644 --- a/src/lib/campaignHomeSearchContract.ts +++ b/src/lib/campaignHomeSearchContract.ts @@ -25,5 +25,20 @@ export const normalizeHomeSearchRaw = (raw: string): string => raw.trim() export const homeSearchUiFocused = (input: { inputFocused: boolean; isActive: boolean }): boolean => input.inputFocused || input.isActive +/** + * B112 drawer — blur with any typed text keeps the ritual; only empty blur + * unfocuses (Início still uses `whenInactive` via the default prop). + */ +export const homeSearchShouldUnfocusOnBlur = ( + raw: string, + policy: 'whenInactive' | 'whenEmpty', + isActive: boolean, +): boolean => { + if (policy === 'whenEmpty') { + return normalizeHomeSearchRaw(raw).length === 0 + } + return !isActive +} + /** B106 — mobile top bar back control when Início search is expanded. */ export const HOME_SEARCH_COLLAPSE_ARIA_LABEL = 'Fechar busca' as const diff --git a/src/lib/campaignQuickActionSnap.ts b/src/lib/campaignQuickActionSnap.ts index 0f366f81..699a1a82 100644 --- a/src/lib/campaignQuickActionSnap.ts +++ b/src/lib/campaignQuickActionSnap.ts @@ -29,6 +29,16 @@ export const quickActionsSnapIsFull = (snap: QuickActionsSnapPoint | null): bool export const quickActionsSnapIsDock = (snap: QuickActionsSnapPoint | null): boolean => snap === QUICK_ACTIONS_SNAP_DOCK +export const quickActionsSnapIsCollapsed = (snap: QuickActionsSnapPoint | null): boolean => + snap === QUICK_ACTIONS_SNAP_COLLAPSED + +/** + * B112 — empty blur, handle tap/swipe ↓, and in-chrome navigation all land on + * collapsed (clear search separately so `uiFocused → FULL` cannot reopen). + */ +export const quickActionsSnapAfterDismiss = (): QuickActionsSnapPoint => + QUICK_ACTIONS_SNAP_COLLAPSED + /** Pure scroll-direction detector for the quick-actions peek (B105). */ export const quickActionsScrollDirection = ( previousScrollTop: number, diff --git a/tests/unit/campaignHomeSearchContract.unit.spec.ts b/tests/unit/campaignHomeSearchContract.unit.spec.ts index 1989ed5c..f8a21e28 100644 --- a/tests/unit/campaignHomeSearchContract.unit.spec.ts +++ b/tests/unit/campaignHomeSearchContract.unit.spec.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest' -import { homeSearchUiFocused } from '@/lib/campaignHomeSearchContract' +import { + homeSearchShouldUnfocusOnBlur, + homeSearchUiFocused, +} from '@/lib/campaignHomeSearchContract' describe('homeSearchUiFocused', () => { it('is true when the input is focused without an active query', () => { @@ -15,3 +18,17 @@ describe('homeSearchUiFocused', () => { expect(homeSearchUiFocused({ inputFocused: false, isActive: false })).toBe(false) }) }) + +describe('homeSearchShouldUnfocusOnBlur', () => { + it('whenEmpty unfocuses only blank raw (B112 drawer)', () => { + expect(homeSearchShouldUnfocusOnBlur('', 'whenEmpty', false)).toBe(true) + expect(homeSearchShouldUnfocusOnBlur(' ', 'whenEmpty', false)).toBe(true) + expect(homeSearchShouldUnfocusOnBlur('c', 'whenEmpty', false)).toBe(false) + expect(homeSearchShouldUnfocusOnBlur('ca', 'whenEmpty', true)).toBe(false) + }) + + it('whenInactive follows isActive (Início)', () => { + expect(homeSearchShouldUnfocusOnBlur('c', 'whenInactive', false)).toBe(true) + expect(homeSearchShouldUnfocusOnBlur('ca', 'whenInactive', true)).toBe(false) + }) +}) diff --git a/tests/unit/campaignQuickActionsDrawer.unit.spec.tsx b/tests/unit/campaignQuickActionsDrawer.unit.spec.tsx index c1fc0452..eb756449 100644 --- a/tests/unit/campaignQuickActionsDrawer.unit.spec.tsx +++ b/tests/unit/campaignQuickActionsDrawer.unit.spec.tsx @@ -20,6 +20,8 @@ import { QUICK_ACTIONS_SNAP_DOCK, QUICK_ACTIONS_SNAP_FULL, quickActionsScrollDirection, + quickActionsSnapAfterDismiss, + quickActionsSnapIsCollapsed, quickActionsSnapIsDock, quickActionsSnapIsFull, } from '@/lib/campaignQuickActionSnap' @@ -28,8 +30,10 @@ vi.mock('@/lib/campaignJsonRequest', () => ({ postCampaignJson: vi.fn(), })) +const pathnameState = vi.hoisted(() => ({ current: '/campanha/municipios/foo' })) + vi.mock('next/navigation', () => ({ - usePathname: () => '/campanha/municipios/foo', + usePathname: () => pathnameState.current, })) const idleSuggestPayload: HomeSearchSuccessResponse = { @@ -67,6 +71,7 @@ const searchWithPriorityPayload: HomeSearchSuccessResponse = { const matchMediaMock = vi.fn() beforeEach(() => { + pathnameState.current = '/campanha/municipios/foo' matchMediaMock.mockImplementation((query: string) => ({ matches: false, media: query, @@ -263,7 +268,7 @@ describe('CampaignQuickActionsDrawer (B105)', () => { expect(document.getElementById('quickActionContext')?.getAttribute('data-snap')).toBe('full') }) - it('stays full while search remains focused even if the handle collapses (B109)', () => { + it('handle with live query clears and collapses (B112)', async () => { vi.mocked(postCampaignJson).mockResolvedValue({ ok: true, payload: idleSuggestPayload, @@ -271,9 +276,110 @@ describe('CampaignQuickActionsDrawer (B105)', () => { renderQuickActionsChrome() - fireEvent.focus(screen.getByLabelText('Buscar na campanha')) - fireEvent.click(screen.getByRole('button', { name: 'Ocultar ações rápidas' })) + const input = screen.getByLabelText('Buscar na campanha') + fireEvent.focus(input) + fireEvent.change(input, { target: { value: 'cairu' } }) + + await waitFor(() => { + expect((input as HTMLInputElement).value).toBe('cairu') + }) expect(document.getElementById('quickActionContext')?.getAttribute('data-snap')).toBe('full') + + fireEvent.click(screen.getByRole('button', { name: 'Ocultar ações rápidas' })) + expect(document.getElementById('quickActionContext')?.getAttribute('data-snap')).toBe( + 'collapsed', + ) + expect((screen.getByLabelText('Buscar na campanha') as HTMLInputElement).value).toBe('') + }) + + it('empty blur collapses; blur with text stays full (B112)', async () => { + vi.mocked(postCampaignJson).mockResolvedValue({ + ok: true, + payload: idleSuggestPayload, + }) + + renderQuickActionsChrome() + + const input = screen.getByLabelText('Buscar na campanha') + fireEvent.focus(input) + expect(document.getElementById('quickActionContext')?.getAttribute('data-snap')).toBe('full') + + fireEvent.blur(input) + expect(document.getElementById('quickActionContext')?.getAttribute('data-snap')).toBe( + 'collapsed', + ) + + fireEvent.focus(input) + fireEvent.change(input, { target: { value: 'ca' } }) + await waitFor(() => { + expect((input as HTMLInputElement).value).toBe('ca') + }) + expect(document.getElementById('quickActionContext')?.getAttribute('data-snap')).toBe('full') + + fireEvent.blur(input) + expect(document.getElementById('quickActionContext')?.getAttribute('data-snap')).toBe('full') + expect((input as HTMLInputElement).value).toBe('ca') + }) + + it('in-chrome pathname update clears and collapses without remounting providers (B112)', async () => { + vi.mocked(postCampaignJson).mockResolvedValue({ + ok: true, + payload: idleSuggestPayload, + }) + + const { rerender } = render( + + + + + + + + + , + ) + + const input = screen.getByLabelText('Buscar na campanha') + fireEvent.focus(input) + fireEvent.change(input, { target: { value: 'cairu' } }) + await waitFor(() => { + expect((input as HTMLInputElement).value).toBe('cairu') + }) + expect(document.getElementById('quickActionContext')?.getAttribute('data-snap')).toBe('full') + + pathnameState.current = '/campanha/liderancas/1' + rerender( + + + + + + + + + , + ) + + expect(document.getElementById('quickActionContext')?.getAttribute('data-snap')).toBe( + 'collapsed', + ) + expect((screen.getByLabelText('Buscar na campanha') as HTMLInputElement).value).toBe('') + }) + + it('uses compact bottom stack spacing in the drawer (B112)', () => { + vi.mocked(postCampaignJson).mockResolvedValue({ + ok: true, + payload: idleSuggestPayload, + }) + + renderQuickActionsChrome() + + const context = document.getElementById('quickActionContext') + expect(context?.className).toContain('gap-1') + expect(context?.className).toContain('pb-[max(0.25rem,env(safe-area-inset-bottom,0px))]') + + const searchStack = document.querySelector('[data-slot="home-search-results"]')?.parentElement + expect(searchStack?.className).toContain('gap-1.5') }) it('toggles between dock and collapsed from the handle', () => { @@ -356,13 +462,15 @@ describe('CampaignContentScroll quick-actions direction (B105)', () => { }) describe('campaignQuickActionSnap', () => { - it('detects dock and full snaps', () => { + it('detects dock, full, and collapsed snaps', () => { expect(quickActionsSnapIsDock(QUICK_ACTIONS_SNAP_DOCK)).toBe(true) expect(quickActionsSnapIsDock(QUICK_ACTIONS_SNAP_COLLAPSED)).toBe(false) expect(quickActionsSnapIsDock(QUICK_ACTIONS_SNAP_FULL)).toBe(false) expect(quickActionsSnapIsDock(null)).toBe(false) expect(quickActionsSnapIsFull(QUICK_ACTIONS_SNAP_FULL)).toBe(true) expect(quickActionsSnapIsFull(QUICK_ACTIONS_SNAP_DOCK)).toBe(false) + expect(quickActionsSnapIsCollapsed(QUICK_ACTIONS_SNAP_COLLAPSED)).toBe(true) + expect(quickActionsSnapAfterDismiss()).toBe(QUICK_ACTIONS_SNAP_COLLAPSED) }) it('resolves scroll direction from delta threshold', () => {