- stateDeputyListUrl.ts / stateDeputyListFilters.ts: contrato de URL/filtro próprio (sort/dir, filtro de Partido multi + sentinela "Sem partido"), espelhando municipalityListUrl.ts (paginação/resolveListUrl) e territoryListUrl.ts (sort keys/labels) - stateDeputyData.ts: where/sort resolvidos no banco + facet de partido (loadStateDeputyPartyFacet), select estreito na query principal - StateDeputySortableHead / StateDeputyHeaderFilter / StateDeputyFilters: wrappers finos sobre o chrome compartilhado (shared/CampaignSortableHead, CampaignHeaderFilterPopover), paridade mobile incluída - dobradinhas/page.tsx: redirect canônico em duas fases, CampaignTable sempre montada com caption + empty state, resumo de ordenação aria-live - Correção pós-entrega (design review): "Sem partido" no mobile + caption da tabela + copy plural do empty state - /simplify (1ª rodada): buildStateDeputyPartyOptions compartilhado, remove discriminante filterParam redundante, dedupe/if mortos em stateDeputyListUrl.ts - /simplify (2ª rodada, pós-rebase): remove cast/type morto em stateDeputyData.ts, stateDeputyColumns usa StateDeputyFilterOption em vez de duplicar a forma, inlinea parsePartiesParam; extrai truncatedNamesLabel compartilhado em campaignListUrl.ts (3º call site — municipalityListFilters e territoryListFilters tinham a mesma função com nomes distintos) Gate verde (tsc, lint, format, check:cycles, 396 testes, build); Aikido 0 achados nos 7 arquivos tocados nesta rodada. Docs: docs/plans/ordenacao-filtros-lista-dobradinhas.md, docs/roadmap.md, .cursor/rules/projects/nucleos-eleitorais.mdc.
117 lines
4 KiB
TypeScript
117 lines
4 KiB
TypeScript
export type RawSearchParams = Record<string, string | string[] | undefined>
|
|
|
|
export const firstValue = (value: string | string[] | undefined): string | undefined =>
|
|
Array.isArray(value) ? value[0] : value
|
|
|
|
/** Flatten a repeated query param into distinct trimmed values. */
|
|
export const allParamValues = (value: string | string[] | undefined): string[] => {
|
|
if (value === undefined) return []
|
|
const cells = Array.isArray(value) ? value : [value]
|
|
const seen = new Set<string>()
|
|
for (const cell of cells) {
|
|
const trimmed = cell.trim()
|
|
if (trimmed) seen.add(trimmed)
|
|
}
|
|
return [...seen]
|
|
}
|
|
|
|
/**
|
|
* A repeatable enum param where selecting EVERY member means "todas" — which
|
|
* is the same filter as selecting none, and canonicalizes to the absent param
|
|
* so both produce one URL (B18's frozen contract). `allParamValues` already
|
|
* dropped duplicates and unknown tokens are ignored, so a hand-typed URL can
|
|
* never widen the filter.
|
|
*/
|
|
export const parseExhaustiveEnumParam = <T extends string>(
|
|
raw: string | string[] | undefined,
|
|
allowed: ReadonlySet<string>,
|
|
): T[] => {
|
|
const values = allParamValues(raw).filter((token): token is T => allowed.has(token))
|
|
return values.length < allowed.size ? values : []
|
|
}
|
|
|
|
/** "A, B" for ≤2 names, "A, B +N" beyond — the active-filters summary shorthand. */
|
|
export const truncatedNamesLabel = (names: readonly string[]): string =>
|
|
names.length <= 2 ? names.join(', ') : `${names.slice(0, 2).join(', ')} +${names.length - 2}`
|
|
|
|
export const normalizedText = (value: string | undefined): string | undefined => {
|
|
if (typeof value !== 'string') return undefined
|
|
const normalized = value.trim()
|
|
return normalized || undefined
|
|
}
|
|
|
|
export const strictDecimalInteger = (value: string | undefined): number | undefined => {
|
|
if (!value || !/^[1-9]\d*$/.test(value)) return undefined
|
|
const number = Number(value)
|
|
return Number.isSafeInteger(number) ? number : undefined
|
|
}
|
|
|
|
export const inspectRawListParams = (
|
|
params: RawSearchParams,
|
|
paramNameSet: ReadonlySet<string>,
|
|
): { hasUnsupportedParams: boolean; query: string } => {
|
|
const serialized = new URLSearchParams()
|
|
let hasUnsupportedParams = false
|
|
|
|
for (const [name, value] of Object.entries(params)) {
|
|
if (!paramNameSet.has(name)) {
|
|
hasUnsupportedParams = true
|
|
continue
|
|
}
|
|
if (value === undefined) continue
|
|
for (const item of Array.isArray(value) ? value : [value]) {
|
|
serialized.append(name, item)
|
|
}
|
|
}
|
|
|
|
return { hasUnsupportedParams, query: serialized.toString() }
|
|
}
|
|
|
|
export type ListStateWithPage = { page: number }
|
|
|
|
export type ResolveListUrlOptions<State extends ListStateWithPage> = {
|
|
params: RawSearchParams
|
|
paramNameSet: ReadonlySet<string>
|
|
parse: (params: RawSearchParams) => State
|
|
buildSearchParams: (state: State) => URLSearchParams
|
|
basePath: string
|
|
totalPages?: number
|
|
}
|
|
|
|
export const resolveListUrl = <State extends ListStateWithPage>(
|
|
options: ResolveListUrlOptions<State>,
|
|
): {
|
|
state: State
|
|
href: string
|
|
redirectHref?: string
|
|
} => {
|
|
const { params, paramNameSet, parse, buildSearchParams, basePath, totalPages } = options
|
|
const parsedState = parse(params)
|
|
const page =
|
|
totalPages !== undefined && totalPages > 0 && parsedState.page > totalPages
|
|
? totalPages
|
|
: parsedState.page
|
|
const state = page === parsedState.page ? parsedState : ({ ...parsedState, page } as State)
|
|
const canonicalParams = buildSearchParams(state)
|
|
const canonicalQuery = canonicalParams.toString()
|
|
const href = canonicalQuery ? `${basePath}?${canonicalQuery}` : basePath
|
|
const raw = inspectRawListParams(params, paramNameSet)
|
|
const needsRedirect = raw.hasUnsupportedParams || raw.query !== canonicalQuery
|
|
|
|
return {
|
|
state,
|
|
href,
|
|
...(needsRedirect ? { redirectHref: href } : {}),
|
|
}
|
|
}
|
|
|
|
export const buildListHref = <State>(
|
|
state: State,
|
|
buildSearchParams: (state: State, page?: number) => URLSearchParams,
|
|
basePath: string,
|
|
page: number,
|
|
): string => {
|
|
const params = buildSearchParams(state, page)
|
|
const query = params.toString()
|
|
return query ? `${basePath}?${query}` : basePath
|
|
}
|