diff --git a/docs/plans/municipios-mobile-filtro-combobox-densificar.md b/docs/plans/municipios-mobile-filtro-combobox-densificar.md index 55741c58..8b5786a1 100644 --- a/docs/plans/municipios-mobile-filtro-combobox-densificar.md +++ b/docs/plans/municipios-mobile-filtro-combobox-densificar.md @@ -1,13 +1,21 @@ # Municípios mobile — filtro combobox + densificar lista -Status: ready -Atualizado em: 2026-08-01 +Status: in-progress +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. ## Design (Impeccable) diff --git a/src/app/(campaign)/campanha/(app)/municipios/page.tsx b/src/app/(campaign)/campanha/(app)/municipios/page.tsx index 0d3b7183..a805a9f9 100644 --- a/src/app/(campaign)/campanha/(app)/municipios/page.tsx +++ b/src/app/(campaign)/campanha/(app)/municipios/page.tsx @@ -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 ? ( - +
+ +
) : null const tableNode = ( diff --git a/src/components/campaign/municipality/MunicipalityFilters.tsx b/src/components/campaign/municipality/MunicipalityFilters.tsx index 4e9fd10a..2240a876 100644 --- a/src/components/campaign/municipality/MunicipalityFilters.tsx +++ b/src/components/campaign/municipality/MunicipalityFilters.tsx @@ -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 (
-
+ {/* B120 — mobile: one combobox (chips + typeahead) replaces the NativeSelect stack. */} +
+ setSearch('')} + onNavigate={navigateWithSearch} + /> +
+ + {/* Desktop: search + summary + scenario; column filters stay on table heads (B16). */} +
onSearchChange(event.target.value)} /> {activeFiltersSummary ? ( -

+

{activeFiltersSummary}

) : null} {showStaffFilters ? ( ) : null} +
+ + {/* Shared actions — one Limpar/Salvar for both breakpoints (B120 / B18). */} +
{hasActiveFilters ? ( ) : null}
- -
- {activeFiltersSummary ? ( -

{activeFiltersSummary}

- ) : null} - {showStaffFilters ? ( - - Prioridade - { - navigateWithSearch({ - ...state, - priority: event.target.value === 'alta' ? 'alta' : undefined, - }) - }} - className="min-h-11 w-full" - > - Todas - Prioritária - - - ) : 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 ( - - navigateWithSearch( - toggleMunicipalityMultiFilterValue( - state, - definition.param as MunicipalityMultiFilterParam, - value, - ), - ) - } - /> - ) - } - - const value = definition.param === 'coverage' ? (state.coverage ?? '') : '' - return ( - - - {definition.label} - - { - const selected = event.target.value - if (definition.selection === 'toggle') { - navigateWithSearch( - selected - ? toggleMunicipalityExclusiveFilterValue(state, 'coverage', selected) - : { ...state, coverage: undefined }, - ) - } - }} - className="min-h-11 w-full" - > - {definition.allLabel ?? 'Todas'} - {(definition.options ?? []).map((option) => ( - - {option.label} - - ))} - - - ) - })} - {showStaffFilters ? ( - - ) : null} - - Ordenar - { - 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 }) => ( - - {label} - - ))} - - -
) } diff --git a/src/components/campaign/municipality/MunicipalityList.tsx b/src/components/campaign/municipality/MunicipalityList.tsx index 0266e9f9..538ccdb7 100644 --- a/src/components/campaign/municipality/MunicipalityList.tsx +++ b/src/components/campaign/municipality/MunicipalityList.tsx @@ -430,7 +430,9 @@ export const MunicipalityList = (props: MunicipalityListProps) => { return ( <> -

+ {/* B120: mobile drops the sort notice (combobox carries sort); desktop keeps + the live region + table caption. */} +

{sortSummary}

diff --git a/src/components/campaign/municipality/MunicipalityListMobileCards.tsx b/src/components/campaign/municipality/MunicipalityListMobileCards.tsx index 46815b71..51d2b565 100644 --- a/src/components/campaign/municipality/MunicipalityListMobileCards.tsx +++ b/src/components/campaign/municipality/MunicipalityListMobileCards.tsx @@ -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) => ( -
+
{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 (
-
-

+
+

{zoneSuffix ? ` ${zoneSuffix}` : null}

- {position ? ( - - ) : null}

{isPriority && isStaffView ? ( - + ) : null}

+ {isStaffView ? ( -
-
-
Classe
-
- -
-
-
-
{municipalityColumnLabels.goalCoverage}
-
+ <> +
+
-
-
-
-
Votos estimados
-
- -
-
-
-
Nível
-
+
+
{canMoveEngagementLevel ? ( )} - +
-
-
Tendência
-
- + + + + + + {isCoordinator ? ( + -
-
-
-
Último sinal
-
- - - -
-
-
-
Assessores
-
- {isCoordinator ? ( - - ) : names.length ? ( - names.join(', ') - ) : ( + ) : names.length ? ( + + {names.join(', ')} + + ) : ( + - )} -
+ + )}
- + ) : null}
) diff --git a/src/components/campaign/municipality/MunicipalityListRowReadouts.tsx b/src/components/campaign/municipality/MunicipalityListRowReadouts.tsx index 76cfa2da..1a75ad47 100644 --- a/src/components/campaign/municipality/MunicipalityListRowReadouts.tsx +++ b/src/components/campaign/municipality/MunicipalityListRowReadouts.tsx @@ -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 = ({
) } - -export const TerritorialClassCardReadout = ({ - municipality, -}: { - municipality: MunicipalityListViewModel -}) => ( - - - - - -) diff --git a/src/components/campaign/municipality/MunicipalityMobileFilterCombobox.tsx b/src/components/campaign/municipality/MunicipalityMobileFilterCombobox.tsx new file mode 100644 index 00000000..ed5672b0 --- /dev/null +++ b/src/components/campaign/municipality/MunicipalityMobileFilterCombobox.tsx @@ -0,0 +1,163 @@ +'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 { DEFAULT_VOTE_ESTIMATE_SCENARIO } from '@/lib/voteEstimate' +import { cn } from '@/lib/utils' +import { matchesAtWordStart } 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 +} + +/** + * 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, +}: 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) + + const applyOption = (option: MunicipalityMobileFilterOption) => { + const next = applyMunicipalityMobileFilterOption(state, option) + if (next === 'scenario') { + setScenario?.(option.kind === 'scenario' ? option.scenario : scenario) + clearSearchBox() + return + } + // Carry whatever is in the box as `q` (same contract as the old sort select), + // then empty the typeahead for the next keyword. + onNavigate(next) + clearSearchBox() + } + + 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 ( +
+ {chips.length > 0 ? ( +
    + {chips.map((chip) => ( +
  • + +
  • + ))} +
+ ) : null} + + + items={options} + value={null} + inputValue={search} + onInputValueChange={onSearchChange} + onValueChange={(option) => { + if (option) applyOption(option) + }} + filter={(option, query) => { + if (!query) return true + // When the box is a name search (no option label matches), keep the + // full catalog so a filter can still be picked while `q` is pending. + const anyMatch = options.some((candidate) => + matchesAtWordStart(candidate.label, query), + ) + return anyMatch ? matchesAtWordStart(option.label, query) : true + }} + isItemEqualToValue={(left, right) => left?.id === right?.id} + itemToStringLabel={(option) => option.label} + > + + + + + + Nenhuma opção. Continue digitando para buscar por nome. + + {(option: MunicipalityMobileFilterOption) => ( + + {option.label} + {option.active ? (ativo) : null} + + )} + + + +
+ ) +} diff --git a/src/components/campaign/shared/useCampaignListFilterNavigation.ts b/src/components/campaign/shared/useCampaignListFilterNavigation.ts index 5eaa520a..fa45b6b7 100644 --- a/src/components/campaign/shared/useCampaignListFilterNavigation.ts +++ b/src/components/campaign/shared/useCampaignListFilterNavigation.ts @@ -123,6 +123,12 @@ export const useCampaignListFilterNavigation = ({ 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 diff --git a/src/utilities/municipality/municipalityMobileFilterCombobox.ts b/src/utilities/municipality/municipalityMobileFilterCombobox.ts new file mode 100644 index 00000000..34a96189 --- /dev/null +++ b/src/utilities/municipality/municipalityMobileFilterCombobox.ts @@ -0,0 +1,253 @@ +/** + * 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 + + const param: MunicipalityMultiFilterParam = + definition.param === 'region' + ? 'region' + : definition.param === 'advisor' + ? 'advisor' + : definition.param === 'trend' + ? 'trend' + : definition.param === 'class' + ? 'class' + : 'level' + + 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' => { + if (option.kind === 'sort') { + return { ...state, page: 1, sort: undefined, dir: undefined } + } + if (option.kind === 'scenario') return 'scenario-default' + const next = applyMunicipalityMobileFilterOption(state, option) + return next === 'scenario' ? state : next +} + +/** + * 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) diff --git a/tests/e2e/campaignMunicipalities.e2e.spec.ts b/tests/e2e/campaignMunicipalities.e2e.spec.ts index 95649626..fa491264 100644 --- a/tests/e2e/campaignMunicipalities.e2e.spec.ts +++ b/tests/e2e/campaignMunicipalities.e2e.spec.ts @@ -440,15 +440,13 @@ 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. + // B120 densified the card (no "Tendência" dt label) — tap the territory line + // under the name, which is not a quick-edit control. // `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 }) + await card.locator('p.text-muted-foreground').first().click({ force: true }) await expect(page).toHaveURL(`${campaign.baseURL}/campanha/municipios/${municipality.slug}`) await expect(page.getByRole('heading', { name: municipality.name })).toBeVisible() }) diff --git a/tests/unit/campaignListFilterNavigation.unit.spec.ts b/tests/unit/campaignListFilterNavigation.unit.spec.ts index 9788ca91..0366a72b 100644 --- a/tests/unit/campaignListFilterNavigation.unit.spec.ts +++ b/tests/unit/campaignListFilterNavigation.unit.spec.ts @@ -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?q=silva&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,19 @@ 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 } = 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. + // 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 +319,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 +328,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 }) }, ) diff --git a/tests/unit/municipalityMobileFilterCombobox.unit.spec.ts b/tests/unit/municipalityMobileFilterCombobox.unit.spec.ts new file mode 100644 index 00000000..9779f301 --- /dev/null +++ b/tests/unit/municipalityMobileFilterCombobox.unit.spec.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from 'vitest' + +import { DEFAULT_VOTE_ESTIMATE_SCENARIO } from '@/lib/voteEstimate' +import { + applyMunicipalityMobileFilterOption, + buildMunicipalityMobileFilterChips, + buildMunicipalityMobileFilterOptions, + dismissMunicipalityMobileFilterChip, + findMunicipalityMobileFilterOption, +} from '@/utilities/municipality/municipalityMobileFilterCombobox' +import { buildMunicipalityFilterHref } from '@/utilities/municipality/municipalityListFilters' +import type { MunicipalityListState } from '@/utilities/municipality/municipalityListUrl' + +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') + }) +})