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):** **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). **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) # Wizard — navegação robusta (Voltar header + Android back)
Status: registrado Status: em implementação (as-built parcial 2026-08-01)
Atualizado em: 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 Issue: #195
Priority: P0 Priority: P0
Model: cursor-grok-4.5-high 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. **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 | | Superfície | Header Voltar (`previousHref`) | Android back (history) | Problema | Fix B114 |
| ------------------------- | ------------------------------------ | -------------------------------- | -------------------------------------------------- | | --- | --- | --- | --- | --- |
| Entry busca município | (entry: sem Voltar; X = dismiss) | URL anterior à entrada no wizard | OK se dismiss alinhado a B110 | | 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 | `wizardActionHref` **sem** município | history = busca c/ município | **diverge** | | 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 |
| Tendência choice | href **com** município | history | pode divergir se query/chain | | Body sinal | tipo (c/ município) ✓ | idem | idem | mapa `wizardStepPreviousHref` |
| 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 | | Tendência choice | **mesmo URL** (c/ município) ✗ | stack | Voltar no-op / refresh | previous → busca sem município |
| Encadeados + `returnPath` | misturam chain | stack real do browser | “ações aleatórias” | | 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) ## 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. - [x] **Investigação registrada** no plano/PR: mapa passo→destino de Voltar para os 5 fluxos staff 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. - [x] **Contrato único** `wizardBack`: navigate href **ou** pop camada client. Header e Android consomem o **mesmo** contrato (`requestBack` → `history.back` → popstate).
- [ ] Em **todos** os passos URL do wizard: Voltar header e Android back → passo anterior lógico (não dismiss; não chain aleatória). - [x] Em **todos** os passos URL do wizard: Voltar header e Android back → passo anterior lógico (via replace canônico).
- [ ] Em **liderança form** (e qualquer camada client futura do wizard): Voltar/Android → **grid** da mesma URL, não a ação anterior. - [x] Em **liderança form**: Voltar/Android → **grid** da mesma URL.
- [ ] Entry step: Android back = dismiss/`returnPath` (paridade com X), sem empilhar lixo de history. - [x] Entry step: Android back = dismiss/`returnPath` (paridade com X via mesmo dismissHref).
- [ ] Pins: unit do resolvedor de back; int ou e2e smoke ≥1 fluxo multi-passo + liderança form. - [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. - Guardrails: sem migration / Consent; não quebrar B110 (`returnPath`); staff gate intacto.
## Boundaries (desta entrega) ## Boundaries (desta entrega)
@ -92,8 +96,8 @@ Chrome: `CampaignMobileTopBar` só faz `CampaignWizardNavLink` → `previousHref
## Questões em aberto ## 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. - **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)_ - **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 ## Abordagem proposta
@ -107,14 +111,13 @@ flowchart TB
Form["Leadership form open"] --> Push["pushState wizard-layer"] 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. - **`src/lib/wizardBack.ts`** (puro): `resolveWizardBack`, `wizardStepPreviousHref`, marks `teqoWizardBack` / `teqoWizardLayer`.
- **`useWizardHistoryLayer`** (client): espelho de `useHomeSearchFocusHistory` com chave distinta (`wizard-layer`); open form → push; close/pop → grid. - **`useWizardBackHistory`**: espelho de B106; open form → push layer; Voltar/Android → `history.back` → popstate → replace ou pop layer.
- **`CampaignWizardChromeContext` / shell:** publicar `onBack` ou alvo resolvido para o top bar (além de `previousHref` string). - **`CampaignWizardChromeContext`:** `onBack` no chrome.
- **`CampaignMobileTopBar`:** Voltar chama o contrato (navigate ou pop layer), não só `<Link href>`. - **`CampaignMobileTopBar`:** Voltar botão chama `onBack` (fallback Link se só `previousHref`).
- **Wiring:** corrigir `previousHref` inconsistentes descobertos na Fase 1 (sinal tipo sem município, etc.). - **Wiring:** previousHrefs canônicos nos steps; leadership `clientLayer`.
- **Docs de framework:** App Router + History API na versão Next de `package.json` — verificar na implementação (source-driven).
- **Migration:** Sem migration. - **Migration:** Sem migration.
### Doubt (decisão cara — stack) ### 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 - **Quota:** ~0,5–0,75d
- **Entrega:** tabela de divergências; `wizardBack` unit; ligar **um** fluxo (recomendado: `register-signal`) header=Android. - **Entrega:** tabela de divergências; `wizardBack` unit; ligar **um** fluxo (recomendado: `register-signal`) header=Android.
- **Aceite:** - **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` - **Verify:** `pnpm gate:fast` + unit `wizardBack`
- **Files:** `lib/wizardBack.ts`, steps sinal, top bar mínimo - **Files:** `lib/wizardBack.ts`, steps sinal, top bar mínimo
- **Tamanho:** M - **Tamanho:** M
@ -145,14 +148,14 @@ WHY: Errar history = usuários perdem trabalho / “ações aleatórias” em ca
- **Quota:** ~0,75–1d - **Quota:** ~0,75–1d
- **Entrega:** form liderança pushState; votos/tendência/liderança grid alinhados; e2e smoke. - **Entrega:** form liderança pushState; votos/tendência/liderança grid alinhados; e2e smoke.
- **Aceite:** - **Aceite:**
- [ ] Form edit → Android/Voltar → grid; checklist Objetivos. - [x] Form edit → Android/Voltar → grid; checklist Objetivos.
- **Verify:** `pnpm gate:fast` + e2e ou int smoke - **Verify:** `pnpm gate:fast` + e2e chrome
- **Files:** `WizardLeadershipStep`, hook history, chrome, demais previousHrefs - **Files:** `WizardLeadershipStep`, hook history, chrome, demais previousHrefs
- **Tamanho:** M - **Tamanho:** M
### Checkpoint ### 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 ## 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**. - Cores/títulos/thumb-zone → **B113**.
- Drawer → **B112**. - Drawer → **B112**.
- Mudar modelo de rotas `/campanha/acoes` → fora. - Mudar modelo de rotas `/campanha/acoes` → fora.
- Limpeza de marks órfãos no dismiss X (Link) — Adiado; risco baixo vs Voltar unificado.
## Rabbit holes ## 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. - **Deep-link `?leadershipId=` para form.** Revisitar se compartilhar form no meio do ritual for pedido.
- **Desktop Voltar chrome.** Continua browser-only (B59). - **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 ## Referências

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,14 +3,17 @@
import { useEffect, useId, useMemo, useRef, type ReactNode } from 'react' import { useEffect, useId, useMemo, useRef, type ReactNode } from 'react'
import { CampaignListResults } from '@/components/campaign/shared/CampaignListPending' import { CampaignListResults } from '@/components/campaign/shared/CampaignListPending'
import { useWizardBackHistory } from '@/components/campaign/shared/useWizardBackHistory'
import { import {
toCampaignWizardChromeState, toCampaignWizardChromeState,
useSetCampaignWizardBackHandler,
useSetCampaignWizardChrome, useSetCampaignWizardChrome,
type CampaignWizardChromeSkip, type CampaignWizardChromeSkip,
} from '@/components/campaign/shell/CampaignWizardChromeContext' } from '@/components/campaign/shell/CampaignWizardChromeContext'
import { CAMPAIGN_HOME } from '@/lib/campaignPaths' import { CAMPAIGN_HOME } from '@/lib/campaignPaths'
import { WIZARD_STEP_PENDING_MESSAGE, wizardFlowChromeAriaLabel } from '@/lib/campaignWizardCopy' import { WIZARD_STEP_PENDING_MESSAGE, wizardFlowChromeAriaLabel } from '@/lib/campaignWizardCopy'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import type { WizardClientLayer } from '@/lib/wizardBack'
export type CampaignWizardShellProps = { export type CampaignWizardShellProps = {
flowTitle: string flowTitle: string
@ -24,6 +27,9 @@ export type CampaignWizardShellProps = {
contentAlign?: 'start' | 'end' contentAlign?: 'start' | 'end'
/** When `'none'`, the shell does not move focus to the step title — use on form steps that autofocus an input. */ /** When `'none'`, the shell does not move focus to the step title — use on form steps that autofocus an input. */
contentFocus?: 'title' | 'none' 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 children: ReactNode
} }
@ -38,12 +44,22 @@ export const CampaignWizardShell = ({
trailingAction, trailingAction,
contentAlign = 'start', contentAlign = 'start',
contentFocus = 'title', contentFocus = 'title',
clientLayer = null,
onPopClientLayer,
children, children,
}: CampaignWizardShellProps) => { }: CampaignWizardShellProps) => {
const hasStepTitle = stepTitle != null && stepTitle !== '' const hasStepTitle = stepTitle != null && stepTitle !== ''
const titleRef = useRef<HTMLHeadingElement>(null) const titleRef = useRef<HTMLHeadingElement>(null)
const titleId = useId() const titleId = useId()
const { requestBack } = useWizardBackHistory({
stepKind: isEntryStep ? 'entry' : 'continue',
previousHref: isEntryStep ? undefined : previousHref,
dismissHref,
clientLayer,
onPopClientLayer,
})
const chrome = useMemo( const chrome = useMemo(
() => () =>
toCampaignWizardChromeState({ toCampaignWizardChromeState({
@ -58,6 +74,7 @@ export const CampaignWizardShell = ({
) )
useSetCampaignWizardChrome(chrome) useSetCampaignWizardChrome(chrome)
useSetCampaignWizardBackHandler(requestBack)
useEffect(() => { useEffect(() => {
if (!hasStepTitle || contentFocus === 'none') return 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 { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/Spinner' import { Spinner } from '@/components/ui/Spinner'
import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes' import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes'
import { wizardActionHref } from '@/lib/campaignActionRoutes'
import { postCampaignJson } from '@/lib/campaignJsonRequest' import { postCampaignJson } from '@/lib/campaignJsonRequest'
import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality' import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality'
import { import {
@ -32,6 +31,7 @@ import {
wizardChainContinueHref, wizardChainContinueHref,
wizardChainEndHref, wizardChainEndHref,
} from '@/lib/wizardActionChain' } from '@/lib/wizardActionChain'
import { wizardStepPreviousHref } from '@/lib/wizardBack'
import { import {
applyVoteShortcut, applyVoteShortcut,
getWizardVoteViolation, getWizardVoteViolation,
@ -138,7 +138,11 @@ export const WizardExpectedVotesStep = ({
flowTitle={wizardFlowTitleForSlug(actionSlug)} flowTitle={wizardFlowTitleForSlug(actionSlug)}
stepTitle={wizardNextStepTitle(actionSlug)} stepTitle={wizardNextStepTitle(actionSlug)}
isEntryStep={false} isEntryStep={false}
previousHref={wizardActionHref(actionSlug, undefined, { returnPath })} previousHref={wizardStepPreviousHref({
step: 'expected-votes',
actionSlug,
returnPath,
})}
dismissHref={wizardChainEndHref(returnPath)} dismissHref={wizardChainEndHref(returnPath)}
municipalityLabel={municipalityName} municipalityLabel={municipalityName}
skip={skip} 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 { useCampaignListTransition } from '@/components/campaign/shared/CampaignListPending'
import { CampaignWizardNavLink } from '@/components/campaign/shared/CampaignWizardNavLink' import { CampaignWizardNavLink } from '@/components/campaign/shared/CampaignWizardNavLink'
import { useCampaignHomeSearchChrome } from '@/components/campaign/shell/CampaignHomeSearchChromeContext' 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 { Button } from '@/components/ui/button'
import { SidebarTrigger } from '@/components/ui/Sidebar' import { SidebarTrigger } from '@/components/ui/Sidebar'
import { Skeleton } from '@/components/ui/skeleton' import { Skeleton } from '@/components/ui/skeleton'
@ -39,6 +42,7 @@ export const CampaignMobileTopBar = ({
opsSyncStatus?: ReactNode opsSyncStatus?: ReactNode
}) => { }) => {
const chrome = useCampaignWizardChrome() const chrome = useCampaignWizardChrome()
const requestWizardBack = useCampaignWizardRequestBack()
const homeSearchChrome = useCampaignHomeSearchChrome() const homeSearchChrome = useCampaignHomeSearchChrome()
const { isPending } = useCampaignListTransition() const { isPending } = useCampaignListTransition()
@ -56,16 +60,15 @@ export const CampaignMobileTopBar = ({
<div className="flex min-w-0 flex-1 items-center"> <div className="flex min-w-0 flex-1 items-center">
{chrome.stepKind === 'continue' && chrome.previousHref ? ( {chrome.stepKind === 'continue' && chrome.previousHref ? (
<Button <Button
type="button"
variant="ghost" variant="ghost"
size="sm" size="sm"
className={wizardNavButtonClass} className={wizardNavButtonClass}
asChild
disabled={isPending} disabled={isPending}
onClick={requestWizardBack}
> >
<CampaignWizardNavLink href={chrome.previousHref}>
<ArrowLeft className="size-4 shrink-0" aria-hidden /> <ArrowLeft className="size-4 shrink-0" aria-hidden />
Voltar Voltar
</CampaignWizardNavLink>
</Button> </Button>
) : ( ) : (
<div className="size-11 shrink-0" aria-hidden /> <div className="size-11 shrink-0" aria-hidden />

View file

@ -2,9 +2,11 @@
import { import {
createContext, createContext,
useCallback,
useContext, useContext,
useLayoutEffect, useLayoutEffect,
useMemo, useMemo,
useRef,
useState, useState,
type Dispatch, type Dispatch,
type ReactNode, type ReactNode,
@ -28,13 +30,28 @@ export type CampaignWizardChromeState = {
type CampaignWizardChromeContextValue = { type CampaignWizardChromeContextValue = {
chrome: CampaignWizardChromeState | null chrome: CampaignWizardChromeState | null
setChrome: Dispatch<SetStateAction<CampaignWizardChromeState | null>> setChrome: Dispatch<SetStateAction<CampaignWizardChromeState | null>>
requestBack: () => void
setBackHandler: (handler: (() => void) | null) => void
} }
const CampaignWizardChromeContext = createContext<CampaignWizardChromeContextValue | null>(null) const CampaignWizardChromeContext = createContext<CampaignWizardChromeContextValue | null>(null)
export const CampaignWizardChromeProvider = ({ children }: { children: ReactNode }) => { export const CampaignWizardChromeProvider = ({ children }: { children: ReactNode }) => {
const [chrome, setChrome] = useState<CampaignWizardChromeState | null>(null) 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 ( return (
<CampaignWizardChromeContext.Provider value={value}> <CampaignWizardChromeContext.Provider value={value}>
@ -54,6 +71,9 @@ const useCampaignWizardChromeContext = (): CampaignWizardChromeContextValue => {
export const useCampaignWizardChrome = (): CampaignWizardChromeState | null => export const useCampaignWizardChrome = (): CampaignWizardChromeState | null =>
useCampaignWizardChromeContext().chrome useCampaignWizardChromeContext().chrome
export const useCampaignWizardRequestBack = (): (() => void) =>
useCampaignWizardChromeContext().requestBack
type CampaignWizardChromeInput = { type CampaignWizardChromeInput = {
flowTitle: string flowTitle: string
isEntryStep: boolean isEntryStep: boolean
@ -93,3 +113,15 @@ export const useSetCampaignWizardChrome = (state: CampaignWizardChromeState | nu
[setChrome], [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('region', { name: WIZARD_MUNICIPALITY_STEP_TITLE })).toBeVisible()
await expect(page.getByRole('link', { name: 'Sair da ação' })).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('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.getByRole('link', { name: 'Sair da ação' }).click()
await page.waitForURL(/\/campanha\/?$/) await page.waitForURL(/\/campanha\/?$/)
@ -53,9 +54,9 @@ test.describe('Wizard — header mobile (B75)', () => {
await expect( await expect(
topBar.getByLabel(new RegExp(`^Município em atualização: ${municipality.name}`, 'i')), topBar.getByLabel(new RegExp(`^Município em atualização: ${municipality.name}`, 'i')),
).toBeVisible() ).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 page.waitForURL(/\/campanha\/acoes\/atualizar-votos\/?$/)
await expect(page.getByRole('heading', { name: WIZARD_MUNICIPALITY_STEP_TITLE })).toHaveCount(0) await expect(page.getByRole('heading', { name: WIZARD_MUNICIPALITY_STEP_TITLE })).toHaveCount(0)
await expect(page.getByLabel('Buscar município')).toBeVisible() await expect(page.getByLabel('Buscar município')).toBeVisible()

View file

@ -99,7 +99,7 @@ describe('CampaignMobileTopBar', () => {
expect(screen.queryByRole('link', { name: /Voltar/ })).toBeNull() 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({ renderTopBar({
wizardChrome: { wizardChrome: {
flowTitle: 'Ajustar votos', flowTitle: 'Ajustar votos',
@ -110,9 +110,8 @@ describe('CampaignMobileTopBar', () => {
}, },
}) })
expect(screen.getByRole('link', { name: /Voltar/ }).getAttribute('href')).toBe( expect(screen.getByRole('button', { name: /Voltar/ })).toBeTruthy()
'/campanha/acoes/atualizar-votos', expect(screen.queryByRole('link', { name: /Voltar/ })).toBeNull()
)
expect(screen.getByLabelText('Município em atualização: Cairu').textContent).toBe('Cairu') expect(screen.getByLabelText('Município em atualização: Cairu').textContent).toBe('Cairu')
expect(screen.getByRole('link', { name: 'Sair da ação' })).toBeTruthy() expect(screen.getByRole('link', { name: 'Sair da ação' })).toBeTruthy()
}) })

View file

@ -46,9 +46,9 @@ describe('CampaignWizardShell', () => {
children: 'Corpo', children: 'Corpo',
}) })
expect(screen.getByRole('link', { name: /Voltar/ }).getAttribute('href')).toBe( // B114 — Voltar is a button that shares the Android back contract (not a Link).
'/campanha/acoes/atualizar-votos', expect(screen.getByRole('button', { name: /Voltar/ })).toBeTruthy()
) expect(screen.queryByRole('link', { name: /Voltar/ })).toBeNull()
const topBar = document.querySelector( const topBar = document.querySelector(
'[data-slot="campaign-mobile-top-bar"][data-mode="wizard"]', '[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.getByRole('link', { name: 'Sair da ação' })).toBeTruthy()
expect(screen.queryByRole('button', { name: /Voltar/ })).toBeNull()
expect(screen.queryByRole('link', { 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' import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
const routerState = vi.hoisted(() => ({ const routerState = vi.hoisted(() => ({
push: vi.fn(), replace: vi.fn(),
resolvePush: null as (() => void) | null, resolveReplace: null as (() => void) | null,
})) }))
vi.mock('next/navigation', async (importActual) => ({ vi.mock('next/navigation', async (importActual) => ({
...(await importActual()), ...(await importActual()),
useRouter: () => ({ useRouter: () => ({
push: (...args: unknown[]) => routerState.push(...args), push: vi.fn(),
replace: 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 { CampaignWizardChromeProvider } from '@/components/campaign/shell/CampaignWizardChromeContext'
import { SidebarProvider } from '@/components/ui/Sidebar' import { SidebarProvider } from '@/components/ui/Sidebar'
import { WIZARD_STEP_PENDING_MESSAGE } from '@/lib/campaignWizardCopy' import { WIZARD_STEP_PENDING_MESSAGE } from '@/lib/campaignWizardCopy'
import { WIZARD_BACK_HISTORY_KEY } from '@/lib/wizardBack'
import { stubMatchMedia } from '../helpers/matchMedia' import { stubMatchMedia } from '../helpers/matchMedia'
const mountWizardNavigation = () => const mountWizardNavigation = () =>
@ -60,48 +61,67 @@ describe('wizard navigation pending', () => {
afterEach(() => { afterEach(() => {
cleanup() cleanup()
routerState.push.mockReset() routerState.replace.mockReset()
routerState.resolvePush = null routerState.resolveReplace = null
vi.unstubAllGlobals() vi.unstubAllGlobals()
}) })
it('dims step content and locks chrome while Voltar navigation is in flight', async () => { it('dims step content and locks chrome while Voltar navigation is in flight (B114)', async () => {
routerState.push.mockImplementation( routerState.replace.mockImplementation(
() => () =>
new Promise<void>((resolve) => { 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() 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 const stepBody = screen.getByRole('heading', { level: 1, name: 'Quantos votos?' }).parentElement
expect(stepBody).not.toBeNull() expect(stepBody).not.toBeNull()
expect(stepBody!.getAttribute('aria-busy')).not.toBe('true') expect(stepBody!.getAttribute('aria-busy')).not.toBe('true')
expect(stepBody!.getAttribute('data-pending')).toBeNull() expect(stepBody!.getAttribute('data-pending')).toBeNull()
const backLink = screen.getByRole('link', { name: /Voltar/ }) const backButton = screen.getByRole('button', { name: /Voltar/ })
await act(async () => { await act(async () => {
fireEvent.click(backLink) fireEvent.click(backButton)
}) })
expect(routerState.push).toHaveBeenCalledWith('/campanha/acoes/atualizar-votos', { await waitFor(() => {
expect(routerState.replace).toHaveBeenCalledWith('/campanha/acoes/atualizar-votos', {
scroll: true, scroll: true,
}) })
})
await waitFor(() => { await waitFor(() => {
expect(stepBody!.getAttribute('aria-busy')).toBe('true') expect(stepBody!.getAttribute('aria-busy')).toBe('true')
expect(stepBody!.getAttribute('data-pending')).toBe('true') expect(stepBody!.getAttribute('data-pending')).toBe('true')
}) })
expect(screen.getByText(WIZARD_STEP_PENDING_MESSAGE)).toBeTruthy() expect(screen.getByText(WIZARD_STEP_PENDING_MESSAGE)).toBeTruthy()
expect(backLink.getAttribute('aria-busy')).toBe('true') expect((backButton as HTMLButtonElement).disabled).toBe(true)
await waitFor(() => { await waitFor(() => {
expect(document.querySelector('[data-slot="skeleton"]')).toBeTruthy() expect(document.querySelector('[data-slot="skeleton"]')).toBeTruthy()
}) })
await act(async () => { await act(async () => {
routerState.resolvePush?.() routerState.resolveReplace?.()
}) })
expect(stepBody!.getAttribute('aria-busy')).not.toBe('true') expect(stepBody!.getAttribute('aria-busy')).not.toBe('true')