teqo-backup/src/components/campaign/shared/CampaignCellEditOverlay.tsx
Francisco Solla b210939226 refactor(B193): simplify fixes pós-revisão — mapper único de updates, API de trigger uniforme, grupos de relação extraídos, hardening do sheet host
- Extrai toMunicipalityUpdateViewModel/loadUpdateAuthorNames compartilhados
  (feed + batch da lista); remove avatarClassName morto.
- MunicipalityRelationTriggerProps compartilhado nos 3 wrappers; triggerClassName
  no ExpectedVotesControl; ChipLabel/RelationGroup/CityDash no card.
- Sheet host: cleanup de unmount no overlay (sem drawer órfão), registerFooter
  valida open, branch nulo do handleOpenChange limpa footer; chrome freeze
  documentado.
- A11y/UX: ícone de alerta no rodapé frio (WCAG 1.4.1), iniciais de avatar
  aria-hidden, chip sem_base sem target morto, label da cidade com Tendência,
  aria-label da barra anuncia os 3 cenários, card layout 'colocação · votos'.
- E2E: settleStream no B184 (flake da cópia transitória do streaming), cards
  ancorados por hasText (q= casa prefixos), cor da borda via classe do token.
2026-08-10 11:23:49 -03:00

317 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use client'
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import { CampaignHoverTooltip } from '@/components/campaign/shared/CampaignHoverTooltip'
import { useCampaignListSheet } from '@/components/campaign/shared/CampaignListSheetHost'
import {
Drawer,
DrawerCloseButton,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from '@/components/ui/Drawer'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/Popover'
import { cn } from '@/lib/utils'
export type CampaignCellEditOverlayVariant = 'popover' | 'sheet'
/** `relative` is load-bearing: see the comment where it is composed below. */
const campaignCellEditTriggerClassName =
'relative min-h-11 rounded-md px-1 hover:bg-muted/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'
type CampaignCellEditOverlayProps = {
variant: CampaignCellEditOverlayVariant
open: boolean
onOpenChange: (open: boolean) => void
/** Dialog title: the Drawer's heading, and the Popover's accessible name. */
title: string
trigger: ReactNode
triggerLabel: string
triggerClassName?: string
triggerBusy?: boolean
/**
* Announced by the region this shell keeps OUTSIDE the overlay. Closing is
* what commits a draft, and a region rendered inside the Popover/Drawer
* unmounts with it — so the one announcement that matters most ("Salvando…",
* and the failure that follows) was the one that never reached a screen
* reader (B32+ F4).
*/
statusMessage?: string
children: ReactNode
// Popover only ─────────────────────────────────────────────────────────────
/** B23's read-without-opening tooltip: there is no hover on touch. */
tooltipContent?: ReactNode
align?: 'start' | 'center' | 'end'
contentClassName?: string
/**
* Leaves focus on the trigger so the control's own fields decide what to
* focus. The Drawer never needs it — it always opens with focus on its title,
* never on a field (see `initialFocus` below).
*/
preventPopoverAutoFocus?: boolean
// Sheet only ───────────────────────────────────────────────────────────────
/** Subject line under the title: which row is being edited. */
description?: string
sheetBodyClassName?: string
/**
* Replaces the default "Fechar" for a sheet whose primary action is an
* explicit submit (E14's "Registrar movimento"): in a scrolling body the
* button drifts below the fold, and the footer is where a thumb expects it.
* A submit that belongs to a `<form>` in `children` is associated by the
* standard `form` attribute — the caller owns both ids, so the shell does not
* need to know there is a form at all.
*/
footer?: ReactNode
}
/**
* Container for the list's in-cell quick-edit surfaces: a Popover on `md+`, a
* bottom Drawer below it, where a Popover competes with the virtual keyboard
* (B42; `MunicipalityListUpdateControl` set the precedent in B26).
*
* The variant comes from the call site, not from `matchMedia`: the lists render
* the mobile cards (`md:hidden`) and the table (`hidden md:block`) as sibling
* trees, so each already knows which viewport it belongs to — and a media query
* here would flip the container after hydration.
*
* Only the container lives here. Each control keeps its own auto-save scaffold
* (debounce, abort, flush on close), which is what `onOpenChange` carries — so
* closing the Drawer commits exactly like dismissing the Popover does.
*
* When a `CampaignListSheetProvider` wraps the list (B42 mobile cards), sheet
* cells publish into that single Drawer instead of mounting one per row — prod
* was tripping React #130 with ~125 idle drawer roots on a 25-row page.
*/
export const CampaignCellEditOverlay = ({
variant,
open,
onOpenChange,
title,
description,
trigger,
triggerLabel,
triggerClassName,
triggerBusy,
statusMessage,
tooltipContent,
align = 'start',
contentClassName,
sheetBodyClassName,
footer,
preventPopoverAutoFocus,
children,
}: CampaignCellEditOverlayProps) => {
const sharedSheet = useCampaignListSheet()
const wasOpenRef = useRef(open)
/** C109 — the shared drawer session this control opened (see the host). */
const sessionIdRef = useRef<number | null>(null)
// Latest values for the mount-only cleanup below (never stale, no deps).
const sharedSheetRef = useRef(sharedSheet)
sharedSheetRef.current = sharedSheet
const onOpenChangeRef = useRef(onOpenChange)
onOpenChangeRef.current = onOpenChange
// The control may unmount with its session open (a filter collapse behind
// the modal): dismiss the host so no orphan drawer keeps a frozen chrome
// and a dead body. The host's session guard makes the call a no-op when
// another control already took over.
useEffect(
() => () => {
const sheet = sharedSheetRef.current
const sessionId = sessionIdRef.current
if (sessionId !== null && sheet) {
sheet.dismissSheet(sessionId, onOpenChangeRef.current)
}
},
[],
)
// Miss #52: without the provider every opened cell keeps its own Drawer
// root. The fallback below stays for prod resilience, but in dev the
// missing provider is called out the moment a sheet cell mounts.
useEffect(() => {
if (variant !== 'sheet' || sharedSheet) return
if (process.env.NODE_ENV !== 'development') return
console.error(
'CampaignCellEditOverlay: variant="sheet" sem CampaignListSheetProvider — ' +
'cada célula aberta mantém um Drawer próprio (miss #52). Envolva a lista no provider.',
)
}, [variant, sharedSheet])
/**
* The region is mounted from the first open onwards and never unmounted
* again — a live region has to exist BEFORE its text changes or most screen
* readers skip the first message, and it has to outlive the close, which is
* what commits. Mounting it unconditionally instead would leave ~250 polite
* regions registered on a 25-row município page (5 controls × 2 sibling
* trees), which is a load on assistive tech that nothing here needs.
*/
const [everOpened, setEverOpened] = useState(open)
if (open && !everOpened) setEverOpened(true)
const titleRef = useRef<HTMLHeadingElement | null>(null)
const triggerButton = (
<button
type="button"
aria-expanded={open}
aria-haspopup="dialog"
aria-busy={triggerBusy || undefined}
// `relative` (in the shared class) is load-bearing on the mobile card,
// where the município's own link stretches an `after:inset-0` overlay
// across the whole card: it is what paints this trigger above that overlay
// and keeps its tap. It belongs on the control and not on the cell around
// it — a positioned cell would lift its label and padding too, turning
// them into taps that neither edit nor navigate.
className={cn(
campaignCellEditTriggerClassName,
open ? 'bg-muted/60' : undefined,
triggerClassName,
)}
aria-label={triggerLabel}
// The Popover's own trigger owns the click; the Drawer has none to borrow.
onClick={variant === 'sheet' ? () => onOpenChange(true) : undefined}
>
{trigger}
</button>
)
// One region per control, next to its trigger — never a single global one:
// two cells saving at once would then overwrite each other's announcement,
// and neither would say which row it came from.
// `role="status"` and not a bare `aria-live`: its implicit `aria-atomic`
// makes the sentence be announced whole, which is what these messages are —
// `MunicipalityPortfolioCell` had already settled on it.
const liveRegion =
statusMessage === undefined || !everOpened ? null : (
<p className="sr-only" role="status" aria-live="polite">
{statusMessage}
</p>
)
useLayoutEffect(() => {
if (variant !== 'sheet' || !sharedSheet) return
const wasOpen = wasOpenRef.current
wasOpenRef.current = open
if (!open) {
if (wasOpen && sessionIdRef.current !== null) {
sharedSheet.dismissSheet(sessionIdRef.current, onOpenChange)
sessionIdRef.current = null
}
return
}
// Only the false→true transition opens a session: the controls' callbacks
// are recreated per render (autosave `onOpenChange`, level `handleOpenChange`),
// and calling `openSheet` on every re-render made the host dismiss the
// session it just started (C109 — "sheet quebra ao abrir"). Consequence:
// `title`/`description`/`hasCustomFooter` are frozen while the drawer is
// open — every caller passes static chrome, and the live parts (footer
// buttons/spinner) flow through `setFooterContent` below.
if (!wasOpen) {
sessionIdRef.current = sharedSheet.openSheet({
title,
description,
hasCustomFooter: Boolean(footer),
sheetBodyClassName,
onOpenChange,
})
}
}, [variant, sharedSheet, open, title, description, footer, sheetBodyClassName, onOpenChange])
// C109 — the custom footer is REGISTERED here and rendered by the host
// INSIDE the Drawer's React tree; a portal would keep the Dialog context
// away from its `DialogClose`. Re-registers on every change (spinner,
// label) while the session stays active; a stale session's call is a no-op
// in the host.
useLayoutEffect(() => {
if (variant !== 'sheet' || !sharedSheet) return
const sessionId = sessionIdRef.current
if (sessionId === null) return
sharedSheet.setFooterContent(sessionId, open ? (footer ?? null) : null)
}, [variant, sharedSheet, open, footer])
if (variant === 'sheet' && sharedSheet) {
const showPortals =
open && sessionIdRef.current !== null && sharedSheet.isActiveSheet(sessionIdRef.current)
const bodyTarget = showPortals ? sharedSheet.bodyPortalRef.current : null
// portalRevision keeps this render in sync after the drawer mounts its targets.
void sharedSheet.portalRevision
return (
<>
{triggerButton}
{liveRegion}
{showPortals && bodyTarget ? createPortal(children, bodyTarget) : null}
</>
)
}
if (variant === 'sheet') {
return (
<>
{triggerButton}
{liveRegion}
{open || everOpened ? (
<Drawer open={open} onOpenChange={onOpenChange}>
{open ? (
<DrawerContent initialFocus={titleRef}>
<DrawerHeader>
<DrawerTitle ref={titleRef} tabIndex={-1} className="outline-none">
{title}
</DrawerTitle>
{description ? <DrawerDescription>{description}</DrawerDescription> : null}
</DrawerHeader>
<div
className={cn(
'flex min-h-0 flex-1 flex-col overflow-y-auto px-4 pt-3 pb-2',
sheetBodyClassName,
)}
>
{children}
</div>
<DrawerFooter>
{footer ?? <DrawerCloseButton>Fechar</DrawerCloseButton>}
</DrawerFooter>
</DrawerContent>
) : null}
</Drawer>
) : null}
</>
)
}
return (
<>
<Popover open={open} onOpenChange={onOpenChange}>
<CampaignHoverTooltip
content={tooltipContent}
align={align}
openOnTouch={false}
disabled={open}
>
<PopoverTrigger asChild>{triggerButton}</PopoverTrigger>
</CampaignHoverTooltip>
<PopoverContent
align={align}
sideOffset={8}
className={contentClassName}
// Radix gives the popover `role="dialog"` and no name; the Drawer's
// title is the same sentence, so it serves as one here too.
aria-label={title}
onOpenAutoFocus={preventPopoverAutoFocus ? (event) => event.preventDefault() : undefined}
>
{children}
</PopoverContent>
</Popover>
{liveRegion}
</>
)
}