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]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
842a9ea07e
commit
4281567207
@@ -1,6 +1,6 @@
|
||||
import { motion } from "framer-motion";
|
||||
import { EASE_EXPO, inView } from "../../../lib/motion";
|
||||
import { useReducedMotion } from "../../../lib/useReducedMotion";
|
||||
import { useRef } from "react";
|
||||
import { useInView } from "framer-motion";
|
||||
import { inView } from "../../../lib/motion";
|
||||
|
||||
// Serie fija: doce meses con tendencia al alza y ruido creíble. Determinista a
|
||||
// propósito, para que el audit visual capture siempre la misma gráfica.
|
||||
@@ -23,14 +23,29 @@ function pathFrom(serie: number[]): string {
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
/** Línea de ingresos que se traza sola. El "antes/después" no se explica: se ve. */
|
||||
/**
|
||||
* Línea de ingresos que se traza sola. El "antes/después" no se explica: se ve.
|
||||
*
|
||||
* El trazo lo hacen animaciones CSS (`.ld-rev-*` en index.css) y no `motion.path`. No es
|
||||
* una preferencia de estilo: iOS Safari suspende `requestAnimationFrame` durante el scroll
|
||||
* por inercia, y framer-motion interpola contra el reloj de pared, así que la animación
|
||||
* gastaba su duración sin pintar nada y saltaba al final. En un iPhone se veía como si
|
||||
* nunca hubiera animado. Este componente solo decide CUÁNDO empieza; el CÓMO es del
|
||||
* compositor, que sí sigue dibujando.
|
||||
*
|
||||
* `prefers-reduced-motion` también se resuelve en CSS, así que ya no hace falta el hook.
|
||||
*/
|
||||
export function RevenueLineVisual({ className = "" }: { className?: string }) {
|
||||
const reduced = useReducedMotion();
|
||||
const ref = useRef<SVGSVGElement>(null);
|
||||
// Mismo umbral que el resto de la landing, y `once` para que no se repita al volver.
|
||||
const visible = useInView(ref, inView);
|
||||
const d = pathFrom(SERIE);
|
||||
const area = `${d} L${W - PAD} ${H - PAD} L${PAD} ${H - PAD} Z`;
|
||||
|
||||
return (
|
||||
<svg
|
||||
ref={ref}
|
||||
data-ld-rev-visible={visible ? "true" : "false"}
|
||||
viewBox={`0 0 ${W} ${H}`}
|
||||
className={`w-full ${className}`}
|
||||
role="img"
|
||||
@@ -57,36 +72,26 @@ export function RevenueLineVisual({ className = "" }: { className?: string }) {
|
||||
/>
|
||||
))}
|
||||
|
||||
<motion.path
|
||||
d={area}
|
||||
fill="url(#ld-rev-fill)"
|
||||
initial={{ opacity: reduced ? 1 : 0 }}
|
||||
whileInView={{ opacity: 1 }}
|
||||
viewport={inView}
|
||||
transition={{ duration: 0.9, delay: reduced ? 0 : 0.5, ease: EASE_EXPO }}
|
||||
/>
|
||||
<motion.path
|
||||
<path className="ld-rev-area" d={area} fill="url(#ld-rev-fill)" />
|
||||
{/* `pathLength={1}` normaliza la longitud: deja que dasharray y dashoffset se
|
||||
expresen como fracción del trazo, que es lo que animan los keyframes. */}
|
||||
<path
|
||||
className="ld-rev-linea"
|
||||
d={d}
|
||||
pathLength={1}
|
||||
fill="none"
|
||||
stroke="#3b66ff"
|
||||
strokeWidth="2.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
initial={{ pathLength: reduced ? 1 : 0 }}
|
||||
whileInView={{ pathLength: 1 }}
|
||||
viewport={inView}
|
||||
transition={{ duration: reduced ? 0 : 1.4, ease: EASE_EXPO }}
|
||||
/>
|
||||
{/* Punto final: la marca del "hoy". Aterriza cuando la línea termina. */}
|
||||
<motion.circle
|
||||
<circle
|
||||
className="ld-rev-punto"
|
||||
cx={W - PAD}
|
||||
cy={yDe(SERIE[SERIE.length - 1])}
|
||||
r="5"
|
||||
fill="#3b66ff"
|
||||
initial={{ scale: reduced ? 1 : 0 }}
|
||||
whileInView={{ scale: 1 }}
|
||||
viewport={inView}
|
||||
transition={{ duration: 0.5, delay: reduced ? 0 : 1.3, ease: EASE_EXPO }}
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
@@ -624,6 +624,83 @@ summary {
|
||||
color: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Gráfica de ingresos de la landing ----
|
||||
Se anima con CSS y NO con framer-motion a propósito. iOS Safari suspende
|
||||
`requestAnimationFrame` mientras dura el scroll por inercia, y framer-motion
|
||||
interpola contra el reloj de pared: la animación consume su duración sin pintar un
|
||||
solo fotograma y al reanudarse salta al estado final. En un iPhone se ve exactamente
|
||||
como si nunca hubiera animado, que es el defecto que se reportó. Una animación CSS
|
||||
lleva su propia línea de tiempo y sí se dibuja.
|
||||
El easing es el mismo `EASE_EXPO` de src/lib/motion.ts; si cambia uno, cambia el otro. */
|
||||
.ld-rev-linea {
|
||||
stroke-dasharray: 1px 1px; /* con pathLength="1" las unidades son la longitud total */
|
||||
stroke-dashoffset: 1px;
|
||||
}
|
||||
.ld-rev-area {
|
||||
opacity: 0;
|
||||
}
|
||||
.ld-rev-punto {
|
||||
/* `fill-box` para que el centro del círculo sea el origen y no el del lienzo SVG. */
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
transform: scale(0);
|
||||
}
|
||||
[data-ld-rev-visible="true"] .ld-rev-linea {
|
||||
animation: ld-rev-trazo 1.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;
|
||||
}
|
||||
[data-ld-rev-visible="true"] .ld-rev-area {
|
||||
animation: ld-rev-aparecer 0.9s cubic-bezier(0.16, 1, 0.3, 1) 0.5s forwards;
|
||||
}
|
||||
[data-ld-rev-visible="true"] .ld-rev-punto {
|
||||
animation: ld-rev-aterrizar 0.5s cubic-bezier(0.16, 1, 0.3, 1) 1.3s forwards;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes ld-rev-trazo {
|
||||
from {
|
||||
stroke-dashoffset: 1px;
|
||||
}
|
||||
to {
|
||||
stroke-dashoffset: 0px;
|
||||
}
|
||||
}
|
||||
@keyframes ld-rev-aparecer {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes ld-rev-aterrizar {
|
||||
from {
|
||||
transform: scale(0);
|
||||
}
|
||||
to {
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Con movimiento reducido la gráfica sale ya dibujada. Igual que el resto de la landing,
|
||||
el estado inicial resuelve al FINAL y no se acorta la transición: si dejara la línea en
|
||||
`dashoffset: 1px` sin animación, quedaría invisible para siempre. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ld-rev-linea,
|
||||
[data-ld-rev-visible="true"] .ld-rev-linea {
|
||||
stroke-dashoffset: 0px;
|
||||
animation: none;
|
||||
}
|
||||
.ld-rev-area,
|
||||
[data-ld-rev-visible="true"] .ld-rev-area {
|
||||
opacity: 1;
|
||||
animation: none;
|
||||
}
|
||||
.ld-rev-punto,
|
||||
[data-ld-rev-visible="true"] .ld-rev-punto {
|
||||
transform: scale(1);
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Anti auto-zoom de iOS (fuera de @layer para ganar a las utilidades) ----
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* 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);
|
||||
};
|
||||
}
|
||||
+40
-29
@@ -1,12 +1,15 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
devolverEvento,
|
||||
eventoDisponible,
|
||||
marcarInstalado,
|
||||
suscribir,
|
||||
tomarEvento,
|
||||
yaInstalado,
|
||||
} from "./installPrompt";
|
||||
|
||||
export type InstallPromptState = "unsupported" | "available" | "ios-instructions" | "installed";
|
||||
|
||||
interface BeforeInstallPromptEvent extends Event {
|
||||
prompt: () => Promise<void>;
|
||||
userChoice: Promise<{ outcome: "accepted" | "dismissed"; platform: string }>;
|
||||
}
|
||||
|
||||
const DISMISSED_STORAGE_KEY = "agendamax-install-dismissed";
|
||||
|
||||
function hasDismissedPrompt() {
|
||||
@@ -44,13 +47,18 @@ function isIOSSafari() {
|
||||
return ios && /Safari/i.test(ua) && !/CriOS|FxiOS|EdgiOS|OPiOS/i.test(ua);
|
||||
}
|
||||
|
||||
/**
|
||||
* El estado inicial ya consulta el almacén de `installPrompt`: cuando este hook corre, el
|
||||
* evento puede haberse disparado hace rato. No se registra un listener propio aquí a
|
||||
* propósito — ver el comentario de `src/lib/installPrompt.ts`.
|
||||
*/
|
||||
export function useInstallPrompt() {
|
||||
const [state, setState] = useState<InstallPromptState>(() => {
|
||||
if (typeof window === "undefined") return "unsupported";
|
||||
if (isStandalone()) return "installed";
|
||||
if (isStandalone() || yaInstalado()) return "installed";
|
||||
if (eventoDisponible()) return hasDismissedPrompt() ? "unsupported" : "available";
|
||||
return isIOSSafari() ? "ios-instructions" : "unsupported";
|
||||
});
|
||||
const [deferred, setDeferred] = useState<BeforeInstallPromptEvent | null>(null);
|
||||
const [dismissed, setDismissed] = useState(() => typeof window !== "undefined" && hasDismissedPrompt());
|
||||
const installInFlight = useRef(false);
|
||||
|
||||
@@ -60,41 +68,44 @@ export function useInstallPrompt() {
|
||||
return;
|
||||
}
|
||||
|
||||
const onBeforeInstallPrompt = (event: Event) => {
|
||||
event.preventDefault();
|
||||
setDeferred(event as BeforeInstallPromptEvent);
|
||||
if (!hasDismissedPrompt()) setState("available");
|
||||
};
|
||||
const onInstalled = () => {
|
||||
setDeferred(null);
|
||||
clearDismissedPrompt();
|
||||
setDismissed(false);
|
||||
setState("installed");
|
||||
const sincronizar = () => {
|
||||
if (yaInstalado()) {
|
||||
// Instalar borra el descarte: el aviso ya cumplió su función.
|
||||
clearDismissedPrompt();
|
||||
setDismissed(false);
|
||||
setState("installed");
|
||||
return;
|
||||
}
|
||||
if (eventoDisponible()) {
|
||||
if (!hasDismissedPrompt()) setState("available");
|
||||
return;
|
||||
}
|
||||
// Sin evento pendiente: se cae al comportamiento de iOS, que nunca lo dispara.
|
||||
setState(isIOSSafari() ? "ios-instructions" : "unsupported");
|
||||
};
|
||||
|
||||
window.addEventListener("beforeinstallprompt", onBeforeInstallPrompt);
|
||||
window.addEventListener("appinstalled", onInstalled);
|
||||
return () => {
|
||||
window.removeEventListener("beforeinstallprompt", onBeforeInstallPrompt);
|
||||
window.removeEventListener("appinstalled", onInstalled);
|
||||
};
|
||||
sincronizar();
|
||||
return suscribir(sincronizar);
|
||||
}, []);
|
||||
|
||||
const install = async () => {
|
||||
if (!deferred || installInFlight.current) return;
|
||||
const event = deferred;
|
||||
if (installInFlight.current) return;
|
||||
const event = tomarEvento();
|
||||
if (!event) return;
|
||||
installInFlight.current = true;
|
||||
setDeferred(null);
|
||||
try {
|
||||
await event.prompt();
|
||||
const choice = await event.userChoice;
|
||||
if (choice.outcome === "accepted") setState("installed");
|
||||
else {
|
||||
if (choice.outcome === "accepted") {
|
||||
marcarInstalado();
|
||||
setState("installed");
|
||||
} else {
|
||||
persistDismissedPrompt();
|
||||
setDismissed(true);
|
||||
}
|
||||
} catch {
|
||||
setDeferred(event);
|
||||
// Devolver el evento al almacén: es la única oportunidad de instalar de esta carga.
|
||||
devolverEvento(event);
|
||||
setState("available");
|
||||
} finally {
|
||||
installInFlight.current = false;
|
||||
|
||||
@@ -2,6 +2,10 @@ import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
// Importado por su efecto y antes de montar React a propósito: registra el listener de
|
||||
// `beforeinstallprompt`, que el navegador dispara una sola vez y muy temprano. Si esperara
|
||||
// a que monte el componente del botón —que vive en una ruta lazy— llegaría tarde.
|
||||
import "./lib/installPrompt";
|
||||
import App from "./App.tsx";
|
||||
import "./index.css";
|
||||
|
||||
|
||||
Reference in New Issue
Block a user