Merge pull request #197 from fsolla/cursor/pool-i193-276cd535-d0f3

B112 — Bottom drawer — colapso (blur vazio / nav / handle), swipe ↓ e padding ⅓
This commit is contained in:
Francisco Solla 2026-08-01 21:10:26 -03:00 committed by GitHub
commit f4823c1436
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 225 additions and 52 deletions

View file

@ -1,6 +1,6 @@
# Bottom drawer — colapso (blur vazio / nav / handle), swipe ↓ e padding inferior
Status: registrado
Status: implementado (PR)
Atualizado em: 2026-08-01
Issue: #193
Priority: P0

View file

@ -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 (
<div className="flex w-full min-w-0 flex-col gap-4">
<div className={cn('flex w-full min-w-0 flex-col', compactStack ? 'gap-1.5' : 'gap-4')}>
<CampaignSearchInput
id={HOME_SEARCH_INPUT_ID}
label={HOME_SEARCH_LABEL}
@ -37,7 +48,7 @@ export const CampaignHomeSearch = ({
onChange={(event) => setRaw(event.target.value)}
onFocus={() => setInputFocused(true)}
onBlur={() => {
if (!query.isActive) {
if (homeSearchShouldUnfocusOnBlur(query.raw, blurUnfocusPolicy, query.isActive)) {
setInputFocused(false)
}
}}

View file

@ -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}
>
<HomeSearchResultsProvider value={searchResultsState}>
<HomeSearchResultsShell>

View file

@ -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
@ -123,13 +140,9 @@ export const CampaignQuickActionsDrawer = ({
<div
id="quickActionContext"
className={cn(
'flex min-h-0 flex-col overflow-y-auto px-4',
isFull
? 'flex-1 gap-2 pb-[max(0.25rem,env(safe-area-inset-bottom,0px))]'
: cn(
'gap-2 pb-[max(0.25rem,env(safe-area-inset-bottom,0px))]',
isDock ? 'flex-1' : 'shrink-0',
),
// B112 — dock/collapsed bottom gap ≈ ⅓ of prior gap-2 (keep safe-area).
'flex min-h-0 flex-col gap-1 overflow-y-auto px-4 pb-[max(0.25rem,env(safe-area-inset-bottom,0px))]',
isFull || isDock ? 'flex-1' : 'shrink-0',
)}
data-snap={isFull ? 'full' : isDock ? 'dock' : 'collapsed'}
>
@ -151,6 +164,8 @@ export const CampaignQuickActionsDrawer = ({
<CampaignGlobalSearchBody
placeholder={isDock || isFull ? undefined : ''}
showResults={showSearchResults}
blurUnfocusPolicy="whenEmpty"
compactStack
/>
</HomeSearchExcludeProvider>
</div>

View file

@ -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<CampaignQuickActionsSnapCo
)
export const CampaignQuickActionsSnapProvider = ({ children }: { children: ReactNode }) => {
const pathname = usePathname()
// B112 — load = dock; pathname collapse lives in the drawer (needs `clear`).
const [snapPoint, setSnapPoint] = useState<QuickActionsSnapPoint | null>(QUICK_ACTIONS_SNAP_DOCK)
useEffect(() => {
setSnapPoint(QUICK_ACTIONS_SNAP_DOCK)
}, [pathname])
const value = useMemo(
(): CampaignQuickActionsSnapContextValue => ({
snapPoint,

View file

@ -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

View file

@ -29,6 +29,13 @@ export const quickActionsSnapIsFull = (snap: QuickActionsSnapPoint | null): bool
export const quickActionsSnapIsDock = (snap: QuickActionsSnapPoint | null): boolean =>
snap === QUICK_ACTIONS_SNAP_DOCK
/**
* 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,

View file

@ -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)
})
})

View file

@ -20,6 +20,7 @@ import {
QUICK_ACTIONS_SNAP_DOCK,
QUICK_ACTIONS_SNAP_FULL,
quickActionsScrollDirection,
quickActionsSnapAfterDismiss,
quickActionsSnapIsDock,
quickActionsSnapIsFull,
} from '@/lib/campaignQuickActionSnap'
@ -28,8 +29,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 +70,7 @@ const searchWithPriorityPayload: HomeSearchSuccessResponse = {
const matchMediaMock = vi.fn()
beforeEach(() => {
pathnameState.current = '/campanha/municipios/foo'
matchMediaMock.mockImplementation((query: string) => ({
matches: false,
media: query,
@ -263,7 +267,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 +275,110 @@ describe('CampaignQuickActionsDrawer (B105)', () => {
renderQuickActionsChrome(<CampaignQuickActionsDrawer actions={[]} />)
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(<CampaignQuickActionsDrawer actions={[]} />)
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(
<TooltipProvider delayDuration={300}>
<CampaignQuickActionContextProvider>
<CampaignQuickActionsSnapProvider>
<CampaignGlobalSearchProvider>
<CampaignQuickActionsDrawer actions={[]} />
</CampaignGlobalSearchProvider>
</CampaignQuickActionsSnapProvider>
</CampaignQuickActionContextProvider>
</TooltipProvider>,
)
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(
<TooltipProvider delayDuration={300}>
<CampaignQuickActionContextProvider>
<CampaignQuickActionsSnapProvider>
<CampaignGlobalSearchProvider>
<CampaignQuickActionsDrawer actions={[]} />
</CampaignGlobalSearchProvider>
</CampaignQuickActionsSnapProvider>
</CampaignQuickActionContextProvider>
</TooltipProvider>,
)
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(<CampaignQuickActionsDrawer actions={[]} />)
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 +461,14 @@ describe('CampaignContentScroll quick-actions direction (B105)', () => {
})
describe('campaignQuickActionSnap', () => {
it('detects dock and full snaps', () => {
it('detects dock and full snaps; dismiss lands collapsed', () => {
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(quickActionsSnapAfterDismiss()).toBe(QUICK_ACTIONS_SNAP_COLLAPSED)
})
it('resolves scroll direction from delta threshold', () => {