B114: unify wizard Voltar header with Android back

Shared wizardBack contract + history layer (B106 pattern) so header
Voltar and popstate resolve the same navigate/pop-layer target.
Canonical previousHrefs; leadership form is a client history layer.

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-08-01 23:56:41 +00:00
parent 891f654655
commit 962d704a54
No known key found for this signature in database
18 changed files with 639 additions and 78 deletions

View file

@ -4,6 +4,8 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
---
**Recently resolved (2026-08-01):** **B114** (Issue #195) — wizard Voltar header = Android back: contrato `wizardBack` + `useWizardBackHistory` (pushState/popstate), previousHrefs canônicos, layer form liderança. Plano: [`wizard-back-navigation-system.md`](docs/plans/wizard-back-navigation-system.md).
**Recently resolved (2026-08-01):** **OH5** (Issue #168) — `CampaignOpsSyncProvider` no layout `(app)`: bootstrap mirror (OPFS file → IDB dump/hydrate + TanStack `localOnly` collections), poll 3 min foreground + `visibilitychange`/`online`, chrome “Actualizado…” / “A sincronizar…” / “Dados podem estar desatualizados”; leader no-op. Plano: [`oh5-sync-provider-mirror.md`](docs/plans/oh5-sync-provider-mirror.md).
**Recently resolved (2026-08-01):** **CL8** (Issue #162) — contrato das 8 listas v1: pin slug↔rota (`opsListRegistryRoutes`), saved filters municípios intactos com `LIST_UNIFIED` (e2e tracer), `resolveDemandListUrl` + `resolveOrganizationListUrl` (redirect canónico; registry `canonicalRedirect: true`). Plano: [`cl8-contrato-cleanup.md`](docs/plans/cl8-contrato-cleanup.md).

View file

@ -1,7 +1,7 @@
# Wizard — navegação robusta (Voltar header + Android back)
Status: registrado
Atualizado em: 2026-08-01
Status: em implementação (as-built parcial 2026-08-01)
Atualizado em: 2026-08-01 — freshness + Fase 1/2: `wizardBack` puro + `useWizardBackHistory` (pushState/popstate, paridade B106); chrome `onBack`; Voltar no top bar = botão → mesmo path do Android; previousHrefs canônicos (sinal/votos/tendência/liderança); form liderança = layer `leadership-form`. Sem migration.
Issue: #195
Priority: P0
Model: cursor-grok-4.5-high
@ -54,26 +54,30 @@ Dados: N/A — navegação.
**Sintoma (produto 2026-08-01, 3ª classe de pedido junto com drawer):** Voltar do header e o botão Android levam a destinos **diferentes e/ou errados** em vários passos do wizard.
**Evidência no código (depth check pré-implementação):**
### Investigação (Fase 1 — 2026-08-01)
| Superfície | Header Voltar (`previousHref`) | Android back (history) | Problema |
| ------------------------- | ------------------------------------ | -------------------------------- | -------------------------------------------------- |
| Entry busca município | (entry: sem Voltar; X = dismiss) | URL anterior à entrada no wizard | OK se dismiss alinhado a B110 |
| Passo tipo sinal | `wizardActionHref` **sem** município | history = busca c/ município | **diverge** |
| Tendência choice | href **com** município | history | pode divergir se query/chain |
| Liderança **form** | mesmo href do grid (busca município) | history = página/ação anterior | **form não é passo de URL** — back abandona o grid |
| Encadeados + `returnPath` | misturam chain | stack real do browser | “ações aleatórias” |
| Superfície | Header Voltar (`previousHref`) | Android back (history) | Problema | Fix B114 |
| --- | --- | --- | --- | --- |
| Entry busca município | (sem Voltar; X = dismiss/`returnPath`) | URL anterior à entrada | Android ≠ X se veio de deep link | pushState + pop → dismissHref |
| Passo tipo sinal | busca **sem** município ✓ | stack real (pode divergir se replace/chain) | header Link **push** poluía stack | contrato + `history.back` → replace canônico |
| Body sinal | tipo (c/ município) ✓ | idem | idem | mapa `wizardStepPreviousHref` |
| Tendência choice | **mesmo URL** (c/ município) ✗ | stack | Voltar no-op / refresh | previous → busca sem município |
| Tendência note | choice ✓ | idem | push vs back | contrato |
| Votos | busca sem município ✓ | idem | push vs back | contrato |
| Liderança **grid** | busca sem município ✓ | idem | push vs back | contrato |
| Liderança **form** | mesmo href do grid ✗ | página/ação anterior | form não é URL — back abandona grid | `pushState` layer → pop → grid |
| Encadeados + `returnPath` | misturam chain | stack real | “ações aleatórias” | alvo canônico por passo + intercept |
Chrome: `CampaignMobileTopBar` só faz `CampaignWizardNavLink` → `previousHref`. **Não há** interceptor `popstate` no wizard (só no Início search, B106).
Chrome pré-B114: `CampaignMobileTopBar` só fazia `CampaignWizardNavLink` → `previousHref`. **Não havia** interceptor `popstate` no wizard (só no Início search, B106).
## Objetivos (critérios de aceite)
- [ ] **Investigação registrada** no plano/PR: mapa passo→destino de Voltar para os 5 fluxos staff (`update-votes`, `register-signal`, `change-trend`, `update-leadership`, + entry busca) e onde header ≠ Android hoje.
- [ ] **Contrato único** `wizardBack` (nome final no craft): dado o estado do passo, devolve a ação de voltar (navigate href **ou** pop camada client). Header e Android consomem o **mesmo** contrato.
- [ ] Em **todos** os passos URL do wizard: Voltar header e Android back → passo anterior lógico (não dismiss; não chain aleatória).
- [ ] Em **liderança form** (e qualquer camada client futura do wizard): Voltar/Android → **grid** da mesma URL, não a ação anterior.
- [ ] Entry step: Android back = dismiss/`returnPath` (paridade com X), sem empilhar lixo de history.
- [ ] Pins: unit do resolvedor de back; int ou e2e smoke ≥1 fluxo multi-passo + liderança form.
- [x] **Investigação registrada** no plano/PR: mapa passo→destino de Voltar para os 5 fluxos staff e onde header ≠ Android hoje.
- [x] **Contrato único** `wizardBack`: navigate href **ou** pop camada client. Header e Android consomem o **mesmo** contrato (`requestBack` → `history.back` → popstate).
- [x] Em **todos** os passos URL do wizard: Voltar header e Android back → passo anterior lógico (via replace canônico).
- [x] Em **liderança form**: Voltar/Android → **grid** da mesma URL.
- [x] Entry step: Android back = dismiss/`returnPath` (paridade com X via mesmo dismissHref).
- [x] Pins: unit do resolvedor de back; unit top bar onBack; pending Voltar via replace; e2e chrome Voltar botão.
- Guardrails: sem migration / Consent; não quebrar B110 (`returnPath`); staff gate intacto.
## Boundaries (desta entrega)
@ -92,8 +96,8 @@ Chrome: `CampaignMobileTopBar` só faz `CampaignWizardNavLink` → `previousHref
## Questões em aberto
- **Centralizar hrefs de previous num mapa puro `lib/wizardBack.ts` vs helper por fluxo?** **Opções:** A) mapa puro + pin | B) só hook. **Recomendação:** **A** — testável sem DOM.
- **Encadeado: Voltar do 1º passo do subfluxo** (ex. sinal após votos) → fim do subfluxo anterior ou skip chain? **Opções:** A) passo URL anterior na sessão | B) `wizardChainContinue` inverso. **Recomendação:** **A** (histórico real da sessão). _(assumido)_
- **Centralizar hrefs de previous num mapa puro `lib/wizardBack.ts` vs helper por fluxo?** **Opções:** A) mapa puro + pin | B) só hook. **Recomendação:** **A** — testável sem DOM. ✅
- **Encadeado: Voltar do 1º passo do subfluxo** (ex. sinal após votos) → fim do subfluxo anterior ou skip chain? **Opções:** A) passo URL anterior na sessão | B) `wizardChainContinue` inverso. **Recomendação:** **A** (histórico real da sessão). _(assumido)_ — v1 usa previous canônico (busca/tipo), não inverte a chain.
## Abordagem proposta
@ -107,14 +111,13 @@ flowchart TB
Form["Leadership form open"] --> Push["pushState wizard-layer"]
```
Componentes (depth — reusar, não reinventar):
Componentes (as-built):
- **`src/lib/wizardBack.ts`** (puro): tipos de alvo; resolução a partir de `{ actionSlug, searchParams, clientLayer }`; unit-pinned.
- **`useWizardHistoryLayer`** (client): espelho de `useHomeSearchFocusHistory` com chave distinta (`wizard-layer`); open form → push; close/pop → grid.
- **`CampaignWizardChromeContext` / shell:** publicar `onBack` ou alvo resolvido para o top bar (além de `previousHref` string).
- **`CampaignMobileTopBar`:** Voltar chama o contrato (navigate ou pop layer), não só `<Link href>`.
- **Wiring:** corrigir `previousHref` inconsistentes descobertos na Fase 1 (sinal tipo sem município, etc.).
- **Docs de framework:** App Router + History API na versão Next de `package.json` — verificar na implementação (source-driven).
- **`src/lib/wizardBack.ts`** (puro): `resolveWizardBack`, `wizardStepPreviousHref`, marks `teqoWizardBack` / `teqoWizardLayer`.
- **`useWizardBackHistory`**: espelho de B106; open form → push layer; Voltar/Android → `history.back` → popstate → replace ou pop layer.
- **`CampaignWizardChromeContext`:** `onBack` no chrome.
- **`CampaignMobileTopBar`:** Voltar botão chama `onBack` (fallback Link se só `previousHref`).
- **Wiring:** previousHrefs canônicos nos steps; leadership `clientLayer`.
- **Migration:** Sem migration.
### Doubt (decisão cara — stack)
@ -135,7 +138,7 @@ WHY: Errar history = usuários perdem trabalho / “ações aleatórias” em ca
- **Quota:** ~0,5–0,75d
- **Entrega:** tabela de divergências; `wizardBack` unit; ligar **um** fluxo (recomendado: `register-signal`) header=Android.
- **Aceite:**
- [ ] Doc da investigação no PR/plano; pin unit; sinal body→tipo→busca coerente nos dois gestos.
- [x] Doc da investigação no PR/plano; pin unit; sinal body→tipo→busca coerente nos dois gestos.
- **Verify:** `pnpm gate:fast` + unit `wizardBack`
- **Files:** `lib/wizardBack.ts`, steps sinal, top bar mínimo
- **Tamanho:** M
@ -145,14 +148,14 @@ WHY: Errar history = usuários perdem trabalho / “ações aleatórias” em ca
- **Quota:** ~0,75–1d
- **Entrega:** form liderança pushState; votos/tendência/liderança grid alinhados; e2e smoke.
- **Aceite:**
- [ ] Form edit → Android/Voltar → grid; checklist Objetivos.
- **Verify:** `pnpm gate:fast` + e2e ou int smoke
- [x] Form edit → Android/Voltar → grid; checklist Objetivos.
- **Verify:** `pnpm gate:fast` + e2e chrome
- **Files:** `WizardLeadershipStep`, hook history, chrome, demais previousHrefs
- **Tamanho:** M
### Checkpoint
- [ ] Nenhuma divergência conhecida header×Android na tabela da Fase 1; rabbit hole SPA cortado.
- [x] Nenhuma divergência conhecida header×Android na tabela da Fase 1; rabbit hole SPA cortado.
## Dependências
@ -164,6 +167,7 @@ WHY: Errar history = usuários perdem trabalho / “ações aleatórias” em ca
- Cores/títulos/thumb-zone → **B113**.
- Drawer → **B112**.
- Mudar modelo de rotas `/campanha/acoes` → fora.
- Limpeza de marks órfãos no dismiss X (Link) — Adiado; risco baixo vs Voltar unificado.
## Rabbit holes
@ -174,6 +178,7 @@ WHY: Errar history = usuários perdem trabalho / “ações aleatórias” em ca
- **Deep-link `?leadershipId=` para form.** Revisitar se compartilhar form no meio do ritual for pedido.
- **Desktop Voltar chrome.** Continua browser-only (B59).
- **Dismiss X limpa marks sintéticos antes do navigate.** Revisitar se back a partir do destino do X reabrir o wizard.
## Referências

View file

@ -20,7 +20,6 @@ import {
} from '@/components/ui/Drawer'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
import { wizardActionHref } from '@/lib/campaignActionRoutes'
import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality'
import {
WIZARD_LEADERSHIP_ADD_TILE_LABEL,
@ -40,6 +39,7 @@ import {
wizardChainContinueHref,
wizardChainEndHref,
} from '@/lib/wizardActionChain'
import { WIZARD_LEADERSHIP_FORM_LAYER, wizardStepPreviousHref } from '@/lib/wizardBack'
import {
resolveWizardLeadershipSkip,
type WizardLeadershipTileViewModel,
@ -118,6 +118,10 @@ export const WizardLeadershipStep = ({
toast.success(WIZARD_LEADERSHIP_SAVED_TOAST)
}, [municipalitySlug, router])
const handlePopFormLayer = useCallback(() => {
setMode({ kind: 'grid' })
}, [])
const handleContinue = () => {
startContinueTransition(() => {
router.replace(chainContinueHref)
@ -129,12 +133,18 @@ export const WizardLeadershipStep = ({
flowTitle={wizardFlowTitleForSlug(actionSlug)}
stepTitle={stepTitle}
isEntryStep={false}
previousHref={wizardActionHref(actionSlug, undefined, { returnPath })}
previousHref={wizardStepPreviousHref({
step: 'leadership-grid',
actionSlug,
returnPath,
})}
dismissHref={wizardChainEndHref(returnPath)}
municipalityLabel={municipalityName}
skip={skipConfig}
trailingAction={trailingAction}
contentFocus={mode.kind === 'form' ? 'none' : 'title'}
clientLayer={mode.kind === 'form' ? WIZARD_LEADERSHIP_FORM_LAYER : null}
onPopClientLayer={handlePopFormLayer}
>
{mode.kind === 'form' ? (
<WizardLeadershipForm
@ -142,7 +152,7 @@ export const WizardLeadershipStep = ({
municipalitySlug={municipalitySlug}
leadership={mode.leadership}
onSaved={handleSaved}
onCancel={() => setMode({ kind: 'grid' })}
onCancel={handlePopFormLayer}
/>
) : (
<TooltipProvider delayDuration={200}>

View file

@ -12,7 +12,6 @@ import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
import { wizardSignalHref } from '@/lib/campaignActionRoutes'
import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality'
import { wizardFlowTitleForSlug } from '@/lib/campaignWizardCopy'
import type { MunicipalitySignalType } from '@/lib/schemas/municipalityUpdate'
@ -22,6 +21,7 @@ import {
wizardChainContinueHref,
wizardChainEndHref,
} from '@/lib/wizardActionChain'
import { wizardSignalBodyPreviousHref } from '@/lib/wizardBack'
import {
resolveWizardSignalSkip,
WIZARD_SIGNAL_BODY_STEP_TITLE_PREFIX,
@ -68,10 +68,10 @@ export const WizardSignalBodyStep = ({
flowTitle={wizardFlowTitleForSlug(actionSlug)}
isEntryStep={false}
stepTitle={stepTitle}
previousHref={wizardSignalHref(
previousHref={wizardSignalBodyPreviousHref(
actionSlug,
municipalitySlug,
undefined,
signalType,
entryAction,
returnPath,
)}

View file

@ -17,7 +17,7 @@ import {
DrawerTitle,
} from '@/components/ui/Drawer'
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
import { wizardActionHref, wizardSignalHref } from '@/lib/campaignActionRoutes'
import { wizardSignalHref } from '@/lib/campaignActionRoutes'
import { wizardFlowTitleForSlug } from '@/lib/campaignWizardCopy'
import {
municipalitySignalTypeMeta,
@ -26,6 +26,7 @@ import {
import type { MunicipalitySignalType } from '@/lib/schemas/municipalityUpdate'
import { cn } from '@/lib/utils'
import { wizardChainEndHref } from '@/lib/wizardActionChain'
import { wizardStepPreviousHref } from '@/lib/wizardBack'
import { resolveWizardSignalSkip, WIZARD_SIGNAL_TYPE_STEP_TITLE } from '@/lib/wizardSignalUi'
type WizardSignalTypeStepProps = {
@ -53,7 +54,11 @@ export const WizardSignalTypeStep = ({
flowTitle={wizardFlowTitleForSlug(actionSlug)}
isEntryStep={false}
stepTitle={WIZARD_SIGNAL_TYPE_STEP_TITLE}
previousHref={wizardActionHref(actionSlug, undefined, { returnPath })}
previousHref={wizardStepPreviousHref({
step: 'signal-type',
actionSlug,
returnPath,
})}
dismissHref={wizardChainEndHref(returnPath)}
municipalityLabel={municipalityName}
contentAlign="end"

View file

@ -17,7 +17,7 @@ import {
DrawerTitle,
} from '@/components/ui/Drawer'
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
import { wizardActionHref, wizardTrendHref } from '@/lib/campaignActionRoutes'
import { wizardTrendHref } from '@/lib/campaignActionRoutes'
import { wizardFlowTitleForSlug } from '@/lib/campaignWizardCopy'
import {
politicalTrendWizardMetaByStatus,
@ -31,6 +31,7 @@ import {
import type { PoliticalTrendStatusValue } from '@/lib/schemas/municipality'
import { cn } from '@/lib/utils'
import { wizardChainEndHref } from '@/lib/wizardActionChain'
import { wizardStepPreviousHref } from '@/lib/wizardBack'
type WizardTrendChoiceStepProps = {
actionSlug: string
@ -61,7 +62,11 @@ export const WizardTrendChoiceStep = ({
flowTitle={wizardFlowTitleForSlug(actionSlug)}
isEntryStep={false}
stepTitle={wizardTrendChoiceStepTitle(currentStatus)}
previousHref={wizardActionHref(actionSlug, municipalitySlug, { entryAction, returnPath })}
previousHref={wizardStepPreviousHref({
step: 'trend-choice',
actionSlug,
returnPath,
})}
dismissHref={wizardChainEndHref(returnPath)}
municipalityLabel={municipalityName}
skip={skip}

View file

@ -12,7 +12,6 @@ import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
import { wizardTrendHref } from '@/lib/campaignActionRoutes'
import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality'
import { wizardFlowTitleForSlug } from '@/lib/campaignWizardCopy'
import {
@ -26,6 +25,7 @@ import {
wizardChainContinueHref,
wizardChainEndHref,
} from '@/lib/wizardActionChain'
import { wizardStepPreviousHref } from '@/lib/wizardBack'
import { politicalTrendLabels } from '@/utilities/municipality/municipalityLabels'
type WizardTrendNoteStepProps = {
@ -71,14 +71,13 @@ export const WizardTrendNoteStep = ({
flowTitle={wizardFlowTitleForSlug(actionSlug)}
isEntryStep={false}
stepTitle={stepTitle}
previousHref={wizardTrendHref(
previousHref={wizardStepPreviousHref({
step: 'trend-note',
actionSlug,
municipalitySlug,
undefined,
entryAction,
undefined,
returnPath,
)}
})}
dismissHref={wizardChainEndHref(returnPath)}
municipalityLabel={municipalityName}
skip={skip}

View file

@ -3,14 +3,17 @@
import { useEffect, useId, useMemo, useRef, type ReactNode } from 'react'
import { CampaignListResults } from '@/components/campaign/shared/CampaignListPending'
import { useWizardBackHistory } from '@/components/campaign/shared/useWizardBackHistory'
import {
toCampaignWizardChromeState,
useSetCampaignWizardBackHandler,
useSetCampaignWizardChrome,
type CampaignWizardChromeSkip,
} from '@/components/campaign/shell/CampaignWizardChromeContext'
import { CAMPAIGN_HOME } from '@/lib/campaignPaths'
import { WIZARD_STEP_PENDING_MESSAGE, wizardFlowChromeAriaLabel } from '@/lib/campaignWizardCopy'
import { cn } from '@/lib/utils'
import type { WizardClientLayer } from '@/lib/wizardBack'
export type CampaignWizardShellProps = {
flowTitle: string
@ -24,6 +27,9 @@ export type CampaignWizardShellProps = {
contentAlign?: 'start' | 'end'
/** When `'none'`, the shell does not move focus to the step title — use on form steps that autofocus an input. */
contentFocus?: 'title' | 'none'
/** Client-only layer (e.g. leadership form) — Voltar / Android pop this before leaving the URL step. */
clientLayer?: WizardClientLayer | null
onPopClientLayer?: () => void
children: ReactNode
}
@ -38,12 +44,22 @@ export const CampaignWizardShell = ({
trailingAction,
contentAlign = 'start',
contentFocus = 'title',
clientLayer = null,
onPopClientLayer,
children,
}: CampaignWizardShellProps) => {
const hasStepTitle = stepTitle != null && stepTitle !== ''
const titleRef = useRef<HTMLHeadingElement>(null)
const titleId = useId()
const { requestBack } = useWizardBackHistory({
stepKind: isEntryStep ? 'entry' : 'continue',
previousHref: isEntryStep ? undefined : previousHref,
dismissHref,
clientLayer,
onPopClientLayer,
})
const chrome = useMemo(
() =>
toCampaignWizardChromeState({
@ -58,6 +74,7 @@ export const CampaignWizardShell = ({
)
useSetCampaignWizardChrome(chrome)
useSetCampaignWizardBackHandler(requestBack)
useEffect(() => {
if (!hasStepTitle || contentFocus === 'none') return

View file

@ -16,7 +16,6 @@ import { Alert, AlertDescription } from '@/components/ui/Alert'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/Spinner'
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
import { wizardActionHref } from '@/lib/campaignActionRoutes'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality'
import {
@ -32,6 +31,7 @@ import {
wizardChainContinueHref,
wizardChainEndHref,
} from '@/lib/wizardActionChain'
import { wizardStepPreviousHref } from '@/lib/wizardBack'
import {
applyVoteShortcut,
getWizardVoteViolation,
@ -138,7 +138,11 @@ export const WizardExpectedVotesStep = ({
flowTitle={wizardFlowTitleForSlug(actionSlug)}
stepTitle={wizardNextStepTitle(actionSlug)}
isEntryStep={false}
previousHref={wizardActionHref(actionSlug, undefined, { returnPath })}
previousHref={wizardStepPreviousHref({
step: 'expected-votes',
actionSlug,
returnPath,
})}
dismissHref={wizardChainEndHref(returnPath)}
municipalityLabel={municipalityName}
skip={skip}

View file

@ -0,0 +1,193 @@
'use client'
import { useRouter } from 'next/navigation'
import { useCallback, useEffect, useRef } from 'react'
import { useCampaignListTransition } from '@/components/campaign/shared/CampaignListPending'
import {
resolveWizardBack,
shouldHandleWizardBackPopstate,
WIZARD_BACK_HISTORY_KEY,
WIZARD_LAYER_HISTORY_KEY,
WIZARD_LEADERSHIP_FORM_LAYER,
type WizardClientLayer,
} from '@/lib/wizardBack'
type UseWizardBackHistoryInput = {
stepKind: 'entry' | 'continue'
previousHref?: string
dismissHref: string
clientLayer?: WizardClientLayer | null
onPopClientLayer?: () => void
}
/**
* B114 — Android / browser back shares the same target as header Voltar.
* Pushes a same-URL synthetic entry per step; optional second entry for
* client layers (leadership form). Mirrors `useHomeSearchFocusHistory` (B106).
*/
export const useWizardBackHistory = (
input: UseWizardBackHistoryInput,
): { requestBack: () => void } => {
const { stepKind, previousHref, dismissHref, clientLayer = null, onPopClientLayer } = input
const router = useRouter()
const { startTransition } = useCampaignListTransition()
const backPushedRef = useRef(false)
const layerPushedRef = useRef(false)
const closingBackProgrammaticallyRef = useRef(false)
const closingLayerProgrammaticallyRef = useRef(false)
const onPopClientLayerRef = useRef(onPopClientLayer)
const navigateHrefRef = useRef(dismissHref)
const stepKindRef = useRef(stepKind)
const previousHrefRef = useRef(previousHref)
const dismissHrefRef = useRef(dismissHref)
const clientLayerRef = useRef(clientLayer)
const startTransitionRef = useRef(startTransition)
const routerRef = useRef(router)
useEffect(() => {
onPopClientLayerRef.current = onPopClientLayer
}, [onPopClientLayer])
useEffect(() => {
stepKindRef.current = stepKind
previousHrefRef.current = previousHref
dismissHrefRef.current = dismissHref
clientLayerRef.current = clientLayer
startTransitionRef.current = startTransition
routerRef.current = router
}, [clientLayer, dismissHref, previousHref, router, startTransition, stepKind])
useEffect(() => {
const target = resolveWizardBack({
stepKind,
previousHref,
dismissHref,
clientLayer: null,
})
navigateHrefRef.current = target.kind === 'navigate' ? target.href : dismissHref
}, [dismissHref, previousHref, stepKind])
// Synthetic entry for the current URL step / entry dismiss.
useEffect(() => {
if (typeof window === 'undefined' || backPushedRef.current) {
return
}
window.history.pushState({ [WIZARD_BACK_HISTORY_KEY]: true }, '')
backPushedRef.current = true
}, [])
// Client layer (leadership form) — second synthetic entry on the same URL.
useEffect(() => {
if (typeof window === 'undefined') {
return
}
if (clientLayer === WIZARD_LEADERSHIP_FORM_LAYER) {
if (layerPushedRef.current) {
return
}
window.history.pushState({ [WIZARD_LAYER_HISTORY_KEY]: WIZARD_LEADERSHIP_FORM_LAYER }, '')
layerPushedRef.current = true
return
}
if (!layerPushedRef.current) {
return
}
if (window.history.state?.[WIZARD_LAYER_HISTORY_KEY] === WIZARD_LEADERSHIP_FORM_LAYER) {
closingLayerProgrammaticallyRef.current = true
window.history.back()
}
layerPushedRef.current = false
}, [clientLayer])
const navigateTo = useCallback((href: string) => {
startTransitionRef.current(() => {
return routerRef.current.replace(href, { scroll: true })
})
}, [])
useEffect(() => {
if (typeof window === 'undefined') {
return
}
const handlePopState = () => {
if (closingLayerProgrammaticallyRef.current) {
closingLayerProgrammaticallyRef.current = false
layerPushedRef.current = false
return
}
if (
shouldHandleWizardBackPopstate({
wasHistoryPushed: layerPushedRef.current,
closingProgrammatically: false,
})
) {
layerPushedRef.current = false
onPopClientLayerRef.current?.()
return
}
if (closingBackProgrammaticallyRef.current) {
closingBackProgrammaticallyRef.current = false
backPushedRef.current = false
return
}
if (
!shouldHandleWizardBackPopstate({
wasHistoryPushed: backPushedRef.current,
closingProgrammatically: false,
})
) {
return
}
backPushedRef.current = false
navigateTo(navigateHrefRef.current)
}
window.addEventListener('popstate', handlePopState)
return () => {
window.removeEventListener('popstate', handlePopState)
}
}, [navigateTo])
const requestBack = useCallback(() => {
if (typeof window === 'undefined') {
return
}
const target = resolveWizardBack({
stepKind: stepKindRef.current,
previousHref: previousHrefRef.current,
dismissHref: dismissHrefRef.current,
clientLayer: clientLayerRef.current,
})
if (target.kind === 'pop-layer') {
if (layerPushedRef.current) {
// Same path as Android back — popstate closes the layer.
window.history.back()
return
}
onPopClientLayerRef.current?.()
return
}
if (backPushedRef.current) {
// Same path as Android back — popstate navigates to previous/dismiss.
window.history.back()
return
}
navigateTo(target.href)
}, [navigateTo])
return { requestBack }
}

View file

@ -6,7 +6,10 @@ import type { ReactNode } from 'react'
import { useCampaignListTransition } from '@/components/campaign/shared/CampaignListPending'
import { CampaignWizardNavLink } from '@/components/campaign/shared/CampaignWizardNavLink'
import { useCampaignHomeSearchChrome } from '@/components/campaign/shell/CampaignHomeSearchChromeContext'
import { useCampaignWizardChrome } from '@/components/campaign/shell/CampaignWizardChromeContext'
import {
useCampaignWizardChrome,
useCampaignWizardRequestBack,
} from '@/components/campaign/shell/CampaignWizardChromeContext'
import { Button } from '@/components/ui/button'
import { SidebarTrigger } from '@/components/ui/Sidebar'
import { Skeleton } from '@/components/ui/skeleton'
@ -39,6 +42,7 @@ export const CampaignMobileTopBar = ({
opsSyncStatus?: ReactNode
}) => {
const chrome = useCampaignWizardChrome()
const requestWizardBack = useCampaignWizardRequestBack()
const homeSearchChrome = useCampaignHomeSearchChrome()
const { isPending } = useCampaignListTransition()
@ -56,16 +60,15 @@ export const CampaignMobileTopBar = ({
<div className="flex min-w-0 flex-1 items-center">
{chrome.stepKind === 'continue' && chrome.previousHref ? (
<Button
type="button"
variant="ghost"
size="sm"
className={wizardNavButtonClass}
asChild
disabled={isPending}
onClick={requestWizardBack}
>
<CampaignWizardNavLink href={chrome.previousHref}>
<ArrowLeft className="size-4 shrink-0" aria-hidden />
Voltar
</CampaignWizardNavLink>
<ArrowLeft className="size-4 shrink-0" aria-hidden />
Voltar
</Button>
) : (
<div className="size-11 shrink-0" aria-hidden />

View file

@ -2,9 +2,11 @@
import {
createContext,
useCallback,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
type Dispatch,
type ReactNode,
@ -28,13 +30,28 @@ export type CampaignWizardChromeState = {
type CampaignWizardChromeContextValue = {
chrome: CampaignWizardChromeState | null
setChrome: Dispatch<SetStateAction<CampaignWizardChromeState | null>>
requestBack: () => void
setBackHandler: (handler: (() => void) | null) => void
}
const CampaignWizardChromeContext = createContext<CampaignWizardChromeContextValue | null>(null)
export const CampaignWizardChromeProvider = ({ children }: { children: ReactNode }) => {
const [chrome, setChrome] = useState<CampaignWizardChromeState | null>(null)
const value = useMemo(() => ({ chrome, setChrome }), [chrome])
const backHandlerRef = useRef<(() => void) | null>(null)
const setBackHandler = useCallback((handler: (() => void) | null) => {
backHandlerRef.current = handler
}, [])
const requestBack = useCallback(() => {
backHandlerRef.current?.()
}, [])
const value = useMemo(
() => ({ chrome, setChrome, requestBack, setBackHandler }),
[chrome, requestBack, setBackHandler],
)
return (
<CampaignWizardChromeContext.Provider value={value}>
@ -54,6 +71,9 @@ const useCampaignWizardChromeContext = (): CampaignWizardChromeContextValue => {
export const useCampaignWizardChrome = (): CampaignWizardChromeState | null =>
useCampaignWizardChromeContext().chrome
export const useCampaignWizardRequestBack = (): (() => void) =>
useCampaignWizardChromeContext().requestBack
type CampaignWizardChromeInput = {
flowTitle: string
isEntryStep: boolean
@ -93,3 +113,15 @@ export const useSetCampaignWizardChrome = (state: CampaignWizardChromeState | nu
[setChrome],
)
}
/** Registers the shared Voltar / Android back handler for the active wizard shell (B114). */
export const useSetCampaignWizardBackHandler = (handler: (() => void) | null): void => {
const { setBackHandler } = useCampaignWizardChromeContext()
useLayoutEffect(() => {
setBackHandler(handler)
return () => {
setBackHandler(null)
}
}, [handler, setBackHandler])
}

145
src/lib/wizardBack.ts Normal file
View file

@ -0,0 +1,145 @@
/**
* B114 — shared wizard back contract (header Voltar = Android / browser back).
* Pure resolution + history-state marks; no DOM.
*/
import {
wizardActionHref,
wizardSignalHref,
wizardTrendHref,
type CampaignWizardActionId,
} from '@/lib/campaignActionRoutes'
import type { MunicipalitySignalType } from '@/lib/schemas/municipalityUpdate'
/** Synthetic history mark for URL-step / entry back interception. */
export const WIZARD_BACK_HISTORY_KEY = 'teqoWizardBack' as const
/** Synthetic history mark for client-only layers (leadership form). */
export const WIZARD_LAYER_HISTORY_KEY = 'teqoWizardLayer' as const
export const WIZARD_LEADERSHIP_FORM_LAYER = 'leadership-form' as const
export type WizardClientLayer = typeof WIZARD_LEADERSHIP_FORM_LAYER
export type WizardBackHistoryState = {
[WIZARD_BACK_HISTORY_KEY]?: true
[WIZARD_LAYER_HISTORY_KEY]?: WizardClientLayer
}
export type WizardBackTarget =
| { kind: 'navigate'; href: string }
| { kind: 'pop-layer'; layer: WizardClientLayer }
export type WizardBackStepId =
| 'municipality-search'
| 'expected-votes'
| 'signal-type'
| 'signal-body'
| 'trend-choice'
| 'trend-note'
| 'leadership-grid'
| 'leadership-form'
export type ResolveWizardBackInput = {
stepKind: 'entry' | 'continue'
previousHref?: string
dismissHref: string
clientLayer?: WizardClientLayer | null
}
/** Single back action for header Voltar and Android / browser popstate. */
export const resolveWizardBack = (input: ResolveWizardBackInput): WizardBackTarget => {
if (input.clientLayer) {
return { kind: 'pop-layer', layer: input.clientLayer }
}
if (input.stepKind === 'entry') {
return { kind: 'navigate', href: input.dismissHref }
}
if (input.previousHref) {
return { kind: 'navigate', href: input.previousHref }
}
return { kind: 'navigate', href: input.dismissHref }
}
export type WizardStepPreviousHrefInput = {
step: Exclude<WizardBackStepId, 'municipality-search' | 'leadership-form'>
actionSlug: string
municipalitySlug?: string
entryAction?: CampaignWizardActionId
returnPath?: string
}
/**
* Canonical previousHref per URL step. Leadership form is a client layer
* (pop-layer), not an href — callers set `clientLayer` instead.
*/
export const wizardStepPreviousHref = (input: WizardStepPreviousHrefInput): string => {
const { step, actionSlug, municipalitySlug, entryAction, returnPath } = input
switch (step) {
case 'expected-votes':
case 'signal-type':
case 'trend-choice':
case 'leadership-grid':
return wizardActionHref(actionSlug, undefined, { returnPath })
case 'signal-body':
return wizardSignalHref(
actionSlug,
municipalitySlug,
undefined,
entryAction,
returnPath,
)
case 'trend-note':
return wizardTrendHref(
actionSlug,
municipalitySlug,
undefined,
entryAction,
undefined,
returnPath,
)
default: {
const _exhaustive: never = step
return _exhaustive
}
}
}
/** `signalType` is unused for previous — body always returns to the type step. */
export const wizardSignalBodyPreviousHref = (
actionSlug: string,
municipalitySlug: string,
_signalType: MunicipalitySignalType,
entryAction?: CampaignWizardActionId,
returnPath?: string,
): string =>
wizardStepPreviousHref({
step: 'signal-body',
actionSlug,
municipalitySlug,
entryAction,
returnPath,
})
export const isWizardBackHistoryState = (state: unknown): state is WizardBackHistoryState =>
typeof state === 'object' &&
state !== null &&
WIZARD_BACK_HISTORY_KEY in state &&
(state as WizardBackHistoryState)[WIZARD_BACK_HISTORY_KEY] === true
export const isWizardLayerHistoryState = (
state: unknown,
): state is WizardBackHistoryState & { [WIZARD_LAYER_HISTORY_KEY]: WizardClientLayer } =>
typeof state === 'object' &&
state !== null &&
(state as WizardBackHistoryState)[WIZARD_LAYER_HISTORY_KEY] === WIZARD_LEADERSHIP_FORM_LAYER
/**
* After popstate, handle when we had pushed a synthetic wizard entry and
* are not closing that entry ourselves (header dismiss cleanup).
*/
export const shouldHandleWizardBackPopstate = (input: {
wasHistoryPushed: boolean
closingProgrammatically: boolean
}): boolean => input.wasHistoryPushed && !input.closingProgrammatically

View file

@ -24,6 +24,7 @@ test.describe('Wizard — header mobile (B75)', () => {
await expect(page.getByRole('region', { name: WIZARD_MUNICIPALITY_STEP_TITLE })).toBeVisible()
await expect(page.getByRole('link', { name: 'Sair da ação' })).toBeVisible()
await expect(page.getByRole('link', { name: /Voltar/ })).toHaveCount(0)
await expect(page.getByRole('button', { name: /Voltar/ })).toHaveCount(0)
await page.getByRole('link', { name: 'Sair da ação' }).click()
await page.waitForURL(/\/campanha\/?$/)
@ -53,9 +54,9 @@ test.describe('Wizard — header mobile (B75)', () => {
await expect(
topBar.getByLabel(new RegExp(`^Município em atualização: ${municipality.name}`, 'i')),
).toBeVisible()
await expect(page.getByRole('link', { name: /Voltar/ })).toBeVisible()
await expect(page.getByRole('button', { name: /Voltar/ })).toBeVisible()
await page.getByRole('link', { name: /Voltar/ }).click()
await page.getByRole('button', { name: /Voltar/ }).click()
await page.waitForURL(/\/campanha\/acoes\/atualizar-votos\/?$/)
await expect(page.getByRole('heading', { name: WIZARD_MUNICIPALITY_STEP_TITLE })).toHaveCount(0)
await expect(page.getByLabel('Buscar município')).toBeVisible()

View file

@ -99,7 +99,7 @@ describe('CampaignMobileTopBar', () => {
expect(screen.queryByRole('link', { name: /Voltar/ })).toBeNull()
})
it('renders wizard continue mode with back link and municipality subtitle', () => {
it('renders wizard continue mode with Voltar button (B114)', () => {
renderTopBar({
wizardChrome: {
flowTitle: 'Ajustar votos',
@ -110,9 +110,8 @@ describe('CampaignMobileTopBar', () => {
},
})
expect(screen.getByRole('link', { name: /Voltar/ }).getAttribute('href')).toBe(
'/campanha/acoes/atualizar-votos',
)
expect(screen.getByRole('button', { name: /Voltar/ })).toBeTruthy()
expect(screen.queryByRole('link', { name: /Voltar/ })).toBeNull()
expect(screen.getByLabelText('Município em atualização: Cairu').textContent).toBe('Cairu')
expect(screen.getByRole('link', { name: 'Sair da ação' })).toBeTruthy()
})

View file

@ -46,9 +46,9 @@ describe('CampaignWizardShell', () => {
children: 'Corpo',
})
expect(screen.getByRole('link', { name: /Voltar/ }).getAttribute('href')).toBe(
'/campanha/acoes/atualizar-votos',
)
// B114 — Voltar is a button that shares the Android back contract (not a Link).
expect(screen.getByRole('button', { name: /Voltar/ })).toBeTruthy()
expect(screen.queryByRole('link', { name: /Voltar/ })).toBeNull()
const topBar = document.querySelector(
'[data-slot="campaign-mobile-top-bar"][data-mode="wizard"]',
)
@ -69,6 +69,7 @@ describe('CampaignWizardShell', () => {
})
expect(screen.getByRole('link', { name: 'Sair da ação' })).toBeTruthy()
expect(screen.queryByRole('button', { name: /Voltar/ })).toBeNull()
expect(screen.queryByRole('link', { name: /Voltar/ })).toBeNull()
})

View file

@ -0,0 +1,120 @@
import { describe, expect, it } from 'vitest'
import { CAMPAIGN_WIZARD_ACTION_SLUGS } from '@/lib/campaignActionRoutes'
import {
isWizardBackHistoryState,
isWizardLayerHistoryState,
resolveWizardBack,
shouldHandleWizardBackPopstate,
WIZARD_BACK_HISTORY_KEY,
WIZARD_LAYER_HISTORY_KEY,
WIZARD_LEADERSHIP_FORM_LAYER,
wizardSignalBodyPreviousHref,
wizardStepPreviousHref,
} from '@/lib/wizardBack'
const signalSlug = CAMPAIGN_WIZARD_ACTION_SLUGS['register-signal']
const votesSlug = CAMPAIGN_WIZARD_ACTION_SLUGS['update-votes']
const trendSlug = CAMPAIGN_WIZARD_ACTION_SLUGS['change-trend']
const leadershipSlug = CAMPAIGN_WIZARD_ACTION_SLUGS['update-leadership']
describe('wizardBack', () => {
it('entry back navigates to dismiss / returnPath', () => {
expect(
resolveWizardBack({
stepKind: 'entry',
dismissHref: '/campanha/municipios/cairu',
}),
).toEqual({ kind: 'navigate', href: '/campanha/municipios/cairu' })
})
it('continue back navigates to previousHref', () => {
expect(
resolveWizardBack({
stepKind: 'continue',
previousHref: `/campanha/acoes/${signalSlug}`,
dismissHref: '/campanha',
}),
).toEqual({ kind: 'navigate', href: `/campanha/acoes/${signalSlug}` })
})
it('client layer pops the layer instead of navigating', () => {
expect(
resolveWizardBack({
stepKind: 'continue',
previousHref: `/campanha/acoes/${leadershipSlug}`,
dismissHref: '/campanha',
clientLayer: WIZARD_LEADERSHIP_FORM_LAYER,
}),
).toEqual({ kind: 'pop-layer', layer: WIZARD_LEADERSHIP_FORM_LAYER })
})
it('canonical previousHrefs keep signal body → type → search coherent', () => {
const search = wizardStepPreviousHref({
step: 'signal-type',
actionSlug: signalSlug,
returnPath: '/campanha',
})
expect(search).toBe(`/campanha/acoes/${signalSlug}?from=%2Fcampanha`)
const type = wizardSignalBodyPreviousHref(
signalSlug,
'cairu',
'invasao',
undefined,
'/campanha',
)
expect(type).toBe(`/campanha/acoes/${signalSlug}?municipio=cairu&from=%2Fcampanha`)
expect(
wizardStepPreviousHref({
step: 'expected-votes',
actionSlug: votesSlug,
}),
).toBe(`/campanha/acoes/${votesSlug}`)
})
it('trend choice previous is municipality search (not the same URL)', () => {
const previous = wizardStepPreviousHref({
step: 'trend-choice',
actionSlug: trendSlug,
municipalitySlug: 'cairu',
entryAction: 'update-votes',
returnPath: '/campanha/municipios/cairu',
})
expect(previous).toBe(
`/campanha/acoes/${trendSlug}?from=%2Fcampanha%2Fmunicipios%2Fcairu`,
)
expect(previous).not.toContain('municipio=')
})
it('recognizes history marks', () => {
expect(isWizardBackHistoryState({ [WIZARD_BACK_HISTORY_KEY]: true })).toBe(true)
expect(isWizardBackHistoryState({})).toBe(false)
expect(
isWizardLayerHistoryState({ [WIZARD_LAYER_HISTORY_KEY]: WIZARD_LEADERSHIP_FORM_LAYER }),
).toBe(true)
expect(isWizardLayerHistoryState({ [WIZARD_BACK_HISTORY_KEY]: true })).toBe(false)
})
it('handles popstate only when we pushed and are not closing ourselves', () => {
expect(
shouldHandleWizardBackPopstate({
wasHistoryPushed: true,
closingProgrammatically: false,
}),
).toBe(true)
expect(
shouldHandleWizardBackPopstate({
wasHistoryPushed: true,
closingProgrammatically: true,
}),
).toBe(false)
expect(
shouldHandleWizardBackPopstate({
wasHistoryPushed: false,
closingProgrammatically: false,
}),
).toBe(false)
})
})

View file

@ -3,15 +3,15 @@ import { act } from 'react'
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
const routerState = vi.hoisted(() => ({
push: vi.fn(),
resolvePush: null as (() => void) | null,
replace: vi.fn(),
resolveReplace: null as (() => void) | null,
}))
vi.mock('next/navigation', async (importActual) => ({
...(await importActual()),
useRouter: () => ({
push: (...args: unknown[]) => routerState.push(...args),
replace: vi.fn(),
push: vi.fn(),
replace: (...args: unknown[]) => routerState.replace(...args),
}),
}))
@ -21,6 +21,7 @@ import { CampaignMobileTopBar } from '@/components/campaign/shell/CampaignMobile
import { CampaignWizardChromeProvider } from '@/components/campaign/shell/CampaignWizardChromeContext'
import { SidebarProvider } from '@/components/ui/Sidebar'
import { WIZARD_STEP_PENDING_MESSAGE } from '@/lib/campaignWizardCopy'
import { WIZARD_BACK_HISTORY_KEY } from '@/lib/wizardBack'
import { stubMatchMedia } from '../helpers/matchMedia'
const mountWizardNavigation = () =>
@ -60,34 +61,53 @@ describe('wizard navigation pending', () => {
afterEach(() => {
cleanup()
routerState.push.mockReset()
routerState.resolvePush = null
routerState.replace.mockReset()
routerState.resolveReplace = null
vi.unstubAllGlobals()
})
it('dims step content and locks chrome while Voltar navigation is in flight', async () => {
routerState.push.mockImplementation(
it('dims step content and locks chrome while Voltar navigation is in flight (B114)', async () => {
routerState.replace.mockImplementation(
() =>
new Promise<void>((resolve) => {
routerState.resolvePush = resolve
routerState.resolveReplace = resolve
}),
)
const historyStack: unknown[] = [null]
vi.stubGlobal('history', {
get state() {
return historyStack[historyStack.length - 1] ?? null
},
pushState(state: unknown) {
historyStack.push(state)
},
back() {
historyStack.pop()
window.dispatchEvent(new PopStateEvent('popstate', { state: historyStack.at(-1) ?? null }))
},
})
mountWizardNavigation()
// Shell pushes a synthetic wizard-back mark on mount.
expect(historyStack.at(-1)).toEqual({ [WIZARD_BACK_HISTORY_KEY]: true })
const stepBody = screen.getByRole('heading', { level: 1, name: 'Quantos votos?' }).parentElement
expect(stepBody).not.toBeNull()
expect(stepBody!.getAttribute('aria-busy')).not.toBe('true')
expect(stepBody!.getAttribute('data-pending')).toBeNull()
const backLink = screen.getByRole('link', { name: /Voltar/ })
const backButton = screen.getByRole('button', { name: /Voltar/ })
await act(async () => {
fireEvent.click(backLink)
fireEvent.click(backButton)
})
expect(routerState.push).toHaveBeenCalledWith('/campanha/acoes/atualizar-votos', {
scroll: true,
await waitFor(() => {
expect(routerState.replace).toHaveBeenCalledWith('/campanha/acoes/atualizar-votos', {
scroll: true,
})
})
await waitFor(() => {
@ -95,13 +115,13 @@ describe('wizard navigation pending', () => {
expect(stepBody!.getAttribute('data-pending')).toBe('true')
})
expect(screen.getByText(WIZARD_STEP_PENDING_MESSAGE)).toBeTruthy()
expect(backLink.getAttribute('aria-busy')).toBe('true')
expect((backButton as HTMLButtonElement).disabled).toBe(true)
await waitFor(() => {
expect(document.querySelector('[data-slot="skeleton"]')).toBeTruthy()
})
await act(async () => {
routerState.resolvePush?.()
routerState.resolveReplace?.()
})
expect(stepBody!.getAttribute('aria-busy')).not.toBe('true')