Files
AgendaPro/src/lib/installPrompt.ts
T
AgendaPro DevandClaude Opus 5 4281567207 fix: two defects that only reproduce over a real network
Neither is visible against localhost, which is why both shipped.

**Install button never appeared on `/login`** — a regression from making the login a
lazy route. `beforeinstallprompt` fires once per page load and is never replayed;
`useInstallPrompt` attached its listener from a `useEffect`, i.e. at mount, and
`InstallAppPrompt` now mounts only after an extra round-trip for its chunk. Locally
that round-trip is a millisecond so the listener still won a race it should never
have been in. Over a real connection the event was long gone, so a user on a slow
link lost the install button entirely.

The listener now lives in `src/lib/installPrompt.ts` and registers when the module
evaluates — `main.tsx` imports it for its side effect before mounting React. The hook
only reads from that store. Reproduced deterministically by delaying
`/assets/LoginPage-*.js` by 1.5s via `route()`: absent before, present after (also at
a 4s delay). `test:pwa` against the HTTPS domain now passes.

**Revenue chart did not animate on a real iPhone.** Measured rather than guessed:
the path animation does run in WebKit, and it triggers with the chart 100% visible at
y=601..715 of an 844px viewport — so neither "broken" nor "fires too early". What
fits is that iOS Safari suspends `requestAnimationFrame` during momentum scrolling
while framer-motion interpolates against wall-clock time: the animation spends its
1.4s without painting a frame and snaps to the end on resume, which looks exactly
like it never ran.

The chart's three animations move to CSS keyframes, which keep their own timeline in
the engine. The component only decides *when* (a `useInView` setting
`data-ld-rev-visible`). `prefers-reduced-motion` resolves in CSS too, and still
resolves to the *drawn* state — a line left at `dashoffset: 1px` with no animation
would be invisible forever. Verified: `getAnimations()` returns a `CSSAnimation`, and
under reduced motion the line renders complete.

Not verified: no physical iPhone here, and Playwright WebKit on Windows does not
reproduce iOS's rAF suspension. This is the standard mitigation and changes nothing
on desktop, but on-device confirmation is still outstanding.

Verified: typecheck clean; landing 13/13, PWA passed, responsive 0 findings, visual
62 screens / 0 errors, unit 39/39, e2e 33/33, admin 17/17, booking 12/12.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-28 15:09:29 -06:00

83 lines
2.6 KiB
TypeScript

/**
* Captura de `beforeinstallprompt` a nivel de módulo, no dentro de un hook.
*
* El navegador dispara `beforeinstallprompt` **una sola vez** por carga de página, poco
* después del `load`, y no lo repite: no hay forma de volver a pedirlo. Un listener que
* se registra al montar un componente sencillamente se lo pierde si el componente aparece
* más tarde.
*
* Y aparece más tarde: `LoginPage` se carga con `React.lazy`, así que `InstallAppPrompt`
* monta después de una ida y vuelta de red extra para traer su chunk. En local eso es un
* milisegundo y no se nota; sobre una conexión real el evento ya pasó y el botón de
* instalar no aparecía nunca. `pwa-e2e.mjs` contra el dominio HTTPS lo detecta; contra
* `localhost` no, porque ahí el chunk llega antes que el evento.
*
* Por eso el listener se registra al evaluar este módulo, que `main.tsx` importa antes de
* montar React, y el evento queda guardado hasta que alguien lo pida.
*/
export interface BeforeInstallPromptEvent extends Event {
prompt: () => Promise<void>;
userChoice: Promise<{ outcome: "accepted" | "dismissed"; platform: string }>;
}
let capturado: BeforeInstallPromptEvent | null = null;
let instalado = false;
const suscriptores = new Set<() => void>();
function avisar() {
for (const notificar of suscriptores) notificar();
}
if (typeof window !== "undefined") {
window.addEventListener("beforeinstallprompt", (event) => {
// `preventDefault` evita el mini-infobar de Chrome; el botón propio queda a cargo.
event.preventDefault();
capturado = event as BeforeInstallPromptEvent;
avisar();
});
window.addEventListener("appinstalled", () => {
capturado = null;
instalado = true;
avisar();
});
}
/** El evento pendiente, o null si el navegador nunca lo disparó. */
export function eventoDisponible(): BeforeInstallPromptEvent | null {
return capturado;
}
export function yaInstalado(): boolean {
return instalado;
}
/** Lo saca del almacén: un `BeforeInstallPromptEvent` solo se puede usar una vez. */
export function tomarEvento(): BeforeInstallPromptEvent | null {
const evento = capturado;
if (evento) {
capturado = null;
avisar();
}
return evento;
}
/** Lo devuelve si `prompt()` falló, para no perder la única oportunidad de instalar. */
export function devolverEvento(evento: BeforeInstallPromptEvent) {
capturado = evento;
avisar();
}
export function marcarInstalado() {
capturado = null;
instalado = true;
avisar();
}
export function suscribir(notificar: () => void): () => void {
suscriptores.add(notificar);
return () => {
suscriptores.delete(notificar);
};
}