mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
Merge pull request #222 from fsolla/cursor/pool-i207-c1261790-1012
B120 — Municípios mobile — filtro combobox + densificar lista
This commit is contained in:
commit
d8b8e78a12
13 changed files with 763 additions and 289 deletions
|
|
@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
|||
|
||||
---
|
||||
|
||||
**Recently resolved (2026-08-02):** **B120** (Issue #207) — municípios mobile: combobox multi-filtro (chips + typeahead) no lugar da pilha NativeSelect; overview KPI + aviso de sort só em `md+`; cards densificados (cobertura/nível + controles compactos). URL B18 intacta. Plano: [`municipios-mobile-filtro-combobox-densificar.md`](docs/plans/municipios-mobile-filtro-combobox-densificar.md).
|
||||
|
||||
**Recently resolved (2026-08-02):** **OH10** (Issue #171) — writes municipality staff CAS (`baseUpdatedAt`) + outbox irmão (`opsMunicipalityOutbox`) para municipalityUpdate, declareVotes, tendência, engagement e advisors; flag OFF mantém caminhos actuais. Plano: [`oh10-municipality-writes-cas.md`](docs/plans/oh10-municipality-writes-cas.md).
|
||||
|
||||
**Recently resolved (2026-08-02):** **OH9** (Issue #172) — detalhe de município dual-path: `MunicipalityDetailHeaderView` partilhado; `OfflineBoundary` (SSR=RSC; offline+`OPS_HYBRID`→Local); `MunicipalityDetailLocal` lê mirror (município + pledges×leaderships); regiões online-only com “Disponível quando estiveres online.”; e2e `campaignOpsOffline` (skip sem flag). Plano: [`oh9-municipio-detalhe-dualpath.md`](docs/plans/oh9-municipio-detalhe-dualpath.md).
|
||||
|
|
|
|||
|
|
@ -1,13 +1,28 @@
|
|||
# Municípios mobile — filtro combobox + densificar lista
|
||||
|
||||
Status: ready
|
||||
Atualizado em: 2026-08-01
|
||||
Status: implemented
|
||||
Atualizado em: 2026-08-02
|
||||
Issue: #207
|
||||
Priority: P1
|
||||
Model: cursor-grok-4.5-medium
|
||||
Impeccable: C — UI nova do filtro + critique do card (lista existente)
|
||||
Appetite: ~2 dias eng; combobox multi-filtro + remoções + critique/polish do card; URL B18 intacta; sem migration
|
||||
Responsável: —
|
||||
Responsável: pool worker
|
||||
|
||||
## Freshness audit (2026-08-02)
|
||||
|
||||
- Arquivos citados existem; `municipalityFilterDefinitions` / toggles / `useCampaignListFilterNavigation` / `StrictCombobox`+`ui/combobox` intactos.
|
||||
- B119 (`#206`) done+in-prod — hit-target `relative` no `CampaignCellEditOverlay` já verde.
|
||||
- B118 ainda in-progress — soft serialize; este item **não** remove o h1 (fica com B118).
|
||||
- Overview no desktop: manter `md+` (recomendação A).
|
||||
- Sem migration / schema.
|
||||
|
||||
## Entrega
|
||||
|
||||
- Mobile: `MunicipalityMobileFilterCombobox` (Filter + chips + typeahead) sobre B18.
|
||||
- Overview KPI + sort notice: `hidden` <md.
|
||||
- Cards densificados (cobertura/nível + controles; sem Classe/2022).
|
||||
- Pins unit: chip/URL round-trip; filter navigation atualizado.
|
||||
|
||||
## Design (Impeccable)
|
||||
|
||||
|
|
|
|||
|
|
@ -129,9 +129,12 @@ export default async function MunicipalitiesPage({ searchParams }: Municipalitie
|
|||
|
||||
// The overview and the table's filter header stay mounted even with zero
|
||||
// results — only the rows are replaced by the empty state (inside MunicipalityList).
|
||||
// B120: hide the KPI strip on mobile (viewport budget); keep it on md+.
|
||||
const overviewNode =
|
||||
isStaffView && overview ? (
|
||||
<MunicipalityListOverview view={overview} shameHref={shameHref} />
|
||||
<div className="hidden md:block">
|
||||
<MunicipalityListOverview view={overview} shameHref={shameHref} />
|
||||
</div>
|
||||
) : null
|
||||
|
||||
const tableNode = (
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
'use client'
|
||||
|
||||
import { useMunicipalityEstimateScenario } from '@/components/campaign/municipality/MunicipalityEstimateScenarioContext'
|
||||
import { MunicipalityMobileFilterCombobox } from '@/components/campaign/municipality/MunicipalityMobileFilterCombobox'
|
||||
import { SaveMunicipalityFilterControl } from '@/components/campaign/municipality/SaveMunicipalityFilterControl'
|
||||
import { CampaignMobileMultiFilterField } from '@/components/campaign/shared/CampaignMobileMultiFilterField'
|
||||
import { CampaignSearchInput } from '@/components/campaign/shared/CampaignSearchInput'
|
||||
import { useCampaignListFilterNavigation } from '@/components/campaign/shared/useCampaignListFilterNavigation'
|
||||
import {
|
||||
|
|
@ -10,26 +10,13 @@ import {
|
|||
VoteEstimateScenarioField,
|
||||
} from '@/components/campaign/votePledge/VoteEstimateScenarioField'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Field, FieldLabel } from '@/components/ui/field'
|
||||
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||
import {
|
||||
buildMunicipalityFilterHref,
|
||||
clearMunicipalityListFilters,
|
||||
formatMunicipalityActiveFiltersSummary,
|
||||
getMunicipalityMultiFilterValues,
|
||||
municipalityFilterDefinitions,
|
||||
toggleMunicipalityExclusiveFilterValue,
|
||||
toggleMunicipalityMultiFilterValue,
|
||||
type MunicipalityFilterOption,
|
||||
type MunicipalityMultiFilterParam,
|
||||
} from '@/utilities/municipality/municipalityListFilters'
|
||||
import {
|
||||
municipalityListSortOptions,
|
||||
parseMunicipalitySortValue,
|
||||
resolveMunicipalityListSort,
|
||||
serializeMunicipalitySortValue,
|
||||
type MunicipalityListState,
|
||||
} from '@/utilities/municipality/municipalityListUrl'
|
||||
import type { MunicipalityListState } from '@/utilities/municipality/municipalityListUrl'
|
||||
|
||||
const MunicipalityFilterEstimateScenario = ({
|
||||
className,
|
||||
|
|
@ -65,21 +52,21 @@ export const MunicipalityFilters = ({
|
|||
regionFilterOptions,
|
||||
advisorFilterOptions,
|
||||
}: MunicipalityFiltersProps) => {
|
||||
const { search, onSearchChange, draftQ, isPending, navigateWithSearch, clearSearchAndNavigate } =
|
||||
useCampaignListFilterNavigation({ state, toHref: buildMunicipalityFilterHref })
|
||||
const { sort: activeSort, dir: activeDir } = resolveMunicipalityListSort(state)
|
||||
const {
|
||||
search,
|
||||
setSearch,
|
||||
onSearchChange,
|
||||
draftQ,
|
||||
isPending,
|
||||
navigateWithSearch,
|
||||
clearSearchAndNavigate,
|
||||
} = useCampaignListFilterNavigation({ state, toHref: buildMunicipalityFilterHref })
|
||||
const activeFiltersSummary = formatMunicipalityActiveFiltersSummary({
|
||||
...state,
|
||||
q: draftQ,
|
||||
})
|
||||
const hasActiveFilters = Boolean(activeFiltersSummary)
|
||||
|
||||
const mobileFilterDefinitions = municipalityFilterDefinitions.filter((definition) => {
|
||||
if (definition.staffOnly && !showStaffFilters) return false
|
||||
if (definition.param === 'name') return false
|
||||
return true
|
||||
})
|
||||
|
||||
return (
|
||||
<form
|
||||
role="search"
|
||||
|
|
@ -91,7 +78,24 @@ export const MunicipalityFilters = ({
|
|||
navigateWithSearch(state)
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-end">
|
||||
{/* B120 — mobile: one combobox (chips + typeahead) replaces the NativeSelect stack. */}
|
||||
<div className="md:hidden">
|
||||
<MunicipalityMobileFilterCombobox
|
||||
id="municipality-mobile-filter"
|
||||
state={state}
|
||||
showStaffFilters={showStaffFilters}
|
||||
regionFilterOptions={regionFilterOptions}
|
||||
advisorFilterOptions={advisorFilterOptions}
|
||||
search={search}
|
||||
onSearchChange={onSearchChange}
|
||||
clearSearchBox={() => setSearch('')}
|
||||
onNavigate={navigateWithSearch}
|
||||
onNavigateClearingSearch={clearSearchAndNavigate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Desktop: search + summary + scenario; column filters stay on table heads (B16). */}
|
||||
<div className="hidden flex-col gap-3 md:flex md:flex-row md:items-end">
|
||||
<CampaignSearchInput
|
||||
id="municipality-search"
|
||||
label="Buscar município"
|
||||
|
|
@ -100,152 +104,32 @@ export const MunicipalityFilters = ({
|
|||
onChange={(event) => onSearchChange(event.target.value)}
|
||||
/>
|
||||
{activeFiltersSummary ? (
|
||||
<p className="hidden min-w-0 flex-1 text-sm text-muted-foreground md:block md:self-center md:pb-2 md:whitespace-normal">
|
||||
<p className="min-w-0 flex-1 text-sm text-muted-foreground md:self-center md:pb-2 md:whitespace-normal">
|
||||
{activeFiltersSummary}
|
||||
</p>
|
||||
) : null}
|
||||
{showStaffFilters ? (
|
||||
<MunicipalityFilterEstimateScenario
|
||||
id="municipality-filter-estimate-scenario"
|
||||
className="hidden shrink-0 md:block md:self-end"
|
||||
className="shrink-0 md:self-end"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Shared actions — one Limpar/Salvar for both breakpoints (B120 / B18). */}
|
||||
<div className="flex flex-wrap gap-2 md:items-end">
|
||||
<SaveMunicipalityFilterControl state={state} />
|
||||
{hasActiveFilters ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="min-h-11 shrink-0 md:self-end"
|
||||
className="min-h-11 shrink-0"
|
||||
onClick={() => clearSearchAndNavigate(clearMunicipalityListFilters(state))}
|
||||
>
|
||||
Limpar
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 md:hidden">
|
||||
{activeFiltersSummary ? (
|
||||
<p className="text-sm text-muted-foreground">{activeFiltersSummary}</p>
|
||||
) : null}
|
||||
{showStaffFilters ? (
|
||||
<Field>
|
||||
<FieldLabel htmlFor="municipality-filter-priority">Prioridade</FieldLabel>
|
||||
<NativeSelect
|
||||
id="municipality-filter-priority"
|
||||
value={state.priority ?? ''}
|
||||
onChange={(event) => {
|
||||
navigateWithSearch({
|
||||
...state,
|
||||
priority: event.target.value === 'alta' ? 'alta' : undefined,
|
||||
})
|
||||
}}
|
||||
className="min-h-11 w-full"
|
||||
>
|
||||
<NativeSelectOption value="">Todas</NativeSelectOption>
|
||||
<NativeSelectOption value="alta">Prioritária</NativeSelectOption>
|
||||
</NativeSelect>
|
||||
</Field>
|
||||
) : null}
|
||||
{mobileFilterDefinitions.map((definition) => {
|
||||
if (definition.selection === 'multi') {
|
||||
let options = definition.options ?? []
|
||||
if (definition.param === 'region') options = regionFilterOptions
|
||||
if (definition.param === 'advisor') options = advisorFilterOptions
|
||||
|
||||
if (options.length === 0) return null
|
||||
|
||||
let selected: string[] = []
|
||||
if (definition.param !== 'region' && definition.param !== 'advisor') {
|
||||
selected = getMunicipalityMultiFilterValues(
|
||||
state,
|
||||
definition.param as MunicipalityMultiFilterParam,
|
||||
)
|
||||
} else if (definition.param === 'region') {
|
||||
selected = state.regions ?? []
|
||||
} else if (definition.param === 'advisor') {
|
||||
selected = (state.advisors ?? []).map(String)
|
||||
}
|
||||
|
||||
return (
|
||||
<CampaignMobileMultiFilterField
|
||||
key={definition.param}
|
||||
id={`municipality-filter-${definition.param}`}
|
||||
label={definition.label}
|
||||
emptyLabel={definition.emptyLabel ?? 'Todos'}
|
||||
options={options}
|
||||
selected={selected}
|
||||
onToggle={(value) =>
|
||||
navigateWithSearch(
|
||||
toggleMunicipalityMultiFilterValue(
|
||||
state,
|
||||
definition.param as MunicipalityMultiFilterParam,
|
||||
value,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const value = definition.param === 'coverage' ? (state.coverage ?? '') : ''
|
||||
return (
|
||||
<Field key={definition.param}>
|
||||
<FieldLabel htmlFor={`municipality-filter-${definition.param}`}>
|
||||
{definition.label}
|
||||
</FieldLabel>
|
||||
<NativeSelect
|
||||
id={`municipality-filter-${definition.param}`}
|
||||
value={value}
|
||||
onChange={(event) => {
|
||||
const selected = event.target.value
|
||||
if (definition.selection === 'toggle') {
|
||||
navigateWithSearch(
|
||||
selected
|
||||
? toggleMunicipalityExclusiveFilterValue(state, 'coverage', selected)
|
||||
: { ...state, coverage: undefined },
|
||||
)
|
||||
}
|
||||
}}
|
||||
className="min-h-11 w-full"
|
||||
>
|
||||
<NativeSelectOption value="">{definition.allLabel ?? 'Todas'}</NativeSelectOption>
|
||||
{(definition.options ?? []).map((option) => (
|
||||
<NativeSelectOption key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</NativeSelectOption>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Field>
|
||||
)
|
||||
})}
|
||||
{showStaffFilters ? (
|
||||
<MunicipalityFilterEstimateScenario
|
||||
id="municipality-filter-estimate-scenario-mobile"
|
||||
className="md:hidden"
|
||||
/>
|
||||
) : null}
|
||||
<Field>
|
||||
<FieldLabel htmlFor="municipality-sort">Ordenar</FieldLabel>
|
||||
<NativeSelect
|
||||
id="municipality-sort"
|
||||
value={serializeMunicipalitySortValue(activeSort, activeDir)}
|
||||
onChange={(event) => {
|
||||
const parsed = parseMunicipalitySortValue(event.target.value)
|
||||
if (parsed) navigateWithSearch({ ...state, sort: parsed.key, dir: parsed.dir })
|
||||
}}
|
||||
className="min-h-11 w-full"
|
||||
>
|
||||
{municipalityListSortOptions.map(({ key, dir, label }) => (
|
||||
<NativeSelectOption
|
||||
key={serializeMunicipalitySortValue(key, dir)}
|
||||
value={serializeMunicipalitySortValue(key, dir)}
|
||||
>
|
||||
{label}
|
||||
</NativeSelectOption>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</Field>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -430,7 +430,9 @@ export const MunicipalityList = (props: MunicipalityListProps) => {
|
|||
|
||||
return (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground" aria-live="polite">
|
||||
{/* B120: mobile drops the sort notice (combobox carries sort); desktop keeps
|
||||
the live region + table caption. */}
|
||||
<p className="hidden text-sm text-muted-foreground md:block" aria-live="polite">
|
||||
{sortSummary}
|
||||
</p>
|
||||
|
||||
|
|
|
|||
|
|
@ -12,18 +12,13 @@ import { MunicipalityListAdvisorsControl } from '@/components/campaign/municipal
|
|||
import { MunicipalityListExpectedVotesControl } from '@/components/campaign/municipality/MunicipalityListExpectedVotesControl'
|
||||
import { MunicipalityListGoalCoverageCell } from '@/components/campaign/municipality/MunicipalityListGoalCoverageCell'
|
||||
import { MunicipalityListLevelControl } from '@/components/campaign/municipality/MunicipalityListLevelControl'
|
||||
import {
|
||||
SignalAgeReadout,
|
||||
TerritorialClassCardReadout,
|
||||
} from '@/components/campaign/municipality/MunicipalityListRowReadouts'
|
||||
import { SignalAgeReadout } from '@/components/campaign/municipality/MunicipalityListRowReadouts'
|
||||
import { MunicipalityListSignalControl } from '@/components/campaign/municipality/MunicipalityListSignalControl'
|
||||
import { MunicipalityListTrendControl } from '@/components/campaign/municipality/MunicipalityListTrendControl'
|
||||
import { MunicipalityPriorityIndicator } from '@/components/campaign/municipality/MunicipalityPriorityIndicator'
|
||||
import { MunicipalityVotePositionReadout } from '@/components/campaign/municipality/MunicipalityVotePositionReadout'
|
||||
import { TerritoryLink } from '@/components/campaign/municipality/TerritoryLink'
|
||||
import type { CampaignFormActionState } from '@/utilities/campaignFormActionError'
|
||||
import { municipalityGeographyParts } from '@/utilities/municipality/municipalityLabels'
|
||||
import { municipalityColumnLabels } from '@/utilities/municipality/municipalityListUrl'
|
||||
import type {
|
||||
EligibleAdvisorOption,
|
||||
MunicipalityAdvisorSummary,
|
||||
|
|
@ -48,8 +43,9 @@ export type MunicipalityListMobileCardsProps = {
|
|||
}
|
||||
|
||||
/**
|
||||
* B42 mobile cards with sheet-variant quick edits. Wrapped by
|
||||
* `MunicipalityListMobileSection`, which hosts a single shared Drawer.
|
||||
* B42 mobile cards densified by B120: name + territory, one coverage/level line,
|
||||
* then a compact row of edit-in-place controls. Classe and 2022 position live on
|
||||
* the detail — they don't change "open or act" on the list.
|
||||
*/
|
||||
export const MunicipalityListMobileCards = ({
|
||||
municipalities,
|
||||
|
|
@ -61,23 +57,22 @@ export const MunicipalityListMobileCards = ({
|
|||
signalFormAction,
|
||||
emptySlot,
|
||||
}: MunicipalityListMobileCardsProps) => (
|
||||
<div data-view="mobile-cards" className="flex flex-col gap-4 md:hidden">
|
||||
<div data-view="mobile-cards" className="flex flex-col gap-2.5 md:hidden">
|
||||
{municipalities.length === 0 ? emptySlot : null}
|
||||
{municipalities.map((municipality) => {
|
||||
const names = advisorEntriesFromIds(municipality.advisorIDs, advisorNamesById).map(
|
||||
(advisor) => advisor.name,
|
||||
)
|
||||
const position = municipality.votePosition2022
|
||||
const isPriority = municipality.priority === 'alta'
|
||||
const { region, zoneSuffix } = municipalityGeographyParts(municipality)
|
||||
return (
|
||||
<article
|
||||
key={municipality.id}
|
||||
className="relative flex flex-col gap-3 rounded-xl border p-4"
|
||||
className="relative flex flex-col gap-2 rounded-xl border px-3 py-2.5"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h3 className="font-medium">
|
||||
<div className="min-w-0 flex flex-col gap-0.5">
|
||||
<h3 className="font-medium leading-snug">
|
||||
<Link
|
||||
href={`/campanha/municipios/${municipality.slug}`}
|
||||
className="rounded-md after:absolute after:inset-0 after:rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
|
|
@ -91,45 +86,21 @@ export const MunicipalityListMobileCards = ({
|
|||
</span>
|
||||
{zoneSuffix ? ` ${zoneSuffix}` : null}
|
||||
</p>
|
||||
{position ? (
|
||||
<MunicipalityVotePositionReadout position={position} layout="card" />
|
||||
) : null}
|
||||
</div>
|
||||
{isPriority && isStaffView ? (
|
||||
<MunicipalityPriorityIndicator className="relative size-11" />
|
||||
<MunicipalityPriorityIndicator className="relative size-11 shrink-0" />
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{isStaffView ? (
|
||||
<dl className="grid grid-cols-2 gap-2 text-sm">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Classe</dt>
|
||||
<dd className="flex flex-wrap items-center gap-2">
|
||||
<TerritorialClassCardReadout municipality={municipality} />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">{municipalityColumnLabels.goalCoverage}</dt>
|
||||
<dd>
|
||||
<>
|
||||
<div className="relative flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
|
||||
<div className="min-w-0">
|
||||
<MunicipalityListGoalCoverageCell
|
||||
coverageByScenario={municipality.goalCoverageByScenario}
|
||||
/>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Votos estimados</dt>
|
||||
<dd>
|
||||
<MunicipalityListExpectedVotesControl
|
||||
municipalityID={municipality.id}
|
||||
municipalityName={municipality.name}
|
||||
expectedVotes={municipality.expectedVotes}
|
||||
pledgeCoverage={toMunicipalityPledgeCoverageView(municipality.pledges)}
|
||||
variant="sheet"
|
||||
/>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<dt className="text-muted-foreground">Nível</dt>
|
||||
<dd>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
{canMoveEngagementLevel ? (
|
||||
<MunicipalityListLevelControl
|
||||
municipalityID={municipality.id}
|
||||
|
|
@ -147,58 +118,57 @@ export const MunicipalityListMobileCards = ({
|
|||
layout="card"
|
||||
/>
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Tendência</dt>
|
||||
<dd>
|
||||
<MunicipalityListTrendControl
|
||||
|
||||
<div className="relative flex flex-wrap items-center gap-1">
|
||||
<MunicipalityListTrendControl
|
||||
municipalityID={municipality.id}
|
||||
municipalityName={municipality.name}
|
||||
status={municipality.politicalTrendStatus}
|
||||
trendNote={municipality.politicalTrendNote}
|
||||
updatedAt={municipality.updatedAt}
|
||||
variant="sheet"
|
||||
/>
|
||||
<MunicipalityListExpectedVotesControl
|
||||
municipalityID={municipality.id}
|
||||
municipalityName={municipality.name}
|
||||
expectedVotes={municipality.expectedVotes}
|
||||
pledgeCoverage={toMunicipalityPledgeCoverageView(municipality.pledges)}
|
||||
variant="sheet"
|
||||
/>
|
||||
<MunicipalityListSignalControl
|
||||
municipalityID={municipality.id}
|
||||
municipalitySlug={municipality.slug}
|
||||
municipalityName={municipality.name}
|
||||
lastSignalAt={municipality.lastSignalAt}
|
||||
variant="sheet"
|
||||
formAction={signalFormAction}
|
||||
>
|
||||
<SignalAgeReadout lastSignalAt={municipality.lastSignalAt} layout="card" />
|
||||
</MunicipalityListSignalControl>
|
||||
{isCoordinator ? (
|
||||
<MunicipalityListAdvisorsControl
|
||||
municipalityID={municipality.id}
|
||||
municipalityName={municipality.name}
|
||||
status={municipality.politicalTrendStatus}
|
||||
trendNote={municipality.politicalTrendNote}
|
||||
currentAdvisorIDs={municipality.advisorIDs}
|
||||
isPriority={isPriority}
|
||||
advisorNamesById={advisorNamesById}
|
||||
options={advisorOptions}
|
||||
updatedAt={municipality.updatedAt}
|
||||
variant="sheet"
|
||||
/>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Último sinal</dt>
|
||||
<dd>
|
||||
<MunicipalityListSignalControl
|
||||
municipalityID={municipality.id}
|
||||
municipalitySlug={municipality.slug}
|
||||
municipalityName={municipality.name}
|
||||
lastSignalAt={municipality.lastSignalAt}
|
||||
variant="sheet"
|
||||
formAction={signalFormAction}
|
||||
>
|
||||
<SignalAgeReadout lastSignalAt={municipality.lastSignalAt} layout="card" />
|
||||
</MunicipalityListSignalControl>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Assessores</dt>
|
||||
<dd>
|
||||
{isCoordinator ? (
|
||||
<MunicipalityListAdvisorsControl
|
||||
municipalityID={municipality.id}
|
||||
municipalityName={municipality.name}
|
||||
currentAdvisorIDs={municipality.advisorIDs}
|
||||
isPriority={isPriority}
|
||||
advisorNamesById={advisorNamesById}
|
||||
options={advisorOptions}
|
||||
updatedAt={municipality.updatedAt}
|
||||
variant="sheet"
|
||||
/>
|
||||
) : names.length ? (
|
||||
names.join(', ')
|
||||
) : (
|
||||
) : names.length ? (
|
||||
<span className="relative px-1 text-sm text-muted-foreground">
|
||||
{names.join(', ')}
|
||||
</span>
|
||||
) : (
|
||||
<span className="relative">
|
||||
<MissingAdvisorBadge isPriority={isPriority} />
|
||||
)}
|
||||
</dd>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</dl>
|
||||
</>
|
||||
) : null}
|
||||
</article>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
import { CircleAlertIcon } from 'lucide-react'
|
||||
|
||||
import { CampaignHoverTooltip } from '@/components/campaign/shared/CampaignHoverTooltip'
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
|
|
@ -20,7 +19,7 @@ import type { MunicipalityListViewModel } from '@/utilities/municipality/municip
|
|||
|
||||
const dateFormatter = new Intl.DateTimeFormat('pt-BR')
|
||||
|
||||
/** E10 classe readout — shared by the table column and the mobile card (B42). */
|
||||
/** E10 classe readout — table column (mobile card dropped classe in B120). */
|
||||
export const TerritorialClassReadout = ({
|
||||
municipality,
|
||||
}: {
|
||||
|
|
@ -85,22 +84,3 @@ export const SignalAgeReadout = ({
|
|||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const TerritorialClassCardReadout = ({
|
||||
municipality,
|
||||
}: {
|
||||
municipality: MunicipalityListViewModel
|
||||
}) => (
|
||||
<CampaignHoverTooltip
|
||||
content={
|
||||
municipality.territorialClass === 'sem_base'
|
||||
? null
|
||||
: formatTerritorialClassWhy(municipality.territorialClassFactors)
|
||||
}
|
||||
align="start"
|
||||
>
|
||||
<span className="relative inline-flex items-center">
|
||||
<TerritorialClassReadout municipality={municipality} />
|
||||
</span>
|
||||
</CampaignHoverTooltip>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,167 @@
|
|||
'use client'
|
||||
|
||||
import { FilterIcon, XIcon } from 'lucide-react'
|
||||
|
||||
import { useMunicipalityEstimateScenarioOptional } from '@/components/campaign/municipality/MunicipalityEstimateScenarioContext'
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxContent,
|
||||
ComboboxEmpty,
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
} from '@/components/ui/combobox'
|
||||
import { InputGroupAddon } from '@/components/ui/input-group'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { DEFAULT_VOTE_ESTIMATE_SCENARIO } from '@/lib/voteEstimate'
|
||||
import { matchesAtWordStart, normalizeSearchPhrase } from '@/lib/wordStartFilter'
|
||||
import type { MunicipalityFilterOption } from '@/utilities/municipality/municipalityListFilters'
|
||||
import type { MunicipalityListState } from '@/utilities/municipality/municipalityListUrl'
|
||||
import {
|
||||
applyMunicipalityMobileFilterOption,
|
||||
buildMunicipalityMobileFilterChips,
|
||||
buildMunicipalityMobileFilterOptions,
|
||||
dismissMunicipalityMobileFilterChip,
|
||||
findMunicipalityMobileFilterOption,
|
||||
type MunicipalityMobileFilterOption,
|
||||
} from '@/utilities/municipality/municipalityMobileFilterCombobox'
|
||||
|
||||
type MunicipalityMobileFilterComboboxProps = {
|
||||
id: string
|
||||
state: MunicipalityListState
|
||||
showStaffFilters: boolean
|
||||
regionFilterOptions: MunicipalityFilterOption[]
|
||||
advisorFilterOptions: MunicipalityFilterOption[]
|
||||
search: string
|
||||
onSearchChange: (value: string) => void
|
||||
/** Clear the box without arming the search debounce / URL write. */
|
||||
clearSearchBox: () => void
|
||||
onNavigate: (next: MunicipalityListState) => void
|
||||
/** Drop draft search and navigate (option pick — typeahead text must not become `q`). */
|
||||
onNavigateClearingSearch: (next: MunicipalityListState) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* B120 — GitHub-style filter combobox for the municipalities list on mobile.
|
||||
* Chips + typeahead over B18 URL state; free text without a pick debounces to `q`.
|
||||
*/
|
||||
export const MunicipalityMobileFilterCombobox = ({
|
||||
id,
|
||||
state,
|
||||
showStaffFilters,
|
||||
regionFilterOptions,
|
||||
advisorFilterOptions,
|
||||
search,
|
||||
onSearchChange,
|
||||
clearSearchBox,
|
||||
onNavigate,
|
||||
onNavigateClearingSearch,
|
||||
}: MunicipalityMobileFilterComboboxProps) => {
|
||||
const scenarioContext = useMunicipalityEstimateScenarioOptional()
|
||||
const scenario = scenarioContext?.scenario ?? DEFAULT_VOTE_ESTIMATE_SCENARIO
|
||||
const setScenario = scenarioContext?.setScenario
|
||||
|
||||
const options = buildMunicipalityMobileFilterOptions({
|
||||
state,
|
||||
showStaffFilters,
|
||||
regionFilterOptions,
|
||||
advisorFilterOptions,
|
||||
scenario,
|
||||
})
|
||||
const chips = buildMunicipalityMobileFilterChips(state, options)
|
||||
// One scan per keystroke: when the draft matches no option label it is a name
|
||||
// search — keep the full catalog so a filter can still be picked.
|
||||
const normalizedDraft = normalizeSearchPhrase(search)
|
||||
const draftMatchesOption = normalizedDraft
|
||||
? options.some((option) => matchesAtWordStart(option.label, search))
|
||||
: false
|
||||
|
||||
const applyOption = (option: MunicipalityMobileFilterOption) => {
|
||||
const next = applyMunicipalityMobileFilterOption(state, option)
|
||||
if (next === 'scenario') {
|
||||
if (option.kind === 'scenario') setScenario?.(option.scenario)
|
||||
clearSearchBox()
|
||||
return
|
||||
}
|
||||
// Keep only the committed URL `q` — the box text may be a typeahead prefix
|
||||
// ("Prior", "Tendência"), not a município name. Drop the draft with Limpar's
|
||||
// clear path so the debounce cannot re-commit it after the pick.
|
||||
onNavigateClearingSearch({ ...next, q: state.q })
|
||||
}
|
||||
|
||||
const dismissChip = (chipId: string) => {
|
||||
const option = findMunicipalityMobileFilterOption(options, chipId)
|
||||
if (!option) return
|
||||
const next = dismissMunicipalityMobileFilterChip(state, option)
|
||||
if (next === 'scenario-default') {
|
||||
setScenario?.(DEFAULT_VOTE_ESTIMATE_SCENARIO)
|
||||
return
|
||||
}
|
||||
onNavigate(next)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
{chips.length > 0 ? (
|
||||
<ul className="flex flex-wrap gap-1.5" aria-label="Filtros ativos">
|
||||
{chips.map((chip) => (
|
||||
<li key={chip.id}>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-8 max-w-full items-center gap-1 rounded-md border border-border bg-muted/60 px-2 py-1 text-xs font-medium text-foreground"
|
||||
onClick={() => dismissChip(chip.id)}
|
||||
aria-label={`Remover filtro ${chip.label}`}
|
||||
>
|
||||
<span className="truncate">{chip.label}</span>
|
||||
<XIcon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
|
||||
<Combobox<MunicipalityMobileFilterOption>
|
||||
items={options}
|
||||
value={null}
|
||||
inputValue={search}
|
||||
onInputValueChange={onSearchChange}
|
||||
onValueChange={(option) => {
|
||||
if (option) applyOption(option)
|
||||
}}
|
||||
filter={(option, query) => {
|
||||
if (!query || !draftMatchesOption) return true
|
||||
return matchesAtWordStart(option.label, query)
|
||||
}}
|
||||
isItemEqualToValue={(left, right) => left?.id === right?.id}
|
||||
itemToStringLabel={(option) => option.label}
|
||||
>
|
||||
<ComboboxInput
|
||||
id={id}
|
||||
autoComplete="off"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
placeholder="Filtrar municípios…"
|
||||
aria-label="Filtrar municípios"
|
||||
showTrigger
|
||||
showClear={Boolean(search)}
|
||||
className={cn('min-h-11 w-full rounded-lg')}
|
||||
>
|
||||
<InputGroupAddon align="inline-start">
|
||||
<FilterIcon className="size-4 text-muted-foreground" aria-hidden="true" />
|
||||
</InputGroupAddon>
|
||||
</ComboboxInput>
|
||||
<ComboboxContent className="w-(--anchor-width)">
|
||||
<ComboboxEmpty>Nenhuma opção. Continue digitando para buscar por nome.</ComboboxEmpty>
|
||||
<ComboboxList>
|
||||
{(option: MunicipalityMobileFilterOption) => (
|
||||
<ComboboxItem key={option.id} value={option}>
|
||||
<span className="min-w-0 flex-1 truncate">{option.label}</span>
|
||||
{option.active ? <span className="sr-only"> (ativo)</span> : null}
|
||||
</ComboboxItem>
|
||||
)}
|
||||
</ComboboxList>
|
||||
</ComboboxContent>
|
||||
</Combobox>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -123,6 +123,12 @@ export const useCampaignListFilterNavigation = <State extends { q?: string }>({
|
|||
|
||||
return {
|
||||
search,
|
||||
/**
|
||||
* Raw box write with no debounce/navigation — used after a typeahead pick
|
||||
* so the URL can keep the committed `q` while the input is ready for the
|
||||
* next filter keyword.
|
||||
*/
|
||||
setSearch,
|
||||
onSearchChange,
|
||||
/**
|
||||
* What the active-filters summary should describe. The draft wins while the
|
||||
|
|
|
|||
263
src/utilities/municipality/municipalityMobileFilterCombobox.ts
Normal file
263
src/utilities/municipality/municipalityMobileFilterCombobox.ts
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
/**
|
||||
* Pure option/chip catalog for the mobile municipality filter combobox (B120).
|
||||
* URL contract stays in `municipalityListFilters` / `municipalityListUrl` (B18).
|
||||
*/
|
||||
import {
|
||||
DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
||||
VOTE_ESTIMATE_SCENARIOS,
|
||||
voteEstimateScenarioLabels,
|
||||
type VoteEstimateScenario,
|
||||
} from '@/lib/voteEstimate'
|
||||
import { municipalityPriorityLabels } from '@/utilities/municipality/municipalityLabels'
|
||||
import {
|
||||
getMunicipalityMultiFilterValues,
|
||||
municipalityFilterDefinitions,
|
||||
toggleMunicipalityExclusiveFilterValue,
|
||||
toggleMunicipalityMultiFilterValue,
|
||||
toggleMunicipalityPriorityFilter,
|
||||
type MunicipalityFilterOption,
|
||||
type MunicipalityMultiFilterParam,
|
||||
} from '@/utilities/municipality/municipalityListFilters'
|
||||
import {
|
||||
municipalityListSortOptions,
|
||||
resolveMunicipalityListSort,
|
||||
serializeMunicipalitySortValue,
|
||||
type MunicipalityListSortDirection,
|
||||
type MunicipalityListSortKey,
|
||||
type MunicipalityListState,
|
||||
} from '@/utilities/municipality/municipalityListUrl'
|
||||
|
||||
export type MunicipalityMobileFilterChip = {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export type MunicipalityMobileFilterOption =
|
||||
| {
|
||||
id: string
|
||||
kind: 'priority'
|
||||
label: string
|
||||
active: boolean
|
||||
}
|
||||
| {
|
||||
id: string
|
||||
kind: 'multi'
|
||||
label: string
|
||||
param: MunicipalityMultiFilterParam
|
||||
value: string
|
||||
active: boolean
|
||||
}
|
||||
| {
|
||||
id: string
|
||||
kind: 'coverage'
|
||||
label: string
|
||||
value: string
|
||||
active: boolean
|
||||
}
|
||||
| {
|
||||
id: string
|
||||
kind: 'sort'
|
||||
label: string
|
||||
sort: MunicipalityListSortKey
|
||||
dir: MunicipalityListSortDirection
|
||||
active: boolean
|
||||
}
|
||||
| {
|
||||
id: string
|
||||
kind: 'scenario'
|
||||
label: string
|
||||
scenario: VoteEstimateScenario
|
||||
active: boolean
|
||||
}
|
||||
|
||||
const dimensionLabel = (dimension: string, option: string): string => `${dimension} · ${option}`
|
||||
|
||||
export type BuildMunicipalityMobileFilterOptionsArgs = {
|
||||
state: MunicipalityListState
|
||||
showStaffFilters: boolean
|
||||
regionFilterOptions: MunicipalityFilterOption[]
|
||||
advisorFilterOptions: MunicipalityFilterOption[]
|
||||
/** Client-only estimate scenario (not in the URL). */
|
||||
scenario: VoteEstimateScenario
|
||||
}
|
||||
|
||||
export const buildMunicipalityMobileFilterOptions = ({
|
||||
state,
|
||||
showStaffFilters,
|
||||
regionFilterOptions,
|
||||
advisorFilterOptions,
|
||||
scenario,
|
||||
}: BuildMunicipalityMobileFilterOptionsArgs): MunicipalityMobileFilterOption[] => {
|
||||
const options: MunicipalityMobileFilterOption[] = []
|
||||
const { sort: activeSort, dir: activeDir } = resolveMunicipalityListSort(state)
|
||||
|
||||
if (showStaffFilters) {
|
||||
options.push({
|
||||
id: 'priority:alta',
|
||||
kind: 'priority',
|
||||
label: dimensionLabel('Prioridade', municipalityPriorityLabels.alta),
|
||||
active: state.priority === 'alta',
|
||||
})
|
||||
}
|
||||
|
||||
for (const definition of municipalityFilterDefinitions) {
|
||||
if (definition.param === 'name') continue
|
||||
if (definition.staffOnly && !showStaffFilters) continue
|
||||
|
||||
if (definition.selection === 'multi') {
|
||||
let filterOptions = definition.options ?? []
|
||||
if (definition.param === 'region') filterOptions = regionFilterOptions
|
||||
if (definition.param === 'advisor') filterOptions = advisorFilterOptions
|
||||
if (filterOptions.length === 0) continue
|
||||
|
||||
let param: MunicipalityMultiFilterParam
|
||||
if (definition.param === 'region') param = 'region'
|
||||
else if (definition.param === 'advisor') param = 'advisor'
|
||||
else if (definition.param === 'trend') param = 'trend'
|
||||
else if (definition.param === 'class') param = 'class'
|
||||
else if (definition.param === 'level') param = 'level'
|
||||
else continue // `name` skipped above; `coverage` is toggle-only
|
||||
|
||||
const selected = new Set(getMunicipalityMultiFilterValues(state, param))
|
||||
for (const option of filterOptions) {
|
||||
options.push({
|
||||
id: `multi:${param}:${option.value}`,
|
||||
kind: 'multi',
|
||||
label: dimensionLabel(definition.label, option.label),
|
||||
param,
|
||||
value: option.value,
|
||||
active: selected.has(option.value),
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (definition.selection === 'toggle' && definition.param === 'coverage') {
|
||||
for (const option of definition.options ?? []) {
|
||||
options.push({
|
||||
id: `coverage:${option.value}`,
|
||||
kind: 'coverage',
|
||||
label: dimensionLabel(definition.label, option.label),
|
||||
value: option.value,
|
||||
active: state.coverage === option.value,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const sortOption of municipalityListSortOptions) {
|
||||
const value = serializeMunicipalitySortValue(sortOption.key, sortOption.dir)
|
||||
options.push({
|
||||
id: `sort:${value}`,
|
||||
kind: 'sort',
|
||||
label: dimensionLabel('Ordenar', sortOption.label),
|
||||
sort: sortOption.key,
|
||||
dir: sortOption.dir,
|
||||
active: sortOption.key === activeSort && sortOption.dir === activeDir,
|
||||
})
|
||||
}
|
||||
|
||||
if (showStaffFilters) {
|
||||
for (const estimateScenario of VOTE_ESTIMATE_SCENARIOS) {
|
||||
options.push({
|
||||
id: `scenario:${estimateScenario}`,
|
||||
kind: 'scenario',
|
||||
label: dimensionLabel('Cenário', voteEstimateScenarioLabels[estimateScenario]),
|
||||
scenario: estimateScenario,
|
||||
active: scenario === estimateScenario,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
/**
|
||||
* Active filter chips. Sort only when the URL overrides the default (B18 drops
|
||||
* the default from the query); scenario only when not central.
|
||||
*/
|
||||
export const buildMunicipalityMobileFilterChips = (
|
||||
state: MunicipalityListState,
|
||||
options: readonly MunicipalityMobileFilterOption[],
|
||||
): MunicipalityMobileFilterChip[] => {
|
||||
const chips: MunicipalityMobileFilterChip[] = []
|
||||
let sortChip: MunicipalityMobileFilterChip | null = null
|
||||
let scenarioChip: MunicipalityMobileFilterChip | null = null
|
||||
const sortOverridden = state.sort !== undefined || state.dir !== undefined
|
||||
|
||||
for (const option of options) {
|
||||
if (!option.active) continue
|
||||
if (option.kind === 'sort') {
|
||||
if (sortOverridden) sortChip = { id: option.id, label: option.label }
|
||||
continue
|
||||
}
|
||||
if (option.kind === 'scenario') {
|
||||
if (option.scenario !== DEFAULT_VOTE_ESTIMATE_SCENARIO) {
|
||||
scenarioChip = { id: option.id, label: option.label }
|
||||
}
|
||||
continue
|
||||
}
|
||||
chips.push({ id: option.id, label: option.label })
|
||||
}
|
||||
|
||||
if (sortChip) chips.push(sortChip)
|
||||
if (scenarioChip) chips.push(scenarioChip)
|
||||
return chips
|
||||
}
|
||||
|
||||
/** Chip dismiss: filters toggle off; sort/scenario reset to defaults. */
|
||||
export const dismissMunicipalityMobileFilterChip = (
|
||||
state: MunicipalityListState,
|
||||
option: MunicipalityMobileFilterOption,
|
||||
): MunicipalityListState | 'scenario-default' => {
|
||||
switch (option.kind) {
|
||||
case 'sort':
|
||||
return { ...state, page: 1, sort: undefined, dir: undefined }
|
||||
case 'scenario':
|
||||
return 'scenario-default'
|
||||
case 'priority':
|
||||
case 'multi':
|
||||
case 'coverage': {
|
||||
const next = applyMunicipalityMobileFilterOption(state, option)
|
||||
if (next === 'scenario') {
|
||||
throw new Error(`Unexpected scenario result for ${option.kind}`)
|
||||
}
|
||||
return next
|
||||
}
|
||||
default: {
|
||||
const _exhaustive: never = option
|
||||
return _exhaustive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a typeahead pick (or chip dismiss) to list state. Scenario is not
|
||||
* URL-backed — callers handle it via the estimate-scenario context.
|
||||
*/
|
||||
export const applyMunicipalityMobileFilterOption = (
|
||||
state: MunicipalityListState,
|
||||
option: MunicipalityMobileFilterOption,
|
||||
): MunicipalityListState | 'scenario' => {
|
||||
switch (option.kind) {
|
||||
case 'priority':
|
||||
return toggleMunicipalityPriorityFilter(state)
|
||||
case 'multi':
|
||||
return toggleMunicipalityMultiFilterValue(state, option.param, option.value)
|
||||
case 'coverage':
|
||||
return toggleMunicipalityExclusiveFilterValue(state, 'coverage', option.value)
|
||||
case 'sort':
|
||||
return { ...state, page: 1, sort: option.sort, dir: option.dir }
|
||||
case 'scenario':
|
||||
return 'scenario'
|
||||
default: {
|
||||
const _exhaustive: never = option
|
||||
return _exhaustive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const findMunicipalityMobileFilterOption = (
|
||||
options: readonly MunicipalityMobileFilterOption[],
|
||||
id: string,
|
||||
): MunicipalityMobileFilterOption | undefined => options.find((option) => option.id === id)
|
||||
|
|
@ -54,9 +54,14 @@ test.describe('Municípios — list header mobile (B118)', () => {
|
|||
await expect(heading).toHaveClass(/sr-only/)
|
||||
const headingBox = await heading.boundingBox()
|
||||
expect(headingBox?.height ?? 0).toBeLessThanOrEqual(2)
|
||||
await expect(page.locator('header p')).toBeHidden()
|
||||
// Scope to the list page header (description is `hidden md:block`); avoid
|
||||
// strict-mode flakes if React mounts more than one matching `<p>`.
|
||||
const pageHeader = page.locator('header').filter({ has: heading })
|
||||
await expect(pageHeader.locator('p')).toBeHidden()
|
||||
await expect(page.locator('[data-scope="campaign"]')).toBeHidden()
|
||||
await expect(page.getByLabel('Buscar município')).toBeVisible()
|
||||
// B120: mobile uses the filter combobox; desktop search stays md+ only.
|
||||
await expect(page.getByLabel('Filtrar municípios')).toBeVisible()
|
||||
await expect(page.getByLabel('Buscar município')).toBeHidden()
|
||||
await expect(page.getByText(/\d+ municípios encontrados/)).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
|
@ -440,15 +445,11 @@ test.describe('Municípios — cards no celular (B42)', () => {
|
|||
|
||||
// Anywhere outside a control is the município's own link: the click lands on
|
||||
// the stretched `after:inset-0` overlay, which belongs to the card heading.
|
||||
// The tap goes on a field LABEL inside the metrics grid on purpose — the
|
||||
// first version of this card positioned each grid cell instead of each
|
||||
// control, which lifted the labels and their padding above the overlay and
|
||||
// made half the card a tap that neither edited nor navigated.
|
||||
// `force`: Playwright's hit-target check retries forever here precisely
|
||||
// BECAUSE the stretched overlay intercepts the pointer — which is the
|
||||
// behavior under test. Force dispatches the tap at the label's point, the
|
||||
// overlay receives it (as a user's finger would), and the card navigates.
|
||||
await card.getByText('Tendência', { exact: true }).click({ force: true })
|
||||
// B120 densified the card (no "Tendência" dt label). Do NOT tap the territory
|
||||
// line — `TerritoryLink` is `relative` above the overlay on purpose. Tap the
|
||||
// heading text; `force` because Playwright's hit-target check retries forever
|
||||
// when the overlay intercepts — which is the behavior under test.
|
||||
await card.getByRole('heading', { name: municipality.name }).click({ force: true })
|
||||
await expect(page).toHaveURL(`${campaign.baseURL}/campanha/municipios/${municipality.slug}`)
|
||||
await expect(page.getByRole('heading', { name: municipality.name })).toBeVisible()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -34,14 +34,36 @@ type FilterCase = {
|
|||
/**
|
||||
* A `key|dir` from the list's own sort options that is NOT its default —
|
||||
* otherwise `sort=` drops out of the canonical href and the assertion fails
|
||||
* for a reason unrelated to the hook.
|
||||
* for a reason unrelated to the hook. Used by shells that still expose
|
||||
* NativeSelect "Ordenar"; municípios (B120) use `navigateSecondary` instead.
|
||||
*/
|
||||
sortValue: string
|
||||
/** Href after secondary nav with `q=silva` carried. */
|
||||
hrefWithQueryAndSecondary: string
|
||||
/** Href after secondary nav with no query. */
|
||||
hrefWithSecondary: string
|
||||
/**
|
||||
* Non-search control that navigates. Default: change NativeSelect "Ordenar".
|
||||
* Municípios: pick a combobox filter option (sort NativeSelect removed in B120).
|
||||
*/
|
||||
navigateSecondary: (filterCase: FilterCase) => void
|
||||
element: (currentQuery?: string) => ReactElement
|
||||
/** Same shell with `sortValue` already committed — an external navigation. */
|
||||
elementWithSort: () => ReactElement
|
||||
}
|
||||
|
||||
const navigateViaSortSelect = (filterCase: FilterCase) => {
|
||||
fireEvent.change(screen.getByLabelText('Ordenar'), { target: { value: filterCase.sortValue } })
|
||||
}
|
||||
|
||||
const navigateViaMunicipalityPriorityOption = () => {
|
||||
const combobox = screen.getByRole('combobox', { name: 'Filtrar municípios' })
|
||||
fireEvent.focus(combobox)
|
||||
// Open the list and land on the first staff option (Prioridade · Prioritária).
|
||||
fireEvent.keyDown(combobox, { key: 'ArrowDown' })
|
||||
fireEvent.keyDown(combobox, { key: 'Enter' })
|
||||
}
|
||||
|
||||
const filterCases: FilterCase[] = [
|
||||
{
|
||||
name: 'dobradinhas',
|
||||
|
|
@ -49,6 +71,9 @@ const filterCases: FilterCase[] = [
|
|||
hrefWithQuery: '/campanha/dobradinhas?q=silva',
|
||||
bareHref: '/campanha/dobradinhas',
|
||||
sortValue: 'party|asc',
|
||||
hrefWithQueryAndSecondary: '/campanha/dobradinhas?q=silva&sort=party',
|
||||
hrefWithSecondary: '/campanha/dobradinhas?sort=party',
|
||||
navigateSecondary: navigateViaSortSelect,
|
||||
element: (currentQuery) =>
|
||||
createElement(StateDeputyFilters, {
|
||||
state: { page: 1, ...(currentQuery ? { q: currentQuery } : {}) },
|
||||
|
|
@ -68,6 +93,9 @@ const filterCases: FilterCase[] = [
|
|||
hrefWithQuery: '/campanha/territorios?q=silva',
|
||||
bareHref: '/campanha/territorios',
|
||||
sortValue: 'region|asc',
|
||||
hrefWithQueryAndSecondary: '/campanha/territorios?q=silva&sort=region',
|
||||
hrefWithSecondary: '/campanha/territorios?sort=region',
|
||||
navigateSecondary: navigateViaSortSelect,
|
||||
element: (currentQuery) =>
|
||||
createElement(TerritoryFilters, {
|
||||
state: { page: 1, ...(currentQuery ? { q: currentQuery } : {}) },
|
||||
|
|
@ -85,6 +113,9 @@ const filterCases: FilterCase[] = [
|
|||
hrefWithQuery: '/campanha/municipios?q=silva',
|
||||
bareHref: '/campanha/municipios',
|
||||
sortValue: 'name|asc',
|
||||
hrefWithQueryAndSecondary: '/campanha/municipios?priority=alta',
|
||||
hrefWithSecondary: '/campanha/municipios?priority=alta',
|
||||
navigateSecondary: navigateViaMunicipalityPriorityOption,
|
||||
element: (currentQuery) =>
|
||||
createElement(
|
||||
MunicipalityEstimateScenarioProvider,
|
||||
|
|
@ -135,10 +166,10 @@ const searchInput = (label: string) => screen.getByLabelText(label) as HTMLInput
|
|||
/**
|
||||
* `dir` never appears in these: every `sortValue` here is an `asc` key, which is
|
||||
* each list's default direction, so the canonical serializer drops it.
|
||||
* Municípios secondary is priority (B120 combobox), not sort — see
|
||||
* `hrefWithQueryAndSecondary`.
|
||||
*/
|
||||
const sortKeyOf = ({ sortValue }: FilterCase) => sortValue.split('|')[0]
|
||||
const hrefWithSort = (filterCase: FilterCase) =>
|
||||
`${filterCase.bareHref}?sort=${sortKeyOf(filterCase)}`
|
||||
const hrefWithQueryAndSort = (filterCase: FilterCase) =>
|
||||
`${filterCase.bareHref}?q=silva&sort=${sortKeyOf(filterCase)}`
|
||||
|
||||
|
|
@ -235,18 +266,27 @@ describe('campaign list filter navigation', () => {
|
|||
it.each(filterCases)(
|
||||
'$name: carries the uncommitted search when another control navigates',
|
||||
(filterCase) => {
|
||||
const { searchLabel, sortValue } = filterCase
|
||||
const { searchLabel, navigateSecondary, hrefWithQueryAndSecondary, name } = filterCase
|
||||
mountCase(filterCase)
|
||||
|
||||
typeSearch(searchLabel, 'silva')
|
||||
fireEvent.change(screen.getByLabelText('Ordenar'), { target: { value: sortValue } })
|
||||
navigateSecondary(filterCase)
|
||||
|
||||
expect(routerState.replace).toHaveBeenCalledTimes(1)
|
||||
expect(routerState.replace).toHaveBeenCalledWith(hrefWithQueryAndSort(filterCase), {
|
||||
expect(routerState.replace).toHaveBeenCalledWith(hrefWithQueryAndSecondary, {
|
||||
scroll: false,
|
||||
})
|
||||
|
||||
// The sort consumed the pending search; the timer must not fire a second one.
|
||||
// Municípios B120: a combobox pick must NOT commit the typeahead draft as
|
||||
// `q` (prefix text ≠ município name). Other shells still carry the draft.
|
||||
if (name !== 'municípios') {
|
||||
expect(hrefWithQueryAndSecondary).toContain('q=silva')
|
||||
} else {
|
||||
expect(hrefWithQueryAndSecondary).not.toContain('q=')
|
||||
}
|
||||
|
||||
// The secondary control consumed the pending search; the timer must not
|
||||
// fire a second navigation.
|
||||
advance(SEARCH_DEBOUNCE_MS)
|
||||
expect(routerState.replace).toHaveBeenCalledTimes(1)
|
||||
},
|
||||
|
|
@ -287,7 +327,7 @@ describe('campaign list filter navigation', () => {
|
|||
it.each(filterCases)(
|
||||
'$name: follows the URL when the committed query is dropped from outside the shell',
|
||||
(filterCase) => {
|
||||
const { searchLabel, element } = filterCase
|
||||
const { searchLabel, element, navigateSecondary, hrefWithSecondary } = filterCase
|
||||
const { rerenderWith } = mountCase(filterCase, 'silva')
|
||||
|
||||
// The empty state's "Limpar busca e filtros" is an anchor: it drops `q`
|
||||
|
|
@ -296,10 +336,8 @@ describe('campaign list filter navigation', () => {
|
|||
expect(searchInput(searchLabel).value).toBe('')
|
||||
|
||||
// The box must not put the dropped query back on the next filter touch.
|
||||
fireEvent.change(screen.getByLabelText('Ordenar'), {
|
||||
target: { value: filterCase.sortValue },
|
||||
})
|
||||
expect(routerState.replace).toHaveBeenCalledWith(hrefWithSort(filterCase), { scroll: false })
|
||||
navigateSecondary(filterCase)
|
||||
expect(routerState.replace).toHaveBeenCalledWith(hrefWithSecondary, { scroll: false })
|
||||
},
|
||||
)
|
||||
|
||||
|
|
|
|||
143
tests/unit/municipalityMobileFilterCombobox.unit.spec.ts
Normal file
143
tests/unit/municipalityMobileFilterCombobox.unit.spec.ts
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { DEFAULT_VOTE_ESTIMATE_SCENARIO } from '@/lib/voteEstimate'
|
||||
import { buildMunicipalityFilterHref } from '@/utilities/municipality/municipalityListFilters'
|
||||
import type { MunicipalityListState } from '@/utilities/municipality/municipalityListUrl'
|
||||
import {
|
||||
applyMunicipalityMobileFilterOption,
|
||||
buildMunicipalityMobileFilterChips,
|
||||
buildMunicipalityMobileFilterOptions,
|
||||
dismissMunicipalityMobileFilterChip,
|
||||
findMunicipalityMobileFilterOption,
|
||||
} from '@/utilities/municipality/municipalityMobileFilterCombobox'
|
||||
|
||||
const baseState = (): MunicipalityListState => ({ page: 1 })
|
||||
|
||||
describe('municipalityMobileFilterCombobox', () => {
|
||||
it('builds staff options including priority, coverage, sort and scenario', () => {
|
||||
const options = buildMunicipalityMobileFilterOptions({
|
||||
state: baseState(),
|
||||
showStaffFilters: true,
|
||||
regionFilterOptions: [{ value: 'Sertão Produtivo', label: 'Sertão Produtivo' }],
|
||||
advisorFilterOptions: [{ value: '12', label: 'Ana' }],
|
||||
scenario: DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
||||
})
|
||||
|
||||
expect(options.some((option) => option.id === 'priority:alta')).toBe(true)
|
||||
expect(options.some((option) => option.id === 'coverage:sem_assessor')).toBe(true)
|
||||
expect(options.some((option) => option.id === 'multi:region:Sertão Produtivo')).toBe(true)
|
||||
expect(options.some((option) => option.id === 'multi:advisor:12')).toBe(true)
|
||||
expect(options.some((option) => option.kind === 'sort')).toBe(true)
|
||||
expect(options.some((option) => option.id === 'scenario:pessimistic')).toBe(true)
|
||||
})
|
||||
|
||||
it('hides staff-only options when showStaffFilters is false', () => {
|
||||
const options = buildMunicipalityMobileFilterOptions({
|
||||
state: baseState(),
|
||||
showStaffFilters: false,
|
||||
regionFilterOptions: [{ value: 'Sertão Produtivo', label: 'Sertão Produtivo' }],
|
||||
advisorFilterOptions: [{ value: '12', label: 'Ana' }],
|
||||
scenario: 'optimistic',
|
||||
})
|
||||
|
||||
expect(options.some((option) => option.kind === 'priority')).toBe(false)
|
||||
expect(options.some((option) => option.kind === 'coverage')).toBe(false)
|
||||
expect(options.some((option) => option.kind === 'scenario')).toBe(false)
|
||||
expect(options.some((option) => option.id === 'multi:advisor:12')).toBe(false)
|
||||
expect(options.some((option) => option.id === 'multi:region:Sertão Produtivo')).toBe(true)
|
||||
})
|
||||
|
||||
it('empty dimension stays absent from chips and URL (OR-within / AND-across)', () => {
|
||||
const state = baseState()
|
||||
const options = buildMunicipalityMobileFilterOptions({
|
||||
state,
|
||||
showStaffFilters: true,
|
||||
regionFilterOptions: [{ value: 'Sertão Produtivo', label: 'Sertão Produtivo' }],
|
||||
advisorFilterOptions: [],
|
||||
scenario: DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
||||
})
|
||||
expect(buildMunicipalityMobileFilterChips(state, options)).toEqual([])
|
||||
expect(buildMunicipalityFilterHref(state)).toBe('/campanha/municipios')
|
||||
})
|
||||
|
||||
it('round-trips chips through URL helpers without inventing a new encoding', () => {
|
||||
let state = baseState()
|
||||
const catalog = () =>
|
||||
buildMunicipalityMobileFilterOptions({
|
||||
state,
|
||||
showStaffFilters: true,
|
||||
regionFilterOptions: [
|
||||
{ value: 'Sertão Produtivo', label: 'Sertão Produtivo' },
|
||||
{ value: 'Recôncavo', label: 'Recôncavo' },
|
||||
],
|
||||
advisorFilterOptions: [],
|
||||
scenario: DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
||||
})
|
||||
|
||||
const priority = findMunicipalityMobileFilterOption(catalog(), 'priority:alta')
|
||||
expect(priority).toBeDefined()
|
||||
state = applyMunicipalityMobileFilterOption(state, priority!) as MunicipalityListState
|
||||
|
||||
const region = findMunicipalityMobileFilterOption(catalog(), 'multi:region:Sertão Produtivo')
|
||||
expect(region).toBeDefined()
|
||||
state = applyMunicipalityMobileFilterOption(state, region!) as MunicipalityListState
|
||||
|
||||
const coverage = findMunicipalityMobileFilterOption(catalog(), 'coverage:sem_assessor')
|
||||
expect(coverage).toBeDefined()
|
||||
state = applyMunicipalityMobileFilterOption(state, coverage!) as MunicipalityListState
|
||||
|
||||
const href = buildMunicipalityFilterHref(state)
|
||||
expect(href).toContain('priority=alta')
|
||||
expect(href).toContain('region=')
|
||||
expect(href).toContain('coverage=sem_assessor')
|
||||
expect(href).not.toContain('is:')
|
||||
|
||||
const chips = buildMunicipalityMobileFilterChips(state, catalog())
|
||||
expect(chips.map((chip) => chip.id)).toEqual(
|
||||
expect.arrayContaining([
|
||||
'priority:alta',
|
||||
'multi:region:Sertão Produtivo',
|
||||
'coverage:sem_assessor',
|
||||
]),
|
||||
)
|
||||
|
||||
const dismiss = findMunicipalityMobileFilterOption(catalog(), 'multi:region:Sertão Produtivo')!
|
||||
state = dismissMunicipalityMobileFilterChip(state, dismiss) as MunicipalityListState
|
||||
expect(state.regions).toBeUndefined()
|
||||
expect(buildMunicipalityFilterHref(state)).not.toContain('region=')
|
||||
})
|
||||
|
||||
it('sort chip only when URL overrides default; dismiss clears sort', () => {
|
||||
let state: MunicipalityListState = { page: 1, sort: 'name', dir: 'asc' }
|
||||
const options = buildMunicipalityMobileFilterOptions({
|
||||
state,
|
||||
showStaffFilters: false,
|
||||
regionFilterOptions: [],
|
||||
advisorFilterOptions: [],
|
||||
scenario: DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
||||
})
|
||||
const chips = buildMunicipalityMobileFilterChips(state, options)
|
||||
expect(chips.some((chip) => chip.id.startsWith('sort:'))).toBe(true)
|
||||
|
||||
const sortChip = findMunicipalityMobileFilterOption(
|
||||
options,
|
||||
chips.find((c) => c.id.startsWith('sort:'))!.id,
|
||||
)!
|
||||
state = dismissMunicipalityMobileFilterChip(state, sortChip) as MunicipalityListState
|
||||
expect(state.sort).toBeUndefined()
|
||||
expect(state.dir).toBeUndefined()
|
||||
})
|
||||
|
||||
it('scenario option does not mutate list state (client context owns it)', () => {
|
||||
const state = baseState()
|
||||
const options = buildMunicipalityMobileFilterOptions({
|
||||
state,
|
||||
showStaffFilters: true,
|
||||
regionFilterOptions: [],
|
||||
advisorFilterOptions: [],
|
||||
scenario: DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
||||
})
|
||||
const option = findMunicipalityMobileFilterOption(options, 'scenario:optimistic')!
|
||||
expect(applyMunicipalityMobileFilterOption(state, option)).toBe('scenario')
|
||||
})
|
||||
})
|
||||
Loading…
Reference in a new issue