mirror of
https://github.com/fsolla/teqo.git
synced 2026-12-01 12:03:06 +00:00
Compare commits
9 commits
7c1f178d8d
...
2a568017cb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a568017cb | ||
|
|
729ce6fed4 | ||
|
|
89bf9d0854 | ||
|
|
1cc32a3d09 | ||
|
|
1a377f51df | ||
|
|
5ea288a88b | ||
|
|
feb8e6cab8 | ||
|
|
1c865bd822 | ||
|
|
9a66a23cf6 |
25 changed files with 1237 additions and 151 deletions
|
|
@ -4,6 +4,12 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
|||
|
||||
---
|
||||
|
||||
**OPS46 — infra de teste e2e: coleta local consertada (next/cache) + allocator de município sem colisão no wrap (2026-08-23):** entrega de dois débitos do OPS45 (capture-review-debts). **Fase 1 — e2e local não coleta:** `pnpm exec playwright test --list` falhava em todo spec com `Cannot find module 'node_modules/next/cache'` (e o diagnóstico correto do CI-vs-máquina: não há delta — o CI só roda pelo script `pnpm test:e2e`, que carrega `--conditions=react-server --import=tsx/esm` no `NODE_OPTIONS`; comando bare não tinha nada). Causa: `next@15` não declara `exports` → ESM nativo não resolve `next/cache` (o arquivo é `cache.js`), e `server-only` precisa da condição `react-server`. Fix no runner, zero mudança em produção: hook de resolução ESM vitest-free `tests/helpers/e2eEsmResolve.mjs` (mapeia `next/cache`→`next/cache.js` e injeta `react-server` nas conditions) registrada no processo main via `module.register` e propagada aos workers via `NODE_OPTIONS=--import=e2eEsmLoader.mjs` no `playwright.config.ts` — só quando os flags do script já não estão presentes. Aceite: bare `playwright test --list` coleta 198 testes em 41 arquivos (antes: 0); runs reais bare admin 5/5 e campaign 18/18; `pnpm test:e2e` intocado. **Fase 2 — allocator de município com wrap destrutivo:** a sequência persistente `campaign_fixture_municipality_alloc` nunca é resetada e um ciclo completo de suíte claima ~505 do catálogo de 435 (medido: 432 no int + 73 no e2e) → o wrap acontece em todo ciclo em DB persistente de worktree, e dois runs concorrentes podiam receber o mesmo índice e purgar as linhas vivas um do outro (purge-on-claim). Fix: registry de claims em módulo compartilhado vitest-free `tests/helpers/campaignMunicipalityAllocator.ts` — tabela `campaign_fixture_municipality_claims` (`index` PK, `run_id`, `claimed_at`), claim via `INSERT ON CONFLICT DO NOTHING RETURNING` (conflito = slot vivo → pula; claim stale >2h de run crashado → rouba; tudo ocupado → erro claro de exaustão), release no `cleanup()` dos dois fixtures (int + e2e, só quando claimaram). Guard estático novo no `testMunicipalityAllocatorConventions` (proíbe `nextval`/sequence fora do módulo) + spec int de stress `campaignMunicipalityAllocator.int.spec.ts` (exclusividade viva por 3 wraps, exaustão+recuperação, steal, release). Verificação: tsc/lint/format/cycles verdes (knip: limitação P3 pré-existente de não carregar payload.config, igual no HEAD), unit 2420 + int 819 (92 arquivos) verdes com tabela de claims zerada ao final, e2e local afetado (admin 5/5 + campaign 18/18 bare) verdes; importMap.js restaurado com envs `S3_*` dummy após o `--list` bare regenerá-lo sem elas (classe OPS69 — o guard do #87 cobre no CI). Impl plan: `docs/plans/ops46-infra-teste-e2e-local-allocator-impl.md`.
|
||||
|
||||
**E1 — extração do hook compartilhado de busca assíncrona com debounce (2026-08-23):** a 3ª cópia do efeito de busca async (requestId + `setTimeout(250)` + loading/failed) — introduzida pela C143 em `DemandResponsibleMultiSelect` (demand), e presente em `ResponsibleMultiSelect` (C90) e `AsyncSearchCombobox` — vira o hook `useAsyncSearchOptions({ open, query, search, isQueryReady? }) → { options, loading, failed }` (`src/hooks/useAsyncSearchOptions.ts`, novo; constante `ASYNC_SEARCH_DEBOUNCE_MS` exportada). Os 3 componentes consomem o hook e mantêm só o que é seu (grupos por typeLabel, avatares, headings de sugestões do município, `pinnedOptions`, filtro de selecionados, mensagens de vazio); semântica de query vazia preservada por consumidor (Demand busca sempre → sugestões; ResponsibleMultiSelect reseta via `isContactSearchQueryReady`; combobox com gate configurável — o efeito sync `selected←value` fica no componente). Fix pontual: server actions intocadas (continuam props — hook client-safe por injeção), sem schema/migration/access/Consent. Testes: spec unit novo `tests/unit/useAsyncSearchOptions.unit.spec.ts` (renderHook + fake timers, 9 casos: debounce/trim, coalesce, gate reset, closed, failed + retry, in-flight loading, out-of-order, quirk gate→not-ready com resposta stale pinado — comportamento herdado dos 3 originais, registrado na decisão D3 do impl plan). Impl plan `docs/plans/extrair-hook-busca-assincrona-debounce-impl.md`. Verificação: unit 2428 + int 815 verdes, e2e activity/demand (campaignActivity, campaignRegisterDemand, campaignDemandVisibility) verdes em re-run (1 flake de cold-compile pré-existente isolado), tsc/lint/format/cycles/build verdes; knip com o erro de load pré-existente (exit 0); fora de escopo: `WizardMunicipalitySearchStep` (4ª variante, AbortController — defer com gatilho no plano).
|
||||
|
||||
**S12 — âncora `#novidades` quebra no mobile — deep link não leva ao formulário (2026-08-23):** o deep link `jorgesolla1313.com.br/#novidades` (usado para direcionar tráfego orgânico/pago/WhatsApp para a captura) abria a home de campanha no topo no celular: a home é dona do container de scroll interno (`h-dvh overflow-y-auto`, body `overflow-hidden`), então a navegação nativa por fragmento não aterrissa no alvo, e no mobile o reflow do `h-dvh` + imagens eager do hero deslocam o layout após o scroll inicial. Fix contido: novo componente cliente `CampaignHashScroll` (renderiza null, montado no layout da home) que (1) no load direto com hash retenta o scroll até a seção entrar no viewport (rAF + timeouts, parando na primeira interação do usuário — wheel/touch/pointer/teclas de scroll) e (2) ouve `hashchange` para âncoras in-page (CTA do hero, `#bandeiras`, back/forward) sem tocar em `CampaignHero` (continua server component). `el.scrollIntoView()` sem `behavior` herda `scroll-smooth`/`motion-reduce:scroll-auto` do container — `prefers-reduced-motion` respeitado com zero JS. Sem mudança de visual, schema, formulário S9 ou modelo de scroll de outras rotas. E2E novos: describe mobile 390×844 (load direto, CTA, reduced-motion via `emulateMedia`) + load direto desktop (antes sem cobertura), com o teste de load direto desktop em describe próprio para não criar corrida no `beforeAll` de consent do describe de captura (purge+create não seguro sob workers paralelos). Verificação: lint/typecheck/unit + e2e `campaignNewsletter` e `campaignHomePixel` verdes locais; `gate:push` na entrega; PR em main com auto-merge.
|
||||
|
||||
**C142 — interface do /campanha respeita o perfil de permissão do assessor (2026-08-21):** a entrega fechada parte do C141 (que definiu os eixos `visibility`/`editing` no `campaignUser` e os gates server-side). Com o C142, a UI de todos os rascunhos staff do `/campanha` obedece de ponta a ponta o perfil de edição do assessor: com `editing = somente_leitura` não há nenhum controle de escrita em lugar nenhum (listas, detalhes, tabs, wizards); com `editing = tudo` o assessor enxerga/edita tudo o que vê; com `carteira` mantém o comportamento por carteira. Discriminação das entregas: (1) núcleo puro `src/lib/campaignAdvisorProfile.ts` com `advisorEditingScope()`/`rowEditingAllowed()` (retorna `none` para combinação incoerente `editing=tudo` + `visibility≠tudo`) e `gate: 'writable'` em `requireCampaignPageActor` (redireciona para `/campanha`); (2) todas as células compartilhadas (CampaignInlineEditableCell, MunicipalityRelationEditor, PhonesFieldEditor, DemandDescriptionEditor/Card/WorkflowCard, MunicipalityV2\*Cells, MunicipalityGoalAccountCard, ActivityTaskChecklist, SuggestionCard, MunicipalityPledgesPanel, etc.) ganharam o prop `readOnly`; (3) páginas staff — municípios (lista desktop+mobile, detalhe com tabs Overview/Updates/Leaderships/Suggestions, edição), pessoas (invite e criação gated), lideranças, dobradinhas, demandas, atividades, apoiadores, organizações — escondem os botões de criação (`Nova demanda`, `Nova atividade`, `Planejar giro`, `Novo`/`Importar CSV`, `Nova organização`, `Nova liderança`, `Nova dobradinha`) com `editingScope !== 'none'`; (4) home: `homeActionsForRole(role, editingScope)` filtra os 4 wizards para `somente_leitura` (sobra só o atalho de navegação); (5) `shouldMountQuickActionsFab` não monta o FAB para `somente_leitura`; (6) registry de quick actions (`resolveQuickActionsForPath`) recebe `editingScope` e filtra; (7) e2e novo `tests/e2e/campaignPermissionProfile.e2e.spec.ts` cobre os 3 perfis (somente_leitura sem controles, carteira com carteira, tudo com tudo) usando `createCampaignUser` com `visibility`/`editing`. Verificação: tsc/lint/format/knip/cycles/units (2419) + `gate:fast` verdes; PR em main com auto-merge (rebase); nada muda para coordinator/candidate/leader.
|
||||
|
||||
**S10 — Pixel do Meta (Facebook) na página pública de campanha (2026-08-19):** o time de campanha paga pode configurar o ID numérico do Pixel (Dataset do Events Manager) no admin — global `SiteSettings` → group "Rastreamento / Ads" → "ID do Pixel do Meta (Facebook)", mesma validação/normalização do precedente dos abaixo-assinados (5–20 dígitos, sem HTML/JS; regras agora vivem num único dono em `facebookPixel.ts`, com o `Petition` refatorado para o helper compartilhado). Com o ID configurado, a home pública de campanha (`/`) carrega o base code + `PageView` do Meta (injeção no layout do grupo `(home)` via `next/script`, escopada só à página de campanha — nada de PageView vazando para notícias/etc.); sem ID, nada é carregado (fail-closed). A conclusão da captura de novidades (S9) dispara exatamente um `Lead` (`content_name` "novidades-da-campanha", `eventID` UUID) no padrão do `PetitionForm` — nunca no page load. Leitura via `getCachedGlobal('site-settings')` (ISR sob a tag `global_site-settings`; a edição do admin já revalida a home). Migração `20260819_213947_add_site_settings_facebook_pixel_id` (colunas `tracking_facebook_pixel_id` + versão, sem backfill). Fora da fatia (gatilhos herdados do plano da petição): CAPI/Advanced Matching, dedup `eventID`, fila/retry de `Lead` e cookie banner/CMP. E2e novo `campaignHomePixel` (script `#meta-pixel-*` presente só com ID configurado, CDN stubada; `mode: serial` por precedente).
|
||||
|
|
|
|||
1
docs/changelog/2026-08-23-e1.md
Normal file
1
docs/changelog/2026-08-23-e1.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**E1 — extração do hook compartilhado de busca assíncrona com debounce (2026-08-23):** a 3ª cópia do efeito de busca async (requestId + `setTimeout(250)` + loading/failed) — introduzida pela C143 em `DemandResponsibleMultiSelect` (demand), e presente em `ResponsibleMultiSelect` (C90) e `AsyncSearchCombobox` — vira o hook `useAsyncSearchOptions({ open, query, search, isQueryReady? }) → { options, loading, failed }` (`src/hooks/useAsyncSearchOptions.ts`, novo; constante `ASYNC_SEARCH_DEBOUNCE_MS` exportada). Os 3 componentes consomem o hook e mantêm só o que é seu (grupos por typeLabel, avatares, headings de sugestões do município, `pinnedOptions`, filtro de selecionados, mensagens de vazio); semântica de query vazia preservada por consumidor (Demand busca sempre → sugestões; ResponsibleMultiSelect reseta via `isContactSearchQueryReady`; combobox com gate configurável — o efeito sync `selected←value` fica no componente). Fix pontual: server actions intocadas (continuam props — hook client-safe por injeção), sem schema/migration/access/Consent. Testes: spec unit novo `tests/unit/useAsyncSearchOptions.unit.spec.ts` (renderHook + fake timers, 9 casos: debounce/trim, coalesce, gate reset, closed, failed + retry, in-flight loading, out-of-order, quirk gate→not-ready com resposta stale pinado — comportamento herdado dos 3 originais, registrado na decisão D3 do impl plan). Impl plan `docs/plans/extrair-hook-busca-assincrona-debounce-impl.md`. Verificação: unit 2428 + int 815 verdes, e2e activity/demand (campaignActivity, campaignRegisterDemand, campaignDemandVisibility) verdes em re-run (1 flake de cold-compile pré-existente isolado), tsc/lint/format/cycles/build verdes; knip com o erro de load pré-existente (exit 0); fora de escopo: `WizardMunicipalitySearchStep` (4ª variante, AbortController — defer com gatilho no plano).
|
||||
1
docs/changelog/2026-08-23-ops46.md
Normal file
1
docs/changelog/2026-08-23-ops46.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**OPS46 — infra de teste e2e: coleta local consertada (next/cache) + allocator de município sem colisão no wrap (2026-08-23):** entrega de dois débitos do OPS45 (capture-review-debts). **Fase 1 — e2e local não coleta:** `pnpm exec playwright test --list` falhava em todo spec com `Cannot find module 'node_modules/next/cache'` (e o diagnóstico correto do CI-vs-máquina: não há delta — o CI só roda pelo script `pnpm test:e2e`, que carrega `--conditions=react-server --import=tsx/esm` no `NODE_OPTIONS`; comando bare não tinha nada). Causa: `next@15` não declara `exports` → ESM nativo não resolve `next/cache` (o arquivo é `cache.js`), e `server-only` precisa da condição `react-server`. Fix no runner, zero mudança em produção: hook de resolução ESM vitest-free `tests/helpers/e2eEsmResolve.mjs` (mapeia `next/cache`→`next/cache.js` e injeta `react-server` nas conditions) registrada no processo main via `module.register` e propagada aos workers via `NODE_OPTIONS=--import=e2eEsmLoader.mjs` no `playwright.config.ts` — só quando os flags do script já não estão presentes. Aceite: bare `playwright test --list` coleta 198 testes em 41 arquivos (antes: 0); runs reais bare admin 5/5 e campaign 18/18; `pnpm test:e2e` intocado. **Fase 2 — allocator de município com wrap destrutivo:** a sequência persistente `campaign_fixture_municipality_alloc` nunca é resetada e um ciclo completo de suíte claima ~505 do catálogo de 435 (medido: 432 no int + 73 no e2e) → o wrap acontece em todo ciclo em DB persistente de worktree, e dois runs concorrentes podiam receber o mesmo índice e purgar as linhas vivas um do outro (purge-on-claim). Fix: registry de claims em módulo compartilhado vitest-free `tests/helpers/campaignMunicipalityAllocator.ts` — tabela `campaign_fixture_municipality_claims` (`index` PK, `run_id`, `claimed_at`), claim via `INSERT ON CONFLICT DO NOTHING RETURNING` (conflito = slot vivo → pula; claim stale >2h de run crashado → rouba; tudo ocupado → erro claro de exaustão), release no `cleanup()` dos dois fixtures (int + e2e, só quando claimaram). Guard estático novo no `testMunicipalityAllocatorConventions` (proíbe `nextval`/sequence fora do módulo) + spec int de stress `campaignMunicipalityAllocator.int.spec.ts` (exclusividade viva por 3 wraps, exaustão+recuperação, steal, release). Verificação: tsc/lint/format/cycles verdes (knip: limitação P3 pré-existente de não carregar payload.config, igual no HEAD), unit 2420 + int 819 (92 arquivos) verdes com tabela de claims zerada ao final, e2e local afetado (admin 5/5 + campaign 18/18 bare) verdes; importMap.js restaurado com envs `S3_*` dummy após o `--list` bare regenerá-lo sem elas (classe OPS69 — o guard do #87 cobre no CI). Impl plan: `docs/plans/ops46-infra-teste-e2e-local-allocator-impl.md`.
|
||||
1
docs/changelog/2026-08-23-s12.md
Normal file
1
docs/changelog/2026-08-23-s12.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**S12 — âncora `#novidades` quebra no mobile — deep link não leva ao formulário (2026-08-23):** o deep link `jorgesolla1313.com.br/#novidades` (usado para direcionar tráfego orgânico/pago/WhatsApp para a captura) abria a home de campanha no topo no celular: a home é dona do container de scroll interno (`h-dvh overflow-y-auto`, body `overflow-hidden`), então a navegação nativa por fragmento não aterrissa no alvo, e no mobile o reflow do `h-dvh` + imagens eager do hero deslocam o layout após o scroll inicial. Fix contido: novo componente cliente `CampaignHashScroll` (renderiza null, montado no layout da home) que (1) no load direto com hash retenta o scroll até a seção entrar no viewport (rAF + timeouts, parando na primeira interação do usuário — wheel/touch/pointer/teclas de scroll) e (2) ouve `hashchange` para âncoras in-page (CTA do hero, `#bandeiras`, back/forward) sem tocar em `CampaignHero` (continua server component). `el.scrollIntoView()` sem `behavior` herda `scroll-smooth`/`motion-reduce:scroll-auto` do container — `prefers-reduced-motion` respeitado com zero JS. Sem mudança de visual, schema, formulário S9 ou modelo de scroll de outras rotas. E2E novos: describe mobile 390×844 (load direto, CTA, reduced-motion via `emulateMedia`) + load direto desktop (antes sem cobertura), com o teste de load direto desktop em describe próprio para não criar corrida no `beforeAll` de consent do describe de captura (purge+create não seguro sob workers paralelos). Verificação: lint/typecheck/unit + e2e `campaignNewsletter` e `campaignHomePixel` verdes locais; `gate:push` na entrega; PR em main com auto-merge.
|
||||
99
docs/plans/ancora-novidades-mobile-impl.md
Normal file
99
docs/plans/ancora-novidades-mobile-impl.md
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
# Impl: Âncora #novidades quebra no mobile — deep link não leva ao formulário
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-08-23
|
||||
Issue: #780
|
||||
Intenção: docs/plans/ancora-novidades-mobile.md
|
||||
Appetite restante: herdado — fix contido em 1 componente cliente novo + 1 spec; sem corte
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** abrir `jorgesolla1313.com.br/#novidades` no celular leva o visitante à seção do formulário de captura; o CTA "Receba novidades" do hero rola até a seção no mobile; desktop sem regressão; respeita `prefers-reduced-motion`. Cada visita que não chega ao formulário é audiência perdida na janela eleitoral (tráfego orgânico/pago/WhatsApp apontará para essa URL).
|
||||
- **O que NÃO negociar:** contrato de URL pública `#novidades`; layout/visual da home (anti-goal); modelo de scroll das rotas `(frontend)` (container interno com `overflow-hidden` no body — fora de escopo removê-lo); fluxo do formulário S9 (consent fail-closed, transação, copy); invariantes AGENTS (identificadores em inglês, copy pt-BR, sem abstração <3 call sites, direção lib → utilities → components → app).
|
||||
- **O que reavaliar:** (a) a hipótese de que o click no CTA é interceptado pelo Next e "não aterrissa" — o e2e atual prova que no desktop o `<a href="#novidades">` puro JÁ funciona (CampaignHero.tsx:104), então o click nativo + `hashchange` é o caminho, não uma interceptação a combater; (b) a hipótese de que o problema é só o load direto — no mobile o colapso é o `h-dvh` (URL bar) + imagens `loading="eager"` do hero deslocando o layout após o scroll inicial do browser; (c) Opção A (rolar à seção) vs B (rolar ao formulário) — mantida A (a seção é o contrato publicado; o formulário fica na mesma tela).
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[Load direto /#novidades no mobile] --> B[CampaignHashScroll<br/>montado no layout da home]
|
||||
B --> C{location.hash no mount?}
|
||||
C -->|sim| D[retry-until-in-viewport<br/>rAF + timeouts; stop em interação do usuário]
|
||||
D --> E[el.scrollIntoView - behavior auto]
|
||||
C -->|não| F[aguarda hashchange]
|
||||
F --> G[CTA hero / #bandeiras / back-forward<br/>disparam hashchange]
|
||||
G --> E
|
||||
E --> H[Container da home rola<br/>scroll-smooth · motion-reduce:scroll-auto]
|
||||
H --> I[Seção #novidades com formulário visível]
|
||||
```
|
||||
|
||||
**Opções consideradas:** A | B | C | D | E
|
||||
**Recomendação:** A — um componente cliente `CampaignHashScroll` (renderiza `null`) montado dentro do container de scroll do layout da home; no mount com hash inicial faz retry-until-in-viewport (o layout móvel assenta depois: colapso do `h-dvh` + imagens `eager` do hero); um listener de `hashchange` cobre o CTA do hero, `#bandeiras` e back/forward sem tocar em `CampaignHero` (que continua `<a href="#novidades">` puro, server component). O scroll usa `el.scrollIntoView()` sem `behavior` — `behavior: auto` herda o `scroll-behavior` do container, então `scroll-smooth` rege no normal e `motion-reduce:scroll-auto` já respeita reduced-motion (0 JS extra de a11y). É o mesmo mecanismo que já funciona no desktop (scroll nativo do fragmento) e o mesmo padrão de `scrollIntoView` de CampaignStorySection:16 com o defer de rAF de CampaignAISidebarShell:96 — sem mecanismo paralelo: o componente é o dono único da preocupação.
|
||||
**Rejeitadas:**
|
||||
|
||||
- **B (onClick + scrollIntoView no CTA do hero, padrão CampaignStorySection):** cobre o clique mas NÃO cobre o deep link de load direto (aceite 1 falha) — exigiria um segundo mecanismo para o mount; e `CampaignHero` é server component, o onClick forçaria torná-lo cliente. O `hashchange` cobre o clique com zero mudança no hero.
|
||||
- **C (mudar o modelo de scroll global — tirar `overflow-hidden` do body, scroll no document):** fora de escopo declarado da intenção; afeta TODAS as rotas `(frontend)`; o container interno é o modelo histórico escolhido para o comportamento mobile (dvh/URL bar) — reverter é arriscado na janela eleitoral.
|
||||
- **D (solução só CSS — `scroll-padding`/`scroll-behavior` no html/body):** o window/document não rola (body `overflow-hidden`, layout.tsx:82); CSS de âncora nativa não aterrissa no container aninhado nem resolve o deslocamento pós-load das imagens.
|
||||
- **E (Next `<Link>`/`router.push` com hash):** mudaria o CTA para cliente; `router.push` com hash no App Router tem histórico de não rolar containers aninhados (o Next atua no document); troca um mecanismo que parcialmente funciona por outro com o mesmo risco.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **NOVO `CampaignHashScroll`** (`src/components/CampaignHashScroll.tsx`): `'use client'`, renderiza `null`. Responsabilidades: (1) deep link no mount — resolve o alvo por `getElementById(hash)` e agenda tentativas (rAF + timeouts progressivos, parando quando o alvo entra no viewport ou na primeira interação de scroll/wheel/touch do usuário — one-time listeners); (2) `hashchange` → resolve e rola o alvo (cobre CTA do hero, `#bandeiras` do footer/form, back/forward). Sempre `el.scrollIntoView()` sem `behavior` (herda `scroll-smooth`/`motion-reduce:scroll-auto` do container). `scroll-mt-4` existente da seção (CampaignNewsletterSection.tsx:17) já serve de offset — `scrollIntoView` respeita `scroll-margin`. Depth check: não existe módulo de scroll-por-hash no repo (achado 5) — o componente é o dono; lógica não vai para lib/hook (1 call site).
|
||||
- **`src/app/(frontend)/(home)/layout.tsx`**: monta `<CampaignHashScroll />` como filho do div de scroll (linha 17–23); nenhuma mudança no modelo de scroll nem nas classes.
|
||||
- **`src/components/CampaignHero.tsx`**: sem mudança — CTA continua `<a href="#novidades">` puro (server component); o `hashchange` disparado pelo clique nativo aciona o scroll.
|
||||
- **`tests/e2e/campaignNewsletter.e2e.spec.ts`**: novo describe mobile + testes de load direto e reduced-motion (detalhe em "Fases").
|
||||
- **Migration:** sem migration (nenhuma mudança de schema).
|
||||
- **Access / Consent:** sem mudança — fluxo S9 intacto (o formulário nem é tocado).
|
||||
- **UI:** sem mudança visual (anti-goal da intenção); `scroll-mt-4` existente faz o papel de offset.
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
Sem dados novos; a única "forma" é o **alvo do scroll** (pergunta 3 de data-presentation aplicada à âncora): **Opção A (seção `#novidades`)** — é o contrato de URL publicado e mantido no aceite; o heading dá contexto de onde o visitante chegou e o formulário começa na mesma tela (a seção tem heading + form, ~um viewport de 844px). **Rejeitada B (formulário interno):** id interno de formulário não é contrato público; rolar direto ao form perderia o contexto do heading; e o aceite diz "a seção do formulário". `block: 'start'` (default) com o `scroll-mt-4` existente, não `center` (o `center` de CampaignStorySection serve ao vídeo, não a uma seção de captura).
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer (deep link no mount)** — criar `CampaignHashScroll` com o caminho do hash inicial (retry-until-in-viewport mínimo: rAF + 2–3 timeouts), montar no `(home)/layout.tsx`. Verificação manual em dev mobile (devtools iPhone, `/#novidades`) + desktop. Gate: `pnpm lint` + `pnpm typecheck`.
|
||||
2. **Interação + robustez** — listener `hashchange` (CTA mobile/desktop, `#bandeiras`, back/forward) e stop em interação do usuário. Verificação manual: clique no CTA mobile; voltar no histórico. Gate: `pnpm lint` + `pnpm typecheck`.
|
||||
3. **E2E + gates** — no `campaignNewsletter.e2e.spec.ts`: describe mobile com `test.use({ viewport: { width: 390, height: 844 } })` (padrão campaignHomeActions:149) com (a) load direto `/?e2e=<suffix>#novidades` → `expect(section).toBeInViewport()`; (b) CTA hero → URL `/#novidades` → seção no viewport; (c) mesmo teste (a) com `page.emulateMedia({ reducedMotion: 'reduce' })`; e no describe desktop atual, (d) load direto `/#novidades` (regressão de cobertura hoje inexistente). Manter o teste existente do CTA desktop intacto. Rodar `pnpm test:e2e campaignNewsletter --project=campaign` e a suíte desktop; fechar com `pnpm gate:fast`; push via `pnpm push`.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- Não criar utility/lib/hook genérico de hash-scroll (1 call site — Depth check).
|
||||
- Não tocar em `#bandeiras`/`#formulario`/`#detalhes`: o `hashchange` genérico os cobre de graça na home, mas sem teste dedicado — fora do pedido.
|
||||
- Não simular collapse de URL bar no e2e (comportamento real de browser, indeterminístico) — o viewport mobile pinna o contrato; o colapso é mitigado pelo retry, não testado.
|
||||
- Não mudar `CampaignHero`, `CampaignNewsletterForm`/`CampaignNewsletterSection`, footer nem outras rotas `(frontend)`.
|
||||
- Não mexer no modelo de scroll global (`overflow-hidden` do body).
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Next interceptar o clique em âncora pura e não disparar `hashchange`** (comportamento version-dependent do App Router): o e2e do CTA mobile+desktop pinna o contrato; se falhar, estender o MESMO componente com um listener de click em `a[href^="#"]` (sem mecanismo paralelo — continua um dono).
|
||||
- **Retry loop brigar com o scroll do usuário** (visitante começa a rolar durante o deep link): stop em scroll/wheel/touchstart (one-time) + teto de tentativas — o retry nunca luta com o usuário.
|
||||
- **Flakiness de timing no e2e**: `toBeInViewport` auto-retenta e o retry do componente torna o aterrissar determinístico (não depende de um único timeout).
|
||||
- **Imagens `eager` do hero terminarem de carregar depois do scroll inicial**: coberto pelo retry-until-in-viewport (re-tenta após os shifts de layout, incluindo o do `h-dvh`).
|
||||
- **Regressão desktop do CTA**: o teste existente permanece na suíte; o novo teste de load direto desktop cobre o caminho que hoje não tem nenhuma cobertura.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto: deep link `/#novidades` no mobile leva à seção do formulário; CTA do hero no mobile rola até a seção; desktop sem regressão; `prefers-reduced-motion` respeitado (via `motion-reduce:scroll-auto` herdado + e2e com `emulateMedia`)
|
||||
- [ ] Invariantes AGENTS/engineering-standards: identificadores em inglês; copy pt-BR intocada; sem abstração <3 call sites (1 componente, 1 mount); direção lib → utilities → components → app (componente em `src/components`, montado no app)
|
||||
- [ ] Testes de domínio previstos: e2e mobile (load direto + CTA + reduced-motion) e desktop (load direto novo + CTA existente); sem unit/int novos — nenhum access/write path muda
|
||||
|
||||
---
|
||||
|
||||
### Self-score decision-quality: 5/5
|
||||
|
||||
1. **Decisões caras têm rejeitadas?** Sim — abordagem (A–E com motivo por rejeitada), alvo de scroll (A vs B) e o não-tocar em `CampaignHero`/modelo global estão documentados com porquês.
|
||||
2. **Abordagem cabe no appetite?** Sim — 1 componente novo (renderiza null, ~40 linhas), 1 linha no layout, 1 spec: dentro do appetite herdado da S12, sem corte.
|
||||
3. **Rabbit holes nomeados?** Sim — lib/hook genérico, âncoras fora do pedido, simulação de URL bar, modelo de scroll global, formulário S9.
|
||||
4. **Depth check?** Sim — reusa o padrão `scrollIntoView` (CampaignStorySection:16), o defer rAF (CampaignAISidebarShell:96), o `scroll-mt-4` existente e o padrão de viewport mobile dos e2e (campaignHomeActions:149); não cria utility nova para 1 call site.
|
||||
5. **Intenção preservada?** Sim — o aceite de produto (deep link mobile → seção, CTA → seção, desktop ok, reduced-motion) permanece intacto; a engenharia só entrega o scroll no container dono, sem reescrever layout, formulário ou modelo de scroll.
|
||||
|
||||
---
|
||||
|
||||
## Débitos deferidos (triage do /simplify, 2026-08-23)
|
||||
|
||||
- **Duplicação de asserções de âncora entre specs** (teste mobile CTA vs `frontend.e2e.spec.ts`): defer — absorver como variação de viewport quando o `frontend.e2e.spec.ts` ou um teste de âncora for mexido.
|
||||
- **`[type]`/`artigos` herdam o modelo de scroll que causou o S12**: defer — gatilho: adicionar âncora in-page nesses layouts (nota de 1 linha já no JSDoc do `CampaignHashScroll`).
|
||||
- **Retry fixo 5×150ms é premissa não observada**: defer — gatilho: hero ganhar imagens não-eager / regressão de CLS observada no deep link.
|
||||
- **Teste reduced-motion com asserção fraca**: defer — mesclar com o item da duplicação de spec se um dia registrar.
|
||||
- **Pin e2e do `#bandeiras`/back-forward**: descartado — decisão travada no impl plan (fora do escopo do fix contido).
|
||||
113
docs/plans/extrair-hook-busca-assincrona-debounce-impl.md
Normal file
113
docs/plans/extrair-hook-busca-assincrona-debounce-impl.md
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
# Impl: Extrair hook compartilhado de busca assíncrona com debounce (3ª cópia)
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-08-23
|
||||
Issue: #765
|
||||
Intenção: body é spec (E1 — não há link de plano; a spec é a própria intenção citada)
|
||||
Appetite restante: fix pontual P2 — sem appetite declarado no body; tratado como fix pontual (refactor estrutural sem schema/server/migration)
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** a 3ª cópia do efeito de busca assíncrona com debounce (requestId + `setTimeout` 250ms + loading/failed) desaparece: um hook compartilhado `useAsyncSearchOptions({ open, query, search }) → { options, loading, failed }` é consumido por `DemandResponsibleMultiSelect` (C143), `ResponsibleMultiSelect` (C90) e `AsyncSearchCombobox`; cada componente mantém só o que é seu (grupos, avatar, sugestões, caps).
|
||||
- **O que NÃO negociar:** comportamento idêntico nos 3 call sites (fix pontual — nenhuma mudança de UX); a semântica de query vazia **difere** entre os 3 e o hook não pode unificá-la; padrão `searchRef`/`isQueryReadyRef` preservado; server actions intocadas (continuam como props); `WizardMunicipalitySearchStep` (4ª variante, AbortController/requestSeq) fica fora; copy pt-BR e identificadores em inglês.
|
||||
- **O que reavaliar:** a intenção propõe `T extends { id: string }` — **errado contra o código**: os três tipos reais (`RelationOption`, `ResponsibleOption`, `AsyncSearchOption`) usam `id: number` (D2). A intenção não fixa onde o hook mora — a exploração mostra que `src/hooks/` tem só `use-mobile.ts` (viewport), hooks de campanha hoje colacam no domínio (`useMicTranscript` em `shell/ai/`, `useHomeSearchQuery` em `dashboard/`) e `src/lib/campaignLongPress.ts` já hospeda um hook; a fronteira é deliberada em D1.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph hook["src/hooks/useAsyncSearchOptions.ts (novo — folha, client-safe)"]
|
||||
H["useAsyncSearchOptions<T extends { id: number }>({ open, query, search, isQueryReady? })"]
|
||||
OUT["{ options: T[]; loading: boolean; failed: boolean }"]
|
||||
H --> OUT
|
||||
end
|
||||
H --> C1["DemandResponsibleMultiSelect — sem gate (query vazia busca; server devolve sugestões do município)"]
|
||||
H --> C2["ResponsibleMultiSelect — isQueryReady={isContactSearchQueryReady} (reset quando não-pronta)"]
|
||||
H --> C3["AsyncSearchCombobox — isQueryReady configurável (a prop segue no componente p/ render do vazio)"]
|
||||
```
|
||||
|
||||
**Opções consideradas:** D1–D5 abaixo (fronteira de módulo, API/generics, gate, fronteira hook×componente, exports/teste).
|
||||
|
||||
**Recomendação:** novo módulo `src/hooks/useAsyncSearchOptions.ts` exportando `useAsyncSearchOptions<T extends { id: number }>` + `ASYNC_SEARCH_DEBOUNCE_MS` (250) + o tipo do resultado; os 3 componentes trocam o efeito duplicado por uma chamada ao hook, passando `search` (server action já recebida por prop — o hook fica client-safe por injeção) e, onde existem, seus gates (`isContactSearchQueryReady` no `ResponsibleMultiSelect`, gate configurável no `AsyncSearchCombobox`, nenhum no `DemandResponsibleMultiSelect`). Teste unitário do hook com `renderHook` + fake timers (padrão `campaignHomeSearchQuery.unit.spec.ts`). Nada de schema/server/access/Consent; sem migration.
|
||||
|
||||
**Rejeitadas:** ver D1–D5.
|
||||
|
||||
### Decisões de engenharia
|
||||
|
||||
**D1 — Onde mora o hook (fronteira de módulo; caro de reverter).**
|
||||
Opções: A) `src/hooks/useAsyncSearchOptions.ts` (novo, junto a `use-mobile.ts`) | B) `src/lib/useAsyncSearchOptions.ts` | C) `src/components/campaign/shared/useAsyncSearchOptions.ts`.
|
||||
Recomendação: **A** — (1) `src/hooks/` é o home designado de hooks React do repo e **não é pinado**: o pin de top-level de `codebaseConventions.unit.spec.ts` (L389) cobre só `src/utilities/` — um módulo novo em `src/hooks/` não exige registro nem atualização de spec; (2) direção de dependência: `src/hooks/` é folha do DAG (importa só `react`), importável de `components/` sem ciclo (madge confirma) — a cadeia `lib/ → utilities/ → components/ → app/` não é violada; (3) o hook é deliberadamente genérico (não conhece vocabulário de campanha: `T` e gate são injetados), então uma localização em path de campanha superestimaria a posse do domínio; (4) sem diretiva `'use client'` (módulo client-safe folha consumido só por client components, como `use-mobile.ts`).
|
||||
Alternativas rejeitadas: B — o único hook em `lib/` (`useCampaignLongPress` em `campaignLongPress.ts`) está colocado ali por coesão de módulo (hook + constante `CAMPAIGN_LONG_PRESS_MS` + handlers próprios no mesmo arquivo); `useAsyncSearchOptions` não tem lógica lib-side para colocar junto (`isContactSearchQueryReady` fica no módulo lib existente, injetado como prop — depth check), então em `lib/` o hook alargaria a exceção "React em lib" sem payoff de coesão e borraria "lib = helpers puros" para leitores futuros; C — os precedentes de colação (`useMicTranscript`, `useHomeSearchQuery`) são hooks **privados de feature** com estado acoplado à feature; este hook atravessa `demand/` + `shared/` e sua API não referencia tipos de campanha, e `shared/` comunica "componente compartilhado de campanha" — localização enganosa para um consumidor genérico futuro.
|
||||
|
||||
**D2 — API do hook e debounce.**
|
||||
Opções: A) `T extends { id: string }` (como sugerido na intenção) | B) `T extends { id: number }` | C) `T` sem constraint | D) debounce como prop opcional com default 250.
|
||||
Recomendação: **B + debounce fixo** — os três call sites reais têm `id: number` (`RelationOption`, `ResponsibleOption`, `AsyncSearchOption`); a constraint documenta o shape e rejeita consumidor divergente sem custo (o hook não inspeciona `id` — filtragem fica nos componentes). Debounce fixo: os 3 usam 250ms hoje; prop é especulação (YAGNI). A constante é **exportada** (`ASYNC_SEARCH_DEBOUNCE_MS`), espelhando os precedentes do repo (`HOME_SEARCH_DEBOUNCE_MS` em `campaignHomeSearchContract.ts`, `CAMPAIGN_LONG_PRESS_MS` em `campaignLongPress.ts`) — é o que permite o teste com fake timers sem hardcode.
|
||||
Alternativas rejeitadas: A — nenhum call site usa `id: string`; constraint errada contra o código; C — perde a documentação do shape mínimo e permite uso divergente; D — barato de adicionar depois (gatilho: 4º consumidor com debounce ≠ 250ms); não decidir agora é a decisão.
|
||||
|
||||
**D3 — Gate de query mínima (muda API pública do hook — registrar).**
|
||||
Opções: A) prop opcional `isQueryReady?: (query: string) => boolean`, default `() => true`, lida via ref (padrão `isQueryReadyRef` preservado) e checada **dentro do efeito, antes do timeout**, com reset `options/loading/failed` quando false | B) hook sempre busca; gate fica fora (cada componente pré-filtra) | C) unificar: o hook aplica `isContactSearchQueryReady` por default.
|
||||
Recomendação: **A** — reproduz borda a borda os 3 comportamentos: `DemandResponsibleMultiSelect` busca sempre (default `() => true`; query vazia → server devolve sugestões de assessores do município — fill-in C143), `ResponsibleMultiSelect` reseta com `isContactSearchQueryReady` (L80-85), `AsyncSearchCombobox` com gate configurável (`DemandFields` município, `ContactCombobox` contato). O reset in-effect (options=[], loading=false, failed=false) é o mesmo código nos 2 gated e mora no hook; o guard `requestId` em then/catch/finally e o `cleanup` `clearTimeout` também. Trim: o hook aplica `query.trim()` internamente (os 3 trimmam hoje); server actions seguem trimmando defensivamente — intocadas. **Quirk preservado (pós-`/simplify` pinado por teste):** o branch de gate não-pronto **não invalida** o requestId em voo — herdado fielmente dos 3 originais, uma resposta stale ainda aterrissa depois do reset; o teste `stale in-flight response lands after the query turns not-ready` pinça o comportamento atual (defer com gatilho: um consumidor que exija invalidação real).
|
||||
Alternativas rejeitadas: B — o reset + guard vazaria para cada componente, recriando a duplicação que a entrega elimina; C — unificar mudaria comportamento (Demand ganharia um gate que não tem hoje) e a intenção é explícita: "a semântica de query vazia difere e o hook não pode unificá-la".
|
||||
|
||||
**D4 — Fronteira hook × componente (o que fica em cada um).**
|
||||
Opções: A) hook devolve só `{ options, loading, failed }` brutos; todo filtro/agrupamento/headings/caps fica no componente | B) hook também filtra selecionados (recebe `selected`) | C) hook devolve estado normalizado (grupos prontos).
|
||||
Recomendação: **A** — a filtragem difere entre os 3 (`Set<number>` de ids no Demand vs chave `relationTo:id` no Responsible vs `id !== selected?.id` no combobox), grupos por `typeLabel` só existem no Responsible, `pinnedOptions`/grupos fixos "Seleção"/"Selecionado"/"Resultados" só no combobox, `shortQuery`/headings "Sugestões do município"/"Assessores" e avatares só no Demand — nenhum conhecimento é comum; passar isso ao hook criaria API especulativa e pass-through (depth check: não criar).
|
||||
Alternativas rejeitadas: B — unificar a chave de filtro mudaria a semântica de dedupe do `ResponsibleMultiSelect` (`relationTo:id`); C — normalizar 3 formas distintas numa só é a duplicação inversa (o hook conheceria UI de 3 consumidores).
|
||||
|
||||
**D5 — Exports do módulo, "registro" e teste unitário.**
|
||||
Opções: A) módulo exporta o hook + `ASYNC_SEARCH_DEBOUNCE_MS` + tipo `UseAsyncSearchOptionsResult<T>`; teste unitário novo com `renderHook` + `vi.useFakeTimers` | B) sem tipo de retorno exportado; cobertura só pelos specs existentes dos consumidores.
|
||||
Recomendação: **A (execução ajustada pós-`/simplify`)** — "registrar o hook com type `useAsyncSearchOptions`" aqui significa exportar o hook com sua assinatura tipada (parâmetros `{ open, query, search, isQueryReady? }` + retorno `{ options: T[]; loading: boolean; failed: boolean }`) — **não há pin/registro a atualizar**: `src/hooks/` não é pinado (o pin de `codebaseConventions.unit.spec.ts:389` cobre só top-level de `src/utilities/`), knip valida o export consumido, e hook não é componente Payload (sem import map). **Ajuste:** o tipo `UseAsyncSearchOptionsResult<T>` ficou **local (não exportado)** — o revisor de qualidade apontou export especulativo com zero consumidores e o knip local (regra `types: error`) flagearia; a anotação de retorno interna o mantém como contrato documentado. Teste: `tests/unit/useAsyncSearchOptions.unit.spec.ts` (`.ts`, não `.tsx` — `renderHook` não exige JSX) no padrão de `campaignHomeSearchQuery.unit.spec.ts` (`renderHook` + `vi.useFakeTimers` + `vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS)`) — infra já existente (também `useMicTranscript`, `campaignCellAutosave`), **sem infra nova**. Como a `search` é injetada por prop (e não importada de módulo), o teste passa `vi.fn()` com resolves/rejects controlados — não há módulo server a mockar; o padrão de mock de `activityOverlay.unit.spec.tsx` (L20-23) continua valendo para os consumidores, que ficam intocados. Pós-`/simplify` o spec ganhou 3 casos pin (contratos mais sutis do hook): `loading === true` em voo, retry pós-falha, e o quirk gate→not-ready com resposta stale em voo (ver D3).
|
||||
Alternativas rejeitadas: B — a mecânica requestId/gate/debounce é a parte mais sutil da extração (fonte de regressão silenciosa) e hoje só é coberta indiretamente por e2e; o teste direto do hook é barato e pinaria o contrato que os 3 componentes passarão a compartilhar.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`useAsyncSearchOptions` + `ASYNC_SEARCH_DEBOUNCE_MS`** (`src/hooks/useAsyncSearchOptions.ts`, novo; tipo de retorno `UseAsyncSearchOptionsResult<T>` **local**, não exportado — knip `types: error`): estado `options/loading/failed`; refs `requestId`, `searchRef`, `isQueryReadyRef` (atribuídos no render, como hoje); efeito com `if (!open) return`; gate lido via ref **antes** do timeout (reset e return); `setTimeout(ASYNC_SEARCH_DEBOUNCE_MS)` → `setLoading(true)/setFailed(false)` → `search(query.trim())` com guards `requestId.current !== currentRequestId` em then/catch/finally; cleanup `clearTimeout`. Sem diretiva `'use client'` (folha client-safe, como `use-mobile.ts`). Deps do efeito: `[open, query]` — gate e search via ref, sem re-execução por identidade (padrão preservado).
|
||||
- **`DemandResponsibleMultiSelect`** (`src/components/campaign/demand/DemandResponsibleMultiSelect.tsx`): remove estados/refs L61-69 e o efeito L71-94; `const { options, loading, failed } = useAsyncSearchOptions({ open, query, search })` (sem gate — busca sempre). Mantém: `selected`/chips/avatar/`(criador)`/`lockCreator`/hidden inputs, `visibleOptions` (filtro por `selectedIds`), `shortQuery` e headings "Sugestões do município"/"Assessores", mensagens de vazio.
|
||||
- **`ResponsibleMultiSelect`** (`src/components/campaign/shared/ResponsibleMultiSelect.tsx`): remove L67-76 e o efeito L78-107; hook com `isQueryReady={isContactSearchQueryReady}`. Mantém: `groups` por `typeLabel`, `atCapacity`, mensagem "Digite ao menos dois caracteres…" (o import de `isContactSearchQueryReady` permanece — usado no render, L224), hidden JSON, chips com `typeLabel`.
|
||||
- **`AsyncSearchCombobox`** (`src/components/campaign/shared/AsyncSearchCombobox.tsx`): remove estados/refs L49-60 e o efeito de busca L66-95; hook com `isQueryReady` (a prop continua no componente — usada no render do vazio, L189). **O efeito sync `selected←value` (L62-64) FICA no componente** (é contrato do combobox, não da busca). Mantém: `pinnedOptions`/`pinnedGroupHeading`, grupos "Seleção"/"Selecionado"/"Resultados", `choose()`, `emptyOptionLabel`, `queryTooShortMessage`.
|
||||
- **Consumers de `AsyncSearchCombobox`** (`DemandFields.tsx:85`, `ContactCombobox.tsx:38`, `ActivityTaskFields.tsx:98`): intocados (o gate é resolvido dentro do combobox).
|
||||
- **`tests/unit/useAsyncSearchOptions.unit.spec.ts`** (novo): ~5 `it` — debounce só dispara após `ASYNC_SEARCH_DEBOUNCE_MS`; query rápida em sequência cancela o timer anterior (só a última busca); gate não-pronto → reset sem chamar `search`; resposta fora de ordem descartada (requestId) e `catch` → `failed`, `finally` → `loading=false`; `open=false` não busca.
|
||||
- **Migration:** nenhuma (refactor client, sem schema). **Access / Consent:** nenhum (server actions intocadas; sem escrita nova, PII ou chave). **UI:** Impeccable A — refactor estrutural sem superfície nova.
|
||||
|
||||
### Dados → forma
|
||||
|
||||
N/A — refactor de estado de UI; nenhuma métrica, série, ranking ou mapa novo.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer / schema+server** — nada de schema/server (as server actions já são props dos 3 componentes e ficam intocadas; sem migration; sem access/Consent). O tracer é o próprio hook: criar `src/hooks/useAsyncSearchOptions.ts` + `tests/unit/useAsyncSearchOptions.unit.spec.ts` e rodar `pnpm gate:fast` — a mecânica requestId/debounce/gate fica provada isolada (renderHook + fake timers) antes de tocar os 3 componentes.
|
||||
2. **UI** — migrar os 3 componentes (ordem: `AsyncSearchCombobox` e `ResponsibleMultiSelect` em `shared/` primeiro, depois `DemandResponsibleMultiSelect` em `demand/`), mantendo em cada um só o que é seu (D4); registrar o hook com seu type público `useAsyncSearchOptions` (assinatura + `UseAsyncSearchOptionsResult<T>` exportados — sem pin a atualizar: `src/hooks/` não é pinado; knip valida o consumo). Rodar os e2e afetados da superfície antes do push: `pnpm test:e2e:affected` (activity + demand).
|
||||
3. **Gates** — `pnpm gate:fast`; `pnpm check:cycles` (hook é folha — sem ciclo), `pnpm format:check`, `pnpm exec knip`, `pnpm test` (unit + int — incl. `campaignDemandWorkflow.int.spec.ts`, que cobre o record de responsáveis C143), `pnpm build`; push via `pnpm push`.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- `WizardMunicipalitySearchStep.tsx:107-139` (4ª variante: POST + `AbortController` + `requestSeq`) — mecânica diferente; fora, como a intenção marca.
|
||||
- `useHomeSearchQuery` (`src/components/campaign/dashboard/useHomeSearchQuery.ts`) — debounce-only, sem requestId/loading/failed e com contrato de busca própria (`HOME_SEARCH_DEBOUNCE_MS` em lib); não é a mesma mecânica; sem gatilho para consolidar (1 variante).
|
||||
- Adicionar `AbortController` ao hook — os 3 hoje são guardados por requestId com cleanup só `clearTimeout`; abort mudaria o comportamento sob requisições lentas (o requestId descarta a resposta, não cancela o fetch). Defer com gatilho: call site que exija cancelamento real de rede.
|
||||
- Prop `debounceMs` — especulação (D2); gatilho: 4º consumidor com debounce ≠ 250ms.
|
||||
- Unificar a semântica de query vazia / normalizar grupos, pinned, headings ou avatares no hook — D3/D4.
|
||||
- Mexer nos specs existentes que mockam as server actions (`activityOverlay.unit.spec.tsx`, `activityAgendaInteractions.unit.spec.tsx` mockam `searchActivityResponsibleOptionsAction` na camada de componente) — continuam válidos; a action não muda.
|
||||
- DRY <3 call sites não é rabbit hole aqui — são exatamente 3 call sites reais com comportamentos divergentes (gate/sugestões/grupos), por isso o hook é fino e o resto fica nos componentes.
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Regressão silenciosa de comportamento em 3 superfícies:** mitigado por (a) equivalência borda-a-borda no diff (open/gate/trim/debounce/requestId em then/catch/finally/cleanup — cada linha do efeito removido tem correspondente no hook), (b) teste unitário do hook com fake timers e resolves controlados (inclui fora-de-ordem), (c) e2e afetados: `campaignActivity.e2e.spec.ts`, `campaignRegisterDemand.e2e.spec.ts`, `campaignDemandVisibility.e2e.spec.ts` + `tests/int/campaignDemandWorkflow.int.spec.ts` (C143).
|
||||
- **Gate mal copiado (reset fora do efeito):** o reset de `options/loading/failed` quando `isQueryReady` é false é parte da semântica de hoje (ResponsibleMultiSelect L80-85, AsyncSearchCombobox L68-73) — o hook o reproduz dentro do efeito, antes do timeout; teste cobre o caso.
|
||||
- **`requestId` off-by-one:** padrão idêntico ao atual (`++requestId.current` capturado, comparado em then/catch/finally); teste de resposta fora de ordem pinça.
|
||||
- **Ciclo de import:** hook importa só `react`; `check:cycles` confirma a folha do DAG.
|
||||
- **knip:** exports do hook consumidos pelos 3 componentes; `ASYNC_SEARCH_DEBOUNCE_MS` usado no spec — nenhum export órfão.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto: 3ª cópia eliminada; os três componentes consomem `useAsyncSearchOptions`; comportamento idêntico (debounce 250ms, requestId, loading/failed, gates por componente); cada um mantém grupos/avatar/sugestões/caps
|
||||
- [ ] Invariantes AGENTS/engineering-standards: hook client-safe por injeção (server actions continuam props — sem import server no hook); sem migration; sem access/Consent; identificadores em inglês; copy pt-BR intocada
|
||||
- [ ] Testes de domínio previstos: unit novo do hook (`renderHook` + fake timers) — access/write paths não mudam (server actions intocadas), então sem testes int novos; e2e afetados da superfície activity/demand rodados
|
||||
- [ ] Self-score decision-quality: 5/5 (abaixo)
|
||||
|
||||
## Self-score decision-quality: 5/5
|
||||
|
||||
1. **Decisões caras têm rejeitadas?** Sim — D1 (fronteira de módulo, caro) e D3 (API pública do hook com gate) têm opções e rejeitadas explícitas; D2/D4/D5 são baratas mas registradas porque a intenção exigiu deliberar a API (generics, debounce, fronteira hook×componente, teste).
|
||||
2. **Abordagem cabe no appetite?** Sim — fix pontual P2: refactor estrutural que **remove** ~90 linhas de efeito duplicado, sem schema/server/migration/UI nova; nada de AbortController, `debounceMs`, normalização ou unificação de gates.
|
||||
3. **Rabbit holes nomeados?** Sim — `WizardMunicipalitySearchStep`, `useHomeSearchQuery`, AbortController, `debounceMs`, unificação de query vazia/grupos, specs existentes que mockam as actions.
|
||||
4. **Depth check: reusa shells/helpers existentes?** Sim — reusa `isContactSearchQueryReady` (lib existente) como gate injetado (sem duplicar a lógica de query mínima); preserva os padrões `searchRef`/`isQueryReadyRef`; exporta a constante de debounce como os precedentes `HOME_SEARCH_DEBOUNCE_MS`/`CAMPAIGN_LONG_PRESS_MS`; sem pass-through (D4).
|
||||
5. **Intenção permanece satisfeita?** Sim — o hook extraído tem exatamente o shape da intenção `({ open, query, search }) → { options, loading, failed }` (com `isQueryReady` opcional para os gates existentes); os três consumidores o usam; comportamento preservado e coberto por unit + e2e — a engenharia não reescreveu o outcome.
|
||||
133
docs/plans/ops46-infra-teste-e2e-local-allocator-impl.md
Normal file
133
docs/plans/ops46-infra-teste-e2e-local-allocator-impl.md
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
# OPS46 — Infra de teste e2e: e2e local não coleta (next/cache) + allocator de município com wrap
|
||||
|
||||
Status: implementado
|
||||
Atualizado em: 2026-08-23
|
||||
Issue: #733
|
||||
Impl plan do plano de intenção: `docs/plans/ops46-infra-teste-e2e-local-allocator.md`
|
||||
|
||||
## Fase 1 — e2e local não coleta (`Cannot find module 'next/cache'`)
|
||||
|
||||
### Causa raiz (medida)
|
||||
|
||||
- `next@15.4.11` não declara `exports` no package.json → ESM nativo do Node
|
||||
**nunca** resolve o subpath `next/cache` (o arquivo existe como `cache.js`,
|
||||
mas ESM não tenta extensões — `ERR_MODULE_NOT_FOUND` com "Did you mean to
|
||||
import next/cache.js?").
|
||||
- `server-only` (0.0.1) resolve `index.js` (que lança) sem a condição de
|
||||
export `react-server` (`--conditions=react-server`).
|
||||
- `pnpm test:e2e` carrega ambas as correções via
|
||||
`NODE_OPTIONS="--no-deprecation --conditions=react-server --import=tsx/esm"`
|
||||
— por isso o CI passa: o CI nunca roda `playwright` bare, sempre via script.
|
||||
Qualquer invocação bare (extensão VS Code, `pnpm exec playwright test
|
||||
--list`, runs ad-hoc) quebra na coleta.
|
||||
- CI vs máquina: sem delta — o CI usa o mesmo comando com os mesmos flags;
|
||||
a hipótese do plano ("investigar o que difere no ambiente CI") se resolveu
|
||||
em "nada difere — o CI só roda pelo script".
|
||||
|
||||
### Abordagem implementada (aprovada no GATE)
|
||||
|
||||
Fix no nível do runner, zero mudança em código de produção:
|
||||
|
||||
1. `tests/helpers/e2eEsmResolve.mjs` — hook de resolução ESM com 2 rewrites:
|
||||
- `next/cache` → `next/cache.js` (entry oficial, TS mapeia para `cache.d.ts`);
|
||||
- injeta `react-server` nas `conditions` de resolução (equivalente exato do
|
||||
flag `--conditions=react-server`, aplicado em runtime via `nextResolve`).
|
||||
2. `tests/helpers/e2eEsmLoader.mjs` — entry `--import` que registra a hook
|
||||
(o padrão do tsx: `--import` só funciona se o módulo chamar `module.register`).
|
||||
3. `playwright.config.ts` — quando `NODE_OPTIONS` **não** tem
|
||||
`--conditions=react-server` (invocação bare): `register()` a hook no
|
||||
processo main (a coleta do `--list` acontece aqui, pós-load do config) e
|
||||
propaga `--import=<loader>` via `NODE_OPTIONS` para os workers (herdam o
|
||||
env no spawn). Com os flags presentes (script), nada muda.
|
||||
|
||||
### Opções rejeitadas
|
||||
|
||||
- `next/cache` → `next/cache.js` na fonte (~40 arquivos): toca código de
|
||||
produção para um problema de infra de teste e não resolve `server-only`
|
||||
(o comando bare continuaria quebrando); não idiomático.
|
||||
- Patch do `next` via pnpm `patchedDependencies` adicionando `exports`:
|
||||
exports parcial quebra qualquer subpath não listado; frágil por versão.
|
||||
- `--import`/flags no script apenas + documentar: não satisfaz o aceite
|
||||
(`pnpm exec playwright test --list` coleta na máquina do humano).
|
||||
|
||||
### Verificação Fase 1
|
||||
|
||||
- `pnpm exec playwright test --list` (bare, sem flags): **198 testes em 41
|
||||
arquivos** (antes: `Total: 0 tests in 0 files`).
|
||||
- Run real bare `--project=admin`: **5 passed** (workers com a hook).
|
||||
- Run real bare `--project=campaign` `campaignHomeActions`: **18 passed**.
|
||||
- `pnpm test:e2e --list` (script, flags): inalterado, 198.
|
||||
|
||||
## Fase 2 — allocator de município com wrap destrutivo
|
||||
|
||||
### Medição (plano: "medir primeiro")
|
||||
|
||||
- Claims por ciclo completo num DB persistente: **~505** (432
|
||||
`getMunicipality()` no int + 73 `claimMunicipality()` no e2e) > 435 do
|
||||
catálogo → o wrap acontece em **todo** ciclo de suíte completa. Bug agudo
|
||||
(não teórico): após o wrap, dois runs concorrentes podem receber o mesmo
|
||||
índice e o purge-on-claim de cada um apaga as linhas vivas do outro.
|
||||
|
||||
### Abordagem implementada
|
||||
|
||||
Registry de claims em módulo compartilhado vitest-free
|
||||
`tests/helpers/campaignMunicipalityAllocator.ts` (mesma convenção do
|
||||
`campaignResidue.ts` — importável pelo processo Playwright do e2e):
|
||||
|
||||
- Tabela `campaign_fixture_municipality_claims` (`index` PK, `run_id` text,
|
||||
`claimed_at` timestamptz default now()) criada lazy com a sequence
|
||||
(`CREATE IF NOT EXISTS`, corrida 23505 tolerada).
|
||||
- `claimMunicipalityIndex(payload, catalogSize, runID)`: `nextval` → índice →
|
||||
`INSERT ON CONFLICT ("index") DO NOTHING RETURNING`; conflito = run vivo
|
||||
segura o slot → pula; claim **stale** (TTL 2h, run crashado) → rouba e
|
||||
retenta; tudo ocupado por claims vivos → erro claro ("exhausted") em vez
|
||||
de colisão silenciosa.
|
||||
- `releaseMunicipalityClaims(payload, runID)`: `DELETE WHERE run_id` — chamado
|
||||
no `cleanup()` de ambos os fixtures (int `CampaignFixtures.cleanup`,
|
||||
e2e `CampaignE2EOwnership.cleanup`), só quando o fixture claimou
|
||||
(Set `claimedMunicipalityIndexes` — cleanup sem claims não toca a tabela).
|
||||
- O fixture int perdeu o allocator inline (`nextAllocatedMunicipalityIndex`
|
||||
- a sequence própria); o e2e idem (CREATE SEQUENCE + nextval inline).
|
||||
|
||||
### Guards e testes
|
||||
|
||||
- Guard estático novo no `testMunicipalityAllocatorConventions.unit.spec.ts`:
|
||||
proíbe `nextval(`/`campaign_fixture_municipality_alloc` em `tests/int`,
|
||||
`tests/e2e` e `tests/helpers` fora do módulo do allocator — todo claim passa
|
||||
pelo registry.
|
||||
- Spec int comportamental `tests/int/campaignMunicipalityAllocator.int.spec.ts`
|
||||
(catalogSize sintético, robusto a concorrência da suíte paralela):
|
||||
1. exclusividade viva através de múltiplos wraps (âncora segura 1 slot por
|
||||
120 claims de runs efêmeros > 3 wraps do espaço de 40);
|
||||
2. exaustão (erro claro) + recuperação após release;
|
||||
3. steal de claim stale (envelhecida 3h);
|
||||
4. release libera slots para reuso.
|
||||
|
||||
### Verificação Fase 2
|
||||
|
||||
- Spec do allocator: 4/4 verdes, estável em re-runs.
|
||||
- Suíte int completa: **92 arquivos / 819 testes, todos verdes** (o fixture
|
||||
refatorado claima ~432 municípios sob 8 workers paralelos).
|
||||
- Tabela de claims **zerada** ao final da suíte (release funcionando).
|
||||
- e2e campaign (`campaignHomeActions`, wizard com claims reais): 18/18, claims
|
||||
zeradas após o run.
|
||||
|
||||
## Riscos e notas
|
||||
|
||||
- A hook depende de `module.register` (estável desde Node 20.6); só ativa em
|
||||
invocações bare — o path do script (`pnpm test:e2e`) fica intocado e é o
|
||||
fallback se algo mudar.
|
||||
- TTL 2h > duração de qualquer run vivo; claim crashado bloqueia slots até o
|
||||
TTL (erro de exaustão menciona o prazo).
|
||||
- Um run vivo não pode claimar mais de `catalogSize` slots (a própria
|
||||
exclusividade exaure) — correto por design; fixtures reais liberam por
|
||||
teste.
|
||||
- Durante a entrega, o `--list` bare regenerou o `importMap.js` sem envs
|
||||
`S3_*` (classe OPS69/OPS70 #87, já documentada) — restaurado com
|
||||
`generate:importmap` + envs dummy.
|
||||
|
||||
## Aceite
|
||||
|
||||
- [x] Fase 1: `pnpm exec playwright test --list` coleta na máquina do humano
|
||||
- [x] Fase 2: sem colisão de claim após N wraps (stress test com wraps reais)
|
||||
- [x] Guards: `testMunicipalityAllocatorConventions` verde após a mudança
|
||||
62
docs/plans/worktree-launch-default-llm-max-gateway.md
Normal file
62
docs/plans/worktree-launch-default-llm-max-gateway.md
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
# Default de launch do worktree opencode passa a usar o DeepSeek na variante max servido pelo gateway da Vercel
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-08-23
|
||||
Issue: #784
|
||||
Priority: P2
|
||||
Impeccable: A — N/A sem UI
|
||||
Rascunho UI: N/A — sem UI
|
||||
Appetite: ~0,5–1 dia eng; um outcome verificável
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
Hoje `pnpm worktree next/plan/new` terminam abrindo o opencode com o DeepSeek no modo default, servido direto pelo provedor de inferência mais barato. A política mudou: a sessão que abre nesses lançamentos deve usar a variante de raciocínio mais forte (max) do DeepSeek, servida pelo gateway de IA da Vercel — rota com cache, estabilidade e failover, em vez da rota direta atual. Trocar o default é editar a constante do preset (o próprio mecanismo OPS26 diz "trocar de modelo é editar a constante"), mas hoje o repo não expõe a variante max nem o provider do gateway — este item expõe os dois e só isso. Não queremos mudar o cardápio de modelos de execução de Issues, nem a config de máquina do humano.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** dev que lança worktrees de planejamento/execução e cai direto numa sessão opencode com a tarefa pela frente.
|
||||
- **Job principal:** abrir a sessão do worktree já no modelo de raciocínio mais forte, sem nenhuma ação manual.
|
||||
- **Fluxo desejado:** rodar `pnpm worktree next/plan/new` → a sessão abre com a variante max servida pelo gateway → trabalho começa.
|
||||
- **Anti-goals de produto:** não trocar o modelo de execução de Issues (work-issue); não tocar no `~/.config/opencode/opencode.jsonc` do humano; não virar item de infra/credencial do gateway em si.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- Ao rodar cada um dos três comandos de launch, a sessão abre com a variante max via gateway — verificável pela linha de launch emitida pelo preset e pelos testes unitários atualizados.
|
||||
- Guardrails: nenhuma mudança no fluxo de execução de Issues; config global do humano intocada; docs históricos congelados.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
Dados: N/A — item de tooling/launch, sem superfície de dados.
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** `scripts/lib/worktree.mjs:23` (constante do preset, emitida em `:143`); testes `tests/unit/worktree.unit.spec.ts:151-197` e `tests/unit/opencodeCommands.unit.spec.ts:37`; repo `opencode.json` (adicionar provider OpenAI-compatible do gateway e expor a variante max); textos de doc `.agents/shell/worktree.sh:10`, `scripts/worktree.mjs:27,778`, `.agents/skills/worktree-next-issue/SKILL.md:34`.
|
||||
- **Precedente a olhar:** OPS26 (criou o preset e o mecanismo "trocar modelo = editar a constante"), OPS31/OPS25 (extensões do launch).
|
||||
- **Risco de acoplamento:** baixo — a constante é single source e os testes a seguram; qualquer mudança de string quebra testes, o que é a verificação do item.
|
||||
|
||||
## Dependências
|
||||
|
||||
- Nenhuma dura. Soft: provider do gateway disponível/validável no ambiente de dev local para o executor confirmar a rota.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Config global `~/.config/opencode/opencode.jsonc` do humano — fica de fora por decisão de produto.
|
||||
- Cardápio de modelos de execução de Issues (work-issue/plan-issue como comandos de trabalho) — não muda.
|
||||
- Documentos históricos (`docs/plans`, `docs/CHANGELOG-AGENTS.md`) — congelados, não editar.
|
||||
- Infra/credenciais do gateway — o repo só expõe o provider; chaves/endpoint continuam fora do repo.
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Só completar a string nos comandos".** Se alguém apenas trocar o modelo nos frontmatters dos comandos, muda a execução de Issues (fora de escopo) e ignora o provider do gateway. **Corte neste item:** a mudança é no default de LAUNCH do worktree (preset + provider no repo), não no cardápio de execução.
|
||||
- **"Configurar o gateway no global".** Se alguém criar o provider no opencode.jsonc global, vira config de máquina do humano e contamina todas as sessões. **Corte neste item:** provider no repo `opencode.json`, apenas para expor o caminho que o preset usa.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Os comandos de execução de Issues acompanham o novo default ou ficam como estão?** **Opções:** A) ficam como estão (execução = escolha estável, só o launch muda) | B) alinhar também. **Recomendação:** A — o item é o default de LAUNCH; o cardápio de execução é outro mecanismo e está fora de escopo.
|
||||
- **Onde expor a variante max: no provider do repo ou como flag no preset?** **Opções:** A) default no provider | B) flag nova (`--variant max`) na emissão do launch. **Recomendação:** A — default explícito no provider, mantendo a emissão atual de `--model` intacta e o teste unitário como guarda.
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue #784 (registro)
|
||||
- `scripts/lib/worktree.mjs` · `scripts/worktree.mjs` · `tests/unit/worktree.unit.spec.ts` · `opencode.json` · `.opencode/commands/work-issue.md` · `.opencode/commands/plan-issue.md` · `.agents/shell/worktree.sh` · `.agents/skills/worktree-next-issue/SKILL.md`
|
||||
|
|
@ -1,7 +1,35 @@
|
|||
import { register } from 'node:module'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
import { config as loadEnv } from 'dotenv'
|
||||
|
||||
import { assertTestDatabase } from './tests/helpers/assertTestDatabase'
|
||||
|
||||
/*
|
||||
* OPS46 — a bare `playwright test` (VS Code extension, `pnpm exec playwright
|
||||
* test --list`, ad-hoc runs) must collect like `pnpm test:e2e` does. That
|
||||
* script carries the needed flags in NODE_OPTIONS (`--conditions=react-server
|
||||
* --import=tsx/esm`); this block re-applies the same behavior when they are
|
||||
* absent:
|
||||
* - register() installs the resolution hook (tests/helpers/e2eEsmResolve.mjs)
|
||||
* in THIS process — test collection happens here after config load, which
|
||||
* is why a bare `--list` needs it in-process;
|
||||
* - the NODE_OPTIONS mutation hands the same hook to the worker processes
|
||||
* Playwright spawns for actual runs (they inherit the env at spawn).
|
||||
* When the flags are already present (the scripted path) nothing changes.
|
||||
*/
|
||||
const bareInvocation = !process.env.NODE_OPTIONS?.includes('--conditions=react-server')
|
||||
if (bareInvocation) {
|
||||
register(new URL('./tests/helpers/e2eEsmResolve.mjs', import.meta.url))
|
||||
const configDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const loaderEntry = path.join(configDir, 'tests', 'helpers', 'e2eEsmLoader.mjs')
|
||||
process.env.NODE_OPTIONS = [process.env.NODE_OPTIONS, `--import=${loaderEntry}`]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
import {
|
||||
GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV_NAME,
|
||||
GOOGLE_CALENDAR_TEST_KEY,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { CampaignHashScroll } from '@/components/CampaignHashScroll'
|
||||
import { MetaPixel } from '@/components/MetaPixel'
|
||||
import { getCampaignHomeMetaPixelId } from '@/utilities/campaignHomeTracking'
|
||||
import React from 'react'
|
||||
|
|
@ -19,6 +20,7 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
|
|||
className="relative h-dvh w-full scroll-smooth overflow-y-auto bg-(--campaign-cream) text-(--campaign-ink) motion-reduce:scroll-auto"
|
||||
>
|
||||
{pixelId ? <MetaPixel pixelId={pixelId} /> : null}
|
||||
<CampaignHashScroll />
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -36,7 +36,6 @@ import { ImportPreview as ImportPreview_cdf7e044479f899a31f804427d568b36 } from
|
|||
import { ImportSaveButton as ImportSaveButton_cdf7e044479f899a31f804427d568b36 } from '@payloadcms/plugin-import-export/rsc'
|
||||
import { InstagramSyncStatusPanel as InstagramSyncStatusPanel_90dd38ffecf41d93e389c788f98f48da } from '../../../components/admin/InstagramSyncStatusPanel'
|
||||
import { InstagramPostExclusionPicker as InstagramPostExclusionPicker_ba03418db242c21470543bbeb06827a0 } from '../../../components/admin/InstagramPostExclusionPicker'
|
||||
import { S3ClientUploadHandler as S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24 } from '@payloadcms/storage-s3/client'
|
||||
import { ImportExportProvider as ImportExportProvider_cdf7e044479f899a31f804427d568b36 } from '@payloadcms/plugin-import-export/rsc'
|
||||
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
|
||||
|
||||
|
|
@ -79,7 +78,6 @@ export const importMap = {
|
|||
"@payloadcms/plugin-import-export/rsc#ImportSaveButton": ImportSaveButton_cdf7e044479f899a31f804427d568b36,
|
||||
"./components/admin/InstagramSyncStatusPanel#InstagramSyncStatusPanel": InstagramSyncStatusPanel_90dd38ffecf41d93e389c788f98f48da,
|
||||
"./components/admin/InstagramPostExclusionPicker#InstagramPostExclusionPicker": InstagramPostExclusionPicker_ba03418db242c21470543bbeb06827a0,
|
||||
"@payloadcms/storage-s3/client#S3ClientUploadHandler": S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24,
|
||||
"@payloadcms/plugin-import-export/rsc#ImportExportProvider": ImportExportProvider_cdf7e044479f899a31f804427d568b36,
|
||||
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
|
||||
}
|
||||
|
|
|
|||
110
src/components/CampaignHashScroll.tsx
Normal file
110
src/components/CampaignHashScroll.tsx
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
|
||||
const MAX_ATTEMPTS = 5
|
||||
const RETRY_DELAY_MS = 150
|
||||
const SCROLL_KEYS = new Set(['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', ' '])
|
||||
|
||||
/**
|
||||
* S12 — the campaign home owns its scroll container (`h-dvh overflow-y-auto`
|
||||
* on the (home) layout; the body is `overflow-hidden`), so the browser's
|
||||
* native fragment navigation — which scrolls the document — never lands on a
|
||||
* hash target. On a direct `/#novidades` load the mobile layout settles only
|
||||
* after the `h-dvh` reflow and the hero's eager images, kicking the page back
|
||||
* to the top. (`[type]`/`artigos` share the same scroll-container model; if
|
||||
* they ever gain in-page anchors they inherit this mechanism.)
|
||||
*
|
||||
* Owner of hash scrolling on the home: on mount it retries the initial hash
|
||||
* until the target is in view (stopping at the first user interaction), and a
|
||||
* `hashchange` listener covers in-page anchors (hero CTA, footer `#bandeiras`,
|
||||
* back/forward). `el.scrollIntoView()` without `behavior` inherits the
|
||||
* container's `scroll-smooth` / `motion-reduce:scroll-auto`, so
|
||||
* `prefers-reduced-motion` is honored with zero extra JS. Renders nothing.
|
||||
*/
|
||||
export const CampaignHashScroll = () => {
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let frame: number | undefined
|
||||
let attempt = 0
|
||||
|
||||
const clearRetry = () => {
|
||||
if (timer !== undefined) clearTimeout(timer)
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
}
|
||||
|
||||
// Returns true when a scroll was issued and the retry should continue;
|
||||
// false when there is nothing to do (no hash, unknown target, or the
|
||||
// target is already in view).
|
||||
const scrollToHashIfNeeded = (): boolean => {
|
||||
const hash = window.location.hash
|
||||
if (hash.length < 2) return false
|
||||
let target: HTMLElement | null = null
|
||||
try {
|
||||
target = document.getElementById(decodeURIComponent(hash.slice(1)))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (!target) return false
|
||||
const rect = target.getBoundingClientRect()
|
||||
if (rect.top >= -8 && rect.top < window.innerHeight - 8) return false
|
||||
target.scrollIntoView()
|
||||
return true
|
||||
}
|
||||
|
||||
const retry = () => {
|
||||
clearRetry()
|
||||
if (attempt >= MAX_ATTEMPTS || !scrollToHashIfNeeded()) return
|
||||
attempt += 1
|
||||
// The mobile layout settles after the `h-dvh` reflow and the hero's
|
||||
// eager images; re-check after the frame has painted the scroll.
|
||||
frame = requestAnimationFrame(() => {
|
||||
timer = setTimeout(retry, RETRY_DELAY_MS)
|
||||
})
|
||||
}
|
||||
|
||||
// Never fight the user: stop retrying at the first real interaction.
|
||||
// Programmatic `scrollIntoView` does not fire these, so the retry itself
|
||||
// never cancels itself. Reinstalled whenever a `hashchange` starts a new
|
||||
// retry, so every loop runs guarded.
|
||||
const stopRetrying = () => {
|
||||
clearRetry()
|
||||
window.removeEventListener('wheel', stopRetrying)
|
||||
window.removeEventListener('touchstart', stopRetrying)
|
||||
window.removeEventListener('pointerdown', stopRetrying)
|
||||
window.removeEventListener('keydown', stopOnScrollKey)
|
||||
}
|
||||
|
||||
const stopOnScrollKey = (event: KeyboardEvent) => {
|
||||
if (SCROLL_KEYS.has(event.key)) stopRetrying()
|
||||
}
|
||||
|
||||
const installInteractionGuards = () => {
|
||||
window.addEventListener('wheel', stopRetrying, { passive: true })
|
||||
window.addEventListener('touchstart', stopRetrying, { passive: true })
|
||||
window.addEventListener('pointerdown', stopRetrying, { passive: true })
|
||||
window.addEventListener('keydown', stopOnScrollKey)
|
||||
}
|
||||
|
||||
const handleHashChange = () => {
|
||||
attempt = 0
|
||||
retry()
|
||||
installInteractionGuards()
|
||||
}
|
||||
|
||||
window.addEventListener('hashchange', handleHashChange)
|
||||
installInteractionGuards()
|
||||
retry()
|
||||
|
||||
return () => {
|
||||
clearRetry()
|
||||
window.removeEventListener('hashchange', handleHashChange)
|
||||
window.removeEventListener('wheel', stopRetrying)
|
||||
window.removeEventListener('touchstart', stopRetrying)
|
||||
window.removeEventListener('pointerdown', stopRetrying)
|
||||
window.removeEventListener('keydown', stopOnScrollKey)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return null
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
'use client'
|
||||
|
||||
import { ChevronsUpDownIcon, XIcon } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useState } from 'react'
|
||||
|
||||
import type { RelationOption } from '@/components/campaign/shared/RelationMultiSelect'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/Avatar'
|
||||
|
|
@ -16,6 +16,7 @@ import {
|
|||
CommandList,
|
||||
} from '@/components/ui/Command'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import { useAsyncSearchOptions } from '@/hooks/useAsyncSearchOptions'
|
||||
import { campaignUserInitials } from '@/utilities/campaignUserProfile'
|
||||
|
||||
export type DemandResponsibleOption = RelationOption & { avatarUrl?: string | null }
|
||||
|
|
@ -60,38 +61,7 @@ export const DemandResponsibleMultiSelect = ({
|
|||
const [selected, setSelected] = useState<DemandResponsibleOption[]>(value)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [options, setOptions] = useState<RelationOption[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const requestId = useRef(0)
|
||||
const searchRef = useRef(search)
|
||||
|
||||
searchRef.current = search
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
|
||||
const currentRequestId = ++requestId.current
|
||||
const timeout = window.setTimeout(() => {
|
||||
setLoading(true)
|
||||
setFailed(false)
|
||||
void searchRef
|
||||
.current(query.trim())
|
||||
.then((nextOptions) => {
|
||||
if (requestId.current !== currentRequestId) return
|
||||
setOptions(nextOptions)
|
||||
})
|
||||
.catch(() => {
|
||||
if (requestId.current !== currentRequestId) return
|
||||
setFailed(true)
|
||||
})
|
||||
.finally(() => {
|
||||
if (requestId.current === currentRequestId) setLoading(false)
|
||||
})
|
||||
}, 250)
|
||||
|
||||
return () => window.clearTimeout(timeout)
|
||||
}, [open, query])
|
||||
const { options, loading, failed } = useAsyncSearchOptions({ open, query, search })
|
||||
|
||||
const isCreator = (id: number) => creatorUserId != null && creatorUserId === id
|
||||
const selectedIds = new Set(selected.map((option) => option.id))
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
'use client'
|
||||
|
||||
import { ChevronsUpDownIcon } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
|
|
@ -13,6 +13,7 @@ import {
|
|||
CommandList,
|
||||
} from '@/components/ui/Command'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import { useAsyncSearchOptions } from '@/hooks/useAsyncSearchOptions'
|
||||
|
||||
export type AsyncSearchOption = {
|
||||
id: number
|
||||
|
|
@ -49,51 +50,12 @@ export const AsyncSearchCombobox = ({
|
|||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [selected, setSelected] = useState<AsyncSearchOption | null>(value)
|
||||
const [options, setOptions] = useState<AsyncSearchOption[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const requestId = useRef(0)
|
||||
const searchRef = useRef(search)
|
||||
const isQueryReadyRef = useRef(isQueryReady)
|
||||
|
||||
searchRef.current = search
|
||||
isQueryReadyRef.current = isQueryReady
|
||||
const { options, loading, failed } = useAsyncSearchOptions({ open, query, search, isQueryReady })
|
||||
|
||||
useEffect(() => {
|
||||
setSelected(value)
|
||||
}, [value])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
if (!isQueryReadyRef.current(query)) {
|
||||
setOptions([])
|
||||
setLoading(false)
|
||||
setFailed(false)
|
||||
return
|
||||
}
|
||||
|
||||
const currentRequestId = ++requestId.current
|
||||
const timeout = window.setTimeout(() => {
|
||||
setLoading(true)
|
||||
setFailed(false)
|
||||
void searchRef
|
||||
.current(query.trim())
|
||||
.then((nextOptions) => {
|
||||
if (requestId.current !== currentRequestId) return
|
||||
setOptions(nextOptions)
|
||||
})
|
||||
.catch(() => {
|
||||
if (requestId.current !== currentRequestId) return
|
||||
setFailed(true)
|
||||
})
|
||||
.finally(() => {
|
||||
if (requestId.current === currentRequestId) setLoading(false)
|
||||
})
|
||||
}, 250)
|
||||
|
||||
return () => window.clearTimeout(timeout)
|
||||
}, [open, query])
|
||||
|
||||
const choose = (option: AsyncSearchOption | null) => {
|
||||
setSelected(option)
|
||||
setOpen(false)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
'use client'
|
||||
|
||||
import { ChevronsUpDownIcon, XIcon } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { Badge } from '@/components/ui/Badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
|
@ -15,6 +15,7 @@ import {
|
|||
} from '@/components/ui/Command'
|
||||
import { Field, FieldDescription, FieldError, FieldLabel } from '@/components/ui/field'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import { useAsyncSearchOptions } from '@/hooks/useAsyncSearchOptions'
|
||||
import { isContactSearchQueryReady } from '@/lib/contactSearchQuery'
|
||||
import {
|
||||
MAX_ACTIVITY_RESPONSIBLES,
|
||||
|
|
@ -67,44 +68,12 @@ export const ResponsibleMultiSelect = ({
|
|||
const [selected, setSelected] = useState<ResponsibleOption[]>(value)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [options, setOptions] = useState<ResponsibleOption[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const requestId = useRef(0)
|
||||
const searchRef = useRef(search)
|
||||
|
||||
searchRef.current = search
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
if (!isContactSearchQueryReady(query)) {
|
||||
setOptions([])
|
||||
setLoading(false)
|
||||
setFailed(false)
|
||||
return
|
||||
}
|
||||
|
||||
const currentRequestId = ++requestId.current
|
||||
const timeout = window.setTimeout(() => {
|
||||
setLoading(true)
|
||||
setFailed(false)
|
||||
void searchRef
|
||||
.current(query.trim())
|
||||
.then((nextOptions) => {
|
||||
if (requestId.current !== currentRequestId) return
|
||||
setOptions(nextOptions)
|
||||
})
|
||||
.catch(() => {
|
||||
if (requestId.current !== currentRequestId) return
|
||||
setFailed(true)
|
||||
})
|
||||
.finally(() => {
|
||||
if (requestId.current === currentRequestId) setLoading(false)
|
||||
})
|
||||
}, 250)
|
||||
|
||||
return () => window.clearTimeout(timeout)
|
||||
}, [open, query])
|
||||
const { options, loading, failed } = useAsyncSearchOptions({
|
||||
open,
|
||||
query,
|
||||
search,
|
||||
isQueryReady: isContactSearchQueryReady,
|
||||
})
|
||||
|
||||
const selectedKey = (option: ResponsibleOption) => `${option.relationTo}:${option.id}`
|
||||
const selectedKeys = new Set(selected.map(selectedKey))
|
||||
|
|
|
|||
76
src/hooks/useAsyncSearchOptions.ts
Normal file
76
src/hooks/useAsyncSearchOptions.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
export const ASYNC_SEARCH_DEBOUNCE_MS = 250
|
||||
|
||||
type UseAsyncSearchOptionsResult<T> = {
|
||||
options: T[]
|
||||
loading: boolean
|
||||
failed: boolean
|
||||
}
|
||||
|
||||
type UseAsyncSearchOptionsArgs<T> = {
|
||||
open: boolean
|
||||
query: string
|
||||
search: (query: string) => Promise<T[]>
|
||||
isQueryReady?: (query: string) => boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* E1 — the shared async-search-with-debounce effect (requestId guard against
|
||||
* out-of-order responses, loading/failed states, per-consumer query gate).
|
||||
* The server action is injected as a prop by the consumer, keeping this module
|
||||
* client-safe; each consumer keeps its own filtering/grouping/pinned options.
|
||||
* Contract quirks, preserved from the three original copies: a not-ready query
|
||||
* resets options/loading/failed without invalidating an in-flight request
|
||||
* (a stale response still lands after the reset), and the search receives the
|
||||
* trimmed query.
|
||||
*/
|
||||
export function useAsyncSearchOptions<T extends { id: number }>({
|
||||
open,
|
||||
query,
|
||||
search,
|
||||
isQueryReady = () => true,
|
||||
}: UseAsyncSearchOptionsArgs<T>): UseAsyncSearchOptionsResult<T> {
|
||||
const [options, setOptions] = useState<T[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const requestId = useRef(0)
|
||||
const searchRef = useRef(search)
|
||||
const isQueryReadyRef = useRef(isQueryReady)
|
||||
|
||||
searchRef.current = search
|
||||
isQueryReadyRef.current = isQueryReady
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
if (!isQueryReadyRef.current(query)) {
|
||||
setOptions([])
|
||||
setLoading(false)
|
||||
setFailed(false)
|
||||
return
|
||||
}
|
||||
|
||||
const currentRequestId = ++requestId.current
|
||||
const timeout = window.setTimeout(() => {
|
||||
setLoading(true)
|
||||
setFailed(false)
|
||||
void searchRef
|
||||
.current(query.trim())
|
||||
.then((nextOptions) => {
|
||||
if (requestId.current !== currentRequestId) return
|
||||
setOptions(nextOptions)
|
||||
})
|
||||
.catch(() => {
|
||||
if (requestId.current !== currentRequestId) return
|
||||
setFailed(true)
|
||||
})
|
||||
.finally(() => {
|
||||
if (requestId.current === currentRequestId) setLoading(false)
|
||||
})
|
||||
}, ASYNC_SEARCH_DEBOUNCE_MS)
|
||||
|
||||
return () => window.clearTimeout(timeout)
|
||||
}, [open, query])
|
||||
|
||||
return { options, loading, failed }
|
||||
}
|
||||
|
|
@ -197,3 +197,47 @@ test.describe('Campaign home novidades capture', () => {
|
|||
// refusal precedent is a handled 4xx). The refusal path is pinned by the
|
||||
// int spec `submitCampaignNewsletter.int.spec.ts` (exact message + no rows).
|
||||
})
|
||||
|
||||
/**
|
||||
* S12 — the home owns its scroll container (body `overflow-hidden`), so the
|
||||
* native fragment navigation lands on the section only through
|
||||
* `CampaignHashScroll`. These tests pin the deep-link contract on mobile
|
||||
* (where the `h-dvh` reflow + eager hero images used to kick the page back to
|
||||
* the top) and the direct-load path on desktop (previously uncovered).
|
||||
*/
|
||||
test.describe('Campaign home novidades hash scroll', () => {
|
||||
const scrollSuffix = Date.now()
|
||||
|
||||
test.use({ viewport: { width: 390, height: 844 } })
|
||||
|
||||
test('direct #novidades deep link lands on the section (mobile)', async ({ page }) => {
|
||||
await page.goto(`/?e2e=scroll-${scrollSuffix}#novidades`)
|
||||
const section = page.locator('[data-home-section="newsletter"]')
|
||||
await expect(
|
||||
section.getByRole('heading', { name: 'Receba as novidades da campanha' }),
|
||||
).toBeVisible()
|
||||
await expect(section).toBeInViewport()
|
||||
})
|
||||
|
||||
test('hero CTA scrolls to the newsletter section (mobile)', async ({ page }) => {
|
||||
await page.goto(`/?e2e=scroll-${scrollSuffix}`)
|
||||
await page.locator('[data-cta="secondary"]').click()
|
||||
await expect(page).toHaveURL(/#novidades$/)
|
||||
await expect(page.locator('[data-home-section="newsletter"]')).toBeInViewport()
|
||||
})
|
||||
|
||||
test('deep link respects prefers-reduced-motion (mobile)', async ({ page }) => {
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' })
|
||||
await page.goto(`/?e2e=scroll-${scrollSuffix}#novidades`)
|
||||
await expect(page.locator('[data-home-section="newsletter"]')).toBeInViewport()
|
||||
})
|
||||
})
|
||||
|
||||
test.describe('Campaign home novidades hash scroll — desktop', () => {
|
||||
const desktopSuffix = Date.now()
|
||||
|
||||
test('direct #novidades deep link lands on the section (desktop)', async ({ page }) => {
|
||||
await page.goto(`/?e2e=scroll-${desktopSuffix}#novidades`)
|
||||
await expect(page.locator('[data-home-section="newsletter"]')).toBeInViewport()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -9,6 +9,10 @@ import type { CampaignUser } from '../../../src/payload-types.js'
|
|||
import config from '../../../src/payload.config.js'
|
||||
import { withPayloadTransaction } from '../../../src/utilities/payloadTransaction.js'
|
||||
import { assertTestDatabase } from '../../helpers/assertTestDatabase.js'
|
||||
import {
|
||||
claimMunicipalityIndex,
|
||||
releaseMunicipalityClaims,
|
||||
} from '../../helpers/campaignMunicipalityAllocator.js'
|
||||
import { purgeMunicipalityResidue } from '../../helpers/campaignResidue.js'
|
||||
import { withInviteConsent } from '../../helpers/testDatabaseLease.js'
|
||||
import { test as base, expect } from './e2eTest.js'
|
||||
|
|
@ -75,6 +79,7 @@ export class CampaignE2EOwnership {
|
|||
readonly payload: Payload
|
||||
readonly runID = randomUUID()
|
||||
private counter = 0
|
||||
private readonly claimedMunicipalityIndexes = new Set<number>()
|
||||
private readonly touchedMunicipalities = new Set<number>()
|
||||
private readonly owned = new Map<OwnedCollection, Set<number>>(
|
||||
deletionOrder.map((collection) => [collection, new Set<number>()]),
|
||||
|
|
@ -145,17 +150,12 @@ export class CampaignE2EOwnership {
|
|||
}
|
||||
|
||||
async claimMunicipality(): Promise<{ id: number; name: string; slug: string }> {
|
||||
await this.rootPayload.db.drizzle
|
||||
.execute(sql.raw(`CREATE SEQUENCE IF NOT EXISTS "campaign_fixture_municipality_alloc"`))
|
||||
.catch((error: unknown) => {
|
||||
if ((error as { code?: string }).code === '23505') return
|
||||
throw error
|
||||
})
|
||||
const result = await this.rootPayload.db.drizzle.execute(
|
||||
sql.raw(`SELECT nextval('"campaign_fixture_municipality_alloc"') AS "value"`),
|
||||
const index = await claimMunicipalityIndex(
|
||||
this.rootPayload,
|
||||
municipalityCatalog.length,
|
||||
this.runID,
|
||||
)
|
||||
const index =
|
||||
Number((result.rows[0] as { value: string | number }).value) % municipalityCatalog.length
|
||||
this.claimedMunicipalityIndexes.add(index)
|
||||
const slug = municipalityCatalog[index]!.slug
|
||||
const found = await this.rootPayload.find({
|
||||
collection: 'municipality',
|
||||
|
|
@ -423,6 +423,9 @@ export class CampaignE2EOwnership {
|
|||
}
|
||||
|
||||
async cleanup(): Promise<void> {
|
||||
if (this.claimedMunicipalityIndexes.size > 0) {
|
||||
await releaseMunicipalityClaims(this.rootPayload, this.runID)
|
||||
}
|
||||
await this.discoverOwnedRows()
|
||||
await withPayloadTransaction(this.rootPayload, async ({ req, transactionID }) => {
|
||||
const transaction = this.rootPayload.db.sessions?.[String(transactionID)]?.db as
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ import type {
|
|||
VotePledge,
|
||||
} from '@/payload-types'
|
||||
import { withPayloadTransaction } from '@/utilities/payloadTransaction'
|
||||
import { claimMunicipalityIndex, releaseMunicipalityClaims } from './campaignMunicipalityAllocator'
|
||||
import { purgeMunicipalityResidue, relationId, relationIds } from './campaignResidue'
|
||||
|
||||
/**
|
||||
|
|
@ -202,32 +203,11 @@ const combineErrors = (primary: unknown, cleanup: unknown): AggregateError =>
|
|||
|
||||
/**
|
||||
* Cross-process municipality allocator: seeded municipalities are shared reference rows, so
|
||||
* concurrently running spec files must never operate on the same municipality. A
|
||||
* Postgres sequence hands out globally unique catalog indexes.
|
||||
* concurrently running spec files must never operate on the same municipality. The allocator
|
||||
* (`campaignMunicipalityAllocator.ts`) hands out a catalog index per claim — unique across
|
||||
* live runs even after the Postgres sequence wraps (see its module docs for the wrap
|
||||
* mechanism). Claims are released by `cleanup()` so later runs reuse the slots.
|
||||
*/
|
||||
const MUNICIPALITY_ALLOCATION_SEQUENCE = 'campaign_fixture_municipality_alloc'
|
||||
let allocationSequenceReady: Promise<void> | undefined
|
||||
|
||||
const nextAllocatedMunicipalityIndex = async (
|
||||
payload: Payload,
|
||||
catalogSize: number,
|
||||
): Promise<number> => {
|
||||
allocationSequenceReady ??= payload.db.drizzle
|
||||
.execute(sql.raw(`CREATE SEQUENCE IF NOT EXISTS "${MUNICIPALITY_ALLOCATION_SEQUENCE}"`))
|
||||
.then(() => undefined)
|
||||
.catch((error: unknown) => {
|
||||
// IF NOT EXISTS still races across parallel workers (pg_class unique
|
||||
// violation, SQLSTATE 23505) — the sequence exists, which is all we need.
|
||||
if ((error as { code?: string }).code === '23505') return undefined
|
||||
throw error
|
||||
})
|
||||
await allocationSequenceReady
|
||||
const result = await payload.db.drizzle.execute(
|
||||
sql.raw(`SELECT nextval('"${MUNICIPALITY_ALLOCATION_SEQUENCE}"') AS "value"`),
|
||||
)
|
||||
const value = Number((result.rows[0] as { value: string | number }).value)
|
||||
return value % catalogSize
|
||||
}
|
||||
|
||||
export class CampaignFixtures {
|
||||
readonly payload: Payload
|
||||
|
|
@ -236,6 +216,7 @@ export class CampaignFixtures {
|
|||
private cleaned = false
|
||||
private counter = 0
|
||||
private municipalityCursor = 0
|
||||
private readonly claimedMunicipalityIndexes = new Set<number>()
|
||||
private readonly markers = new Set<string>()
|
||||
private readonly owned = emptyOwnedIDs()
|
||||
private readonly touchedMunicipalities = new Set<number>()
|
||||
|
|
@ -377,10 +358,12 @@ export class CampaignFixtures {
|
|||
async getMunicipality(slug?: string): Promise<Municipality> {
|
||||
let requestedSlug = slug
|
||||
if (!requestedSlug) {
|
||||
const index = await nextAllocatedMunicipalityIndex(
|
||||
const index = await claimMunicipalityIndex(
|
||||
this.rootPayload,
|
||||
municipalityCatalog.length,
|
||||
this.runID,
|
||||
)
|
||||
this.claimedMunicipalityIndexes.add(index)
|
||||
requestedSlug = municipalityCatalog[index]!.slug
|
||||
this.municipalityCursor += 1
|
||||
}
|
||||
|
|
@ -1033,6 +1016,9 @@ export class CampaignFixtures {
|
|||
|
||||
async cleanup(): Promise<void> {
|
||||
if (this.cleaned) return
|
||||
if (this.claimedMunicipalityIndexes.size > 0) {
|
||||
await releaseMunicipalityClaims(this.rootPayload, this.runID)
|
||||
}
|
||||
await this.discoverDependents()
|
||||
await withPayloadTransaction(this.rootPayload, async ({ req }) => {
|
||||
for (const collection of [
|
||||
|
|
|
|||
128
tests/helpers/campaignMunicipalityAllocator.ts
Normal file
128
tests/helpers/campaignMunicipalityAllocator.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import { sql } from '@payloadcms/db-postgres'
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
/**
|
||||
* Cross-process municipality allocator — shared by the int
|
||||
* (`campaignFixtures.ts`) and e2e (`campaignE2EFixtures.ts`) suites.
|
||||
*
|
||||
* Deliberately VITEST-FREE: the e2e fixture imports this module inside the
|
||||
* Playwright process, and a vitest import there crashes at load time (same
|
||||
* rule as `campaignResidue.ts` — OPS45).
|
||||
*
|
||||
* The Postgres sequence hands out globally unique catalog indexes across
|
||||
* parallel workers, but it is NEVER reset: worktree test databases are
|
||||
* persistent, and a full int + e2e cycle claims ~505 of the 435 catalog
|
||||
* slots, so the residue space wraps on every cycle. Once it wraps, two
|
||||
* concurrent runs can receive the SAME index — and the purge-on-claim
|
||||
* contract turns that collision into corruption (each run deletes the other
|
||||
* run's live rows). The claims registry below keeps the sequence as the
|
||||
* cursor but makes a claim exclusive per LIVE run:
|
||||
*
|
||||
* - claim: nextval → index → INSERT (index, run_id) ON CONFLICT DO NOTHING;
|
||||
* a conflict means a live run holds the slot, so skip to the next value;
|
||||
* - stale steal: a claim older than STALE_CLAIM_WINDOW belongs to a
|
||||
* CRASHED run (its cleanup never ran), so it is deleted and the slot is
|
||||
* reclaimed — without this, one aborted run would block slots for hours;
|
||||
* - release: the fixture deletes its own rows at cleanup, so the slots
|
||||
* become claimable again for later runs;
|
||||
* - exhaustion: all slots held by fresh claims → clear error instead of a
|
||||
* silent collision.
|
||||
*/
|
||||
const ALLOCATION_SEQUENCE = 'campaign_fixture_municipality_alloc'
|
||||
const ALLOCATION_CLAIMS = 'campaign_fixture_municipality_claims'
|
||||
const STALE_CLAIM_WINDOW = "interval '2 hours'"
|
||||
|
||||
// Identifiers in the `sql` templates below are INLINE LITERALS on purpose:
|
||||
// `${}` in a drizzle template is a bound parameter, never an identifier.
|
||||
const claimsTable = `"${ALLOCATION_CLAIMS}"`
|
||||
|
||||
let allocatorReady: Promise<void> | undefined
|
||||
|
||||
const ensureAllocatorSchema = (payload: Payload): Promise<void> => {
|
||||
allocatorReady ??= Promise.all([
|
||||
payload.db.drizzle.execute(sql.raw(`CREATE SEQUENCE IF NOT EXISTS "${ALLOCATION_SEQUENCE}"`)),
|
||||
payload.db.drizzle.execute(
|
||||
sql.raw(`
|
||||
CREATE TABLE IF NOT EXISTS ${claimsTable} (
|
||||
"index" integer PRIMARY KEY,
|
||||
"run_id" text NOT NULL,
|
||||
"claimed_at" timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
`),
|
||||
),
|
||||
])
|
||||
.then(() => undefined)
|
||||
.catch((error: unknown) => {
|
||||
// IF NOT EXISTS still races across parallel workers (pg_class unique
|
||||
// violation, SQLSTATE 23505) — the objects exist, which is all we need.
|
||||
if ((error as { code?: string }).code === '23505') return undefined
|
||||
throw error
|
||||
})
|
||||
return allocatorReady
|
||||
}
|
||||
|
||||
const nextAllocationValue = async (payload: Payload): Promise<number> => {
|
||||
const result = await payload.db.drizzle.execute(
|
||||
sql.raw(`SELECT nextval('"${ALLOCATION_SEQUENCE}"') AS "value"`),
|
||||
)
|
||||
return Number((result.rows[0] as { value: string | number }).value)
|
||||
}
|
||||
|
||||
const tryClaimIndex = async (payload: Payload, index: number, runID: string): Promise<boolean> => {
|
||||
const result = await payload.db.drizzle.execute(sql`
|
||||
INSERT INTO ${sql.raw(claimsTable)} ("index", "run_id")
|
||||
VALUES (${index}, ${runID})
|
||||
ON CONFLICT ("index") DO NOTHING
|
||||
RETURNING "index"
|
||||
`)
|
||||
return result.rows.length > 0
|
||||
}
|
||||
|
||||
const tryStealStaleClaim = async (payload: Payload, index: number): Promise<boolean> => {
|
||||
const result = await payload.db.drizzle.execute(sql`
|
||||
DELETE FROM ${sql.raw(claimsTable)}
|
||||
WHERE "index" = ${index} AND "claimed_at" < now() - ${sql.raw(STALE_CLAIM_WINDOW)}
|
||||
RETURNING "index"
|
||||
`)
|
||||
return result.rows.length > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* A catalog index that no LIVE run holds. Never returns an index that a
|
||||
* concurrently running fixture still owns, even after the sequence wraps —
|
||||
* the claim only lands when the INSERT wins. One run may hold at most
|
||||
* `catalogSize` slots at once (its own claims are live); claiming past that
|
||||
* with the same runID exhausts, which is correct — real fixtures release at
|
||||
* each test's cleanup.
|
||||
*/
|
||||
export const claimMunicipalityIndex = async (
|
||||
payload: Payload,
|
||||
catalogSize: number,
|
||||
runID: string,
|
||||
): Promise<number> => {
|
||||
await ensureAllocatorSchema(payload)
|
||||
for (let attempt = 0; attempt < catalogSize; attempt += 1) {
|
||||
const index = (await nextAllocationValue(payload)) % catalogSize
|
||||
if (await tryClaimIndex(payload, index, runID)) return index
|
||||
if (await tryStealStaleClaim(payload, index)) {
|
||||
if (await tryClaimIndex(payload, index, runID)) return index
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`Municipality allocator exhausted: all ${catalogSize} catalog slots are held by ` +
|
||||
`live test runs. Stale claims from crashed runs expire after 2 hours.`,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees every slot a run claimed (runID is per fixture instance — one test).
|
||||
* Called from the fixture cleanup; the claim is held from claim until the
|
||||
* test's rows are purged, so releasing here cannot collide with the live
|
||||
* owner (there is none by definition).
|
||||
*/
|
||||
export const releaseMunicipalityClaims = async (payload: Payload, runID: string): Promise<void> => {
|
||||
await payload.db.drizzle.execute(sql`
|
||||
DELETE FROM ${sql.raw(claimsTable)}
|
||||
WHERE "run_id" = ${runID}
|
||||
`)
|
||||
}
|
||||
9
tests/helpers/e2eEsmLoader.mjs
Normal file
9
tests/helpers/e2eEsmLoader.mjs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
/**
|
||||
* OPS46 — entry point that registers the Playwright ESM resolution hook
|
||||
* (see `e2eEsmResolve.mjs`). Passed to worker processes as
|
||||
* `NODE_OPTIONS=--import=<absolute path>` so bare `playwright test` runs
|
||||
* resolve `next/cache` and `server-only` exactly like `pnpm test:e2e` does.
|
||||
*/
|
||||
import { register } from 'node:module'
|
||||
|
||||
register(new URL('./e2eEsmResolve.mjs', import.meta.url))
|
||||
29
tests/helpers/e2eEsmResolve.mjs
Normal file
29
tests/helpers/e2eEsmResolve.mjs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
/**
|
||||
* OPS46 — ESM resolution hook for the Playwright runner process.
|
||||
*
|
||||
* next@15 ships NO `exports` map in its package.json, so native Node ESM
|
||||
* cannot resolve the bare `next/cache` subpath (the file exists as
|
||||
* `cache.js`, but ESM never tries extensions); `server-only` needs the
|
||||
* `react-server` export condition. `pnpm test:e2e` papers over both with
|
||||
* NODE_OPTIONS flags (`--conditions=react-server --import=tsx/esm`), but a
|
||||
* bare `playwright test` (VS Code extension, `--list`, ad-hoc runs) has
|
||||
* neither. This hook applies the same two resolutions in-process:
|
||||
* - `next/cache` → `next/cache.js` (the shipped, TS-mapped entry)
|
||||
* - inject `react-server` into the resolution conditions (same effect as
|
||||
* the `--conditions=react-server` flag)
|
||||
*
|
||||
* Registered in the main process by `playwright.config.ts` and passed to the
|
||||
* worker processes via `NODE_OPTIONS=--import=...` (see `e2eEsmLoader.mjs`).
|
||||
*/
|
||||
export async function resolve(specifier, context, nextResolve) {
|
||||
if (specifier === 'next/cache') {
|
||||
return nextResolve('next/cache.js', context)
|
||||
}
|
||||
if (!context.conditions.includes('react-server')) {
|
||||
return nextResolve(specifier, {
|
||||
...context,
|
||||
conditions: ['react-server', ...context.conditions],
|
||||
})
|
||||
}
|
||||
return nextResolve(specifier, context)
|
||||
}
|
||||
154
tests/int/campaignMunicipalityAllocator.int.spec.ts
Normal file
154
tests/int/campaignMunicipalityAllocator.int.spec.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
|
||||
import { sql } from '@payloadcms/db-postgres'
|
||||
import { getPayload, type Payload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
import config from '@/payload.config'
|
||||
import {
|
||||
claimMunicipalityIndex,
|
||||
releaseMunicipalityClaims,
|
||||
} from '../helpers/campaignMunicipalityAllocator'
|
||||
|
||||
/**
|
||||
* Behavioral stress of the allocator's claims registry (OPS46). The real
|
||||
* catalog has 435 slots and a full int + e2e cycle claims ~505 of them, so
|
||||
* the sequence wraps every cycle on persistent worktree databases; these
|
||||
* tests exercise the wrap with a small synthetic `catalogSize` so the
|
||||
* properties are observable in one run. They run under the PARALLEL int
|
||||
* suite, so assertions never depend on the exact index a claim lands on —
|
||||
* only on the registry invariants (live exclusivity through the wrap,
|
||||
* exhaustion, release, stale steal) that hold regardless of what other
|
||||
* specs claim concurrently.
|
||||
*/
|
||||
|
||||
let payload: Payload
|
||||
const releasedRunIDs: string[] = []
|
||||
|
||||
const freshRunID = (): string => {
|
||||
const runID = randomUUID()
|
||||
releasedRunIDs.push(runID)
|
||||
return runID
|
||||
}
|
||||
|
||||
const claimCount = async (runID: string): Promise<number> => {
|
||||
const result = await payload.db.drizzle.execute(sql`
|
||||
SELECT count(*)::int AS "count"
|
||||
FROM "campaign_fixture_municipality_claims"
|
||||
WHERE "run_id" = ${runID}
|
||||
`)
|
||||
return Number((result.rows[0] as { count: number }).count)
|
||||
}
|
||||
|
||||
describe('campaign municipality allocator registry', () => {
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config: await config })
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await Promise.all(releasedRunIDs.map((runID) => releaseMunicipalityClaims(payload, runID)))
|
||||
})
|
||||
|
||||
it('never hands a live run an index another live run holds, across many sequence wraps', async () => {
|
||||
const catalogSize = 40
|
||||
// The anchor run keeps ONE slot held for the whole test; the residue
|
||||
// space (40 slots) wraps ~3 times over the 120 claims below, and the
|
||||
// registry must skip the held slot every time the cursor lands on it.
|
||||
const anchor = freshRunID()
|
||||
const anchorIndex = await claimMunicipalityIndex(payload, catalogSize, anchor)
|
||||
|
||||
for (let cycle = 0; cycle < 60; cycle += 1) {
|
||||
const runID = freshRunID()
|
||||
const first = await claimMunicipalityIndex(payload, catalogSize, runID)
|
||||
const second = await claimMunicipalityIndex(payload, catalogSize, runID)
|
||||
expect(second).not.toBe(first)
|
||||
expect([first, second]).not.toContain(anchorIndex)
|
||||
await releaseMunicipalityClaims(payload, runID)
|
||||
}
|
||||
expect(await claimCount(anchor)).toBe(1)
|
||||
})
|
||||
|
||||
it('fails loudly with an exhaustion error instead of colliding, then recovers on release', async () => {
|
||||
const catalogSize = 8
|
||||
const holder = freshRunID()
|
||||
|
||||
let exhausted = false
|
||||
for (let attempt = 0; attempt < 100 && !exhausted; attempt += 1) {
|
||||
try {
|
||||
await claimMunicipalityIndex(payload, catalogSize, holder)
|
||||
} catch (error) {
|
||||
expect((error as Error).message).toMatch(/exhausted/i)
|
||||
exhausted = true
|
||||
}
|
||||
}
|
||||
expect(exhausted, 'all slots held must surface as an exhaustion error').toBe(true)
|
||||
|
||||
await releaseMunicipalityClaims(payload, holder)
|
||||
expect(await claimCount(holder)).toBe(0)
|
||||
|
||||
const recovered = freshRunID()
|
||||
let claimed = false
|
||||
for (let attempt = 0; attempt < 20 && !claimed; attempt += 1) {
|
||||
try {
|
||||
await claimMunicipalityIndex(payload, catalogSize, recovered)
|
||||
claimed = true
|
||||
} catch (error) {
|
||||
expect((error as Error).message).toMatch(/exhausted/i)
|
||||
}
|
||||
}
|
||||
expect(claimed, 'released slots must be claimable again').toBe(true)
|
||||
})
|
||||
|
||||
it('steals claims of a crashed run once they age past the stale window', async () => {
|
||||
const catalogSize = 40
|
||||
const crashed = freshRunID()
|
||||
const survivor = freshRunID()
|
||||
|
||||
const crashedIndex = await claimMunicipalityIndex(payload, catalogSize, crashed)
|
||||
// Simulate a run killed before cleanup: age its claim past the 2h window.
|
||||
await payload.db.drizzle.execute(sql`
|
||||
UPDATE "campaign_fixture_municipality_claims"
|
||||
SET "claimed_at" = now() - interval '3 hours'
|
||||
WHERE "run_id" = ${crashed}
|
||||
`)
|
||||
|
||||
// The stale slot is reclaimable: keep claiming until the survivor lands
|
||||
// on the crashed run's index (the sequence advances one slot per claim,
|
||||
// so a bounded loop covers every slot of the residue space).
|
||||
let reclaimed = false
|
||||
for (let attempt = 0; attempt < catalogSize * 3 && !reclaimed; attempt += 1) {
|
||||
if ((await claimMunicipalityIndex(payload, catalogSize, survivor)) === crashedIndex) {
|
||||
reclaimed = true
|
||||
}
|
||||
}
|
||||
expect(reclaimed, 'stale claim must be stealable').toBe(true)
|
||||
expect(await claimCount(crashed)).toBe(0)
|
||||
// The survivor may hold up to catalogSize slots at this point; release
|
||||
// inline so the later tests keep free space (the afterAll is the net).
|
||||
await releaseMunicipalityClaims(payload, survivor)
|
||||
})
|
||||
|
||||
it('releases every slot of a run on release and lets later runs reuse the space', async () => {
|
||||
const catalogSize = 40
|
||||
const runA = freshRunID()
|
||||
const runB = freshRunID()
|
||||
|
||||
const claimedA = new Set<number>()
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
claimedA.add(await claimMunicipalityIndex(payload, catalogSize, runA))
|
||||
}
|
||||
expect(claimedA.size).toBe(5)
|
||||
expect(await claimCount(runA)).toBe(5)
|
||||
|
||||
await releaseMunicipalityClaims(payload, runA)
|
||||
expect(await claimCount(runA)).toBe(0)
|
||||
|
||||
const claimedB = new Set<number>()
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
claimedB.add(await claimMunicipalityIndex(payload, catalogSize, runB))
|
||||
}
|
||||
expect(claimedB.size).toBe(5)
|
||||
})
|
||||
})
|
||||
|
|
@ -95,4 +95,31 @@ describe('municipality allocator discipline (miss #73)', () => {
|
|||
'anchor with ^ (or locate by href) — catalog names are not prefix-unique',
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('routes every claim through the shared allocator module (OPS46)', () => {
|
||||
// The claims registry (campaignMunicipalityAllocator.ts) is what makes the
|
||||
// purge-on-claim contract safe after the sequence wraps; a direct
|
||||
// nextval/sequence reference anywhere else reintroduces the collision it
|
||||
// exists to prevent.
|
||||
const offenders: string[] = []
|
||||
const allocatorModule = repoPath(
|
||||
resolve(repoRoot, 'tests/helpers/campaignMunicipalityAllocator.ts'),
|
||||
)
|
||||
const scanned = [
|
||||
...specFiles,
|
||||
...walkFiles(resolve(repoRoot, 'tests/helpers'), ['.ts']),
|
||||
].filter((file) => repoPath(file) !== allocatorModule)
|
||||
|
||||
for (const file of scanned) {
|
||||
const source = readFileSync(file, 'utf8')
|
||||
if (/nextval\(|campaign_fixture_municipality_alloc/.test(source)) {
|
||||
offenders.push(repoPath(file))
|
||||
}
|
||||
}
|
||||
|
||||
expect(
|
||||
offenders,
|
||||
'claim through claimMunicipalityIndex — direct sequence access bypasses the claims registry',
|
||||
).toEqual([])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
175
tests/unit/useAsyncSearchOptions.unit.spec.ts
Normal file
175
tests/unit/useAsyncSearchOptions.unit.spec.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
import { act, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { ASYNC_SEARCH_DEBOUNCE_MS, useAsyncSearchOptions } from '@/hooks/useAsyncSearchOptions'
|
||||
|
||||
type TestOption = { id: number; label: string }
|
||||
|
||||
const renderOptions = (
|
||||
props: {
|
||||
open?: boolean
|
||||
query?: string
|
||||
isQueryReady?: (query: string) => boolean
|
||||
} = {},
|
||||
) => {
|
||||
const search = vi.fn(
|
||||
async (query: string): Promise<TestOption[]> => [{ id: 1, label: `hit:${query}` }],
|
||||
)
|
||||
const view = renderHook(
|
||||
(current: { open: boolean; query: string; isQueryReady?: (query: string) => boolean }) =>
|
||||
useAsyncSearchOptions<TestOption>({
|
||||
open: current.open,
|
||||
query: current.query,
|
||||
search,
|
||||
...(current.isQueryReady ? { isQueryReady: current.isQueryReady } : {}),
|
||||
}),
|
||||
{
|
||||
initialProps: {
|
||||
open: props.open ?? true,
|
||||
query: props.query ?? '',
|
||||
...(props.isQueryReady ? { isQueryReady: props.isQueryReady } : {}),
|
||||
},
|
||||
},
|
||||
)
|
||||
return { search, view }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('useAsyncSearchOptions', () => {
|
||||
it('waits out the debounce, then searches with the trimmed query', async () => {
|
||||
const { search, view } = renderOptions({ query: ' ca ' })
|
||||
|
||||
expect(search).not.toHaveBeenCalled()
|
||||
expect(view.result.current.loading).toBe(false)
|
||||
|
||||
await act(async () => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
|
||||
expect(search).toHaveBeenCalledTimes(1)
|
||||
expect(search).toHaveBeenCalledWith('ca')
|
||||
expect(view.result.current.options).toEqual([{ id: 1, label: 'hit:ca' }])
|
||||
expect(view.result.current.loading).toBe(false)
|
||||
expect(view.result.current.failed).toBe(false)
|
||||
})
|
||||
|
||||
it('does not search while the dialog stays closed', async () => {
|
||||
const { search, view } = renderOptions({ open: false, query: 'cairu' })
|
||||
|
||||
await act(async () => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
|
||||
expect(search).not.toHaveBeenCalled()
|
||||
expect(view.result.current.options).toEqual([])
|
||||
expect(view.result.current.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('coalesces rapid query changes into a single search for the last query', async () => {
|
||||
const { search, view } = renderOptions({ query: 'a' })
|
||||
|
||||
act(() => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS - 1))
|
||||
view.rerender({ open: true, query: 'ab' })
|
||||
await act(async () => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
|
||||
expect(search).toHaveBeenCalledTimes(1)
|
||||
expect(search).toHaveBeenCalledWith('ab')
|
||||
})
|
||||
|
||||
it('resets state without searching when the query is not ready', async () => {
|
||||
const { search, view } = renderOptions({ isQueryReady: (query) => query.length >= 2 })
|
||||
|
||||
await act(async () => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
|
||||
expect(search).not.toHaveBeenCalled()
|
||||
expect(view.result.current.options).toEqual([])
|
||||
expect(view.result.current.loading).toBe(false)
|
||||
expect(view.result.current.failed).toBe(false)
|
||||
|
||||
view.rerender({ open: true, query: 'ca', isQueryReady: (query) => query.length >= 2 })
|
||||
await act(async () => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
|
||||
expect(search).toHaveBeenCalledTimes(1)
|
||||
expect(search).toHaveBeenCalledWith('ca')
|
||||
})
|
||||
|
||||
it('sets failed on a rejected search and clears loading', async () => {
|
||||
const { search, view } = renderOptions({ query: 'ca' })
|
||||
search.mockRejectedValueOnce(new Error('boom'))
|
||||
|
||||
await act(async () => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
|
||||
expect(view.result.current.failed).toBe(true)
|
||||
expect(view.result.current.loading).toBe(false)
|
||||
expect(view.result.current.options).toEqual([])
|
||||
})
|
||||
|
||||
it('recovers from a failed search on the next successful one', async () => {
|
||||
const { search, view } = renderOptions({ query: 'ca' })
|
||||
search.mockRejectedValueOnce(new Error('boom'))
|
||||
|
||||
await act(async () => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
expect(view.result.current.failed).toBe(true)
|
||||
|
||||
view.rerender({ open: true, query: 'cairu' })
|
||||
await act(async () => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
|
||||
expect(view.result.current.failed).toBe(false)
|
||||
expect(view.result.current.options).toEqual([{ id: 1, label: 'hit:cairu' }])
|
||||
expect(view.result.current.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps loading while the request is in flight', async () => {
|
||||
const { search, view } = renderOptions({ query: 'ca' })
|
||||
search.mockImplementationOnce(() => new Promise<TestOption[]>(() => {}))
|
||||
|
||||
act(() => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
|
||||
expect(view.result.current.loading).toBe(true)
|
||||
expect(view.result.current.failed).toBe(false)
|
||||
})
|
||||
|
||||
it('lets a stale in-flight response land after the query turns not-ready (preserved quirk)', async () => {
|
||||
const { search, view } = renderOptions({ query: 'ca', isQueryReady: (q) => q.length >= 2 })
|
||||
|
||||
let resolveFirst: (options: TestOption[]) => void = () => {}
|
||||
search.mockImplementationOnce(
|
||||
() => new Promise<TestOption[]>((resolve) => (resolveFirst = resolve)),
|
||||
)
|
||||
|
||||
act(() => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
expect(view.result.current.loading).toBe(true)
|
||||
|
||||
view.rerender({ open: true, query: '', isQueryReady: (q) => q.length >= 2 })
|
||||
expect(view.result.current.options).toEqual([])
|
||||
expect(view.result.current.loading).toBe(false)
|
||||
|
||||
await act(async () => resolveFirst([{ id: 1, label: 'stale' }]))
|
||||
|
||||
expect(view.result.current.options).toEqual([{ id: 1, label: 'stale' }])
|
||||
expect(view.result.current.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('discards an out-of-order response from a superseded request', async () => {
|
||||
const { search, view } = renderOptions({ query: 'ca' })
|
||||
|
||||
let resolveFirst: (options: TestOption[]) => void = () => {}
|
||||
search.mockImplementationOnce(
|
||||
() => new Promise<TestOption[]>((resolve) => (resolveFirst = resolve)),
|
||||
)
|
||||
search.mockResolvedValueOnce([{ id: 2, label: 'hit:campanha' }])
|
||||
|
||||
act(() => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
view.rerender({ open: true, query: 'campanha' })
|
||||
await act(async () => void vi.advanceTimersByTime(ASYNC_SEARCH_DEBOUNCE_MS))
|
||||
expect(search).toHaveBeenCalledTimes(2)
|
||||
|
||||
await act(async () => resolveFirst([{ id: 1, label: 'stale' }]))
|
||||
|
||||
expect(view.result.current.options).toEqual([{ id: 2, label: 'hit:campanha' }])
|
||||
expect(view.result.current.loading).toBe(false)
|
||||
})
|
||||
})
|
||||
Loading…
Reference in a new issue