UI: reemplazar diálogos nativos del navegador por modales/avisos propios de la plataforma
Los confirm()/alert()/prompt() nativos se veían fuera de la marca ("<dominio> dice…").
Se agrega un DialogProvider (montado en el layout autenticado) con su estilo visual y se
consume via hooks useConfirm / usePrompt / useToast:
- confirmaciones -> modal propio (con variante "peligro" para eliminaciones)
- prompts (crear paquete / fase) -> modal con input
- alerts de error/éxito -> toasts
Reemplazados todos los diálogos nativos: RegistroHorasPanel, CatalogoClient,
ConfiguracionClient, CotizacionForm, ExportButtons, ListDeleteButton, DeleteButton,
CambiarEstadoButtons. Validado E2E (Playwright): al revertir una partida pagada aparece
el modal propio y NO se dispara el confirm nativo.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
1aab45f29c
commit
26e6d3a9bf
@@ -37,6 +37,7 @@ import {
|
||||
useCotizacionStore,
|
||||
ServicioSeleccionado,
|
||||
} from "@/lib/store";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
import {
|
||||
ExportPDFButtonDraft,
|
||||
ExportExcelButtonDraft,
|
||||
@@ -136,6 +137,7 @@ export function CotizacionForm({
|
||||
}: CotizacionFormProps) {
|
||||
const router = useRouter();
|
||||
const store = useCotizacionStore();
|
||||
const showToast = useToast();
|
||||
|
||||
const [expandedFases, setExpandedFases] = useState<Set<number>>(
|
||||
new Set([0, 1, 2, 3])
|
||||
@@ -369,10 +371,10 @@ export function CotizacionForm({
|
||||
}
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert("Error: " + (err.error || "No se pudo guardar"));
|
||||
showToast("Error: " + (err.error || "No se pudo guardar"), "error");
|
||||
}
|
||||
} catch {
|
||||
alert("Error al guardar la cotizacion");
|
||||
showToast("Error al guardar la cotización", "error");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { Eye, FileDown, FileSpreadsheet, Loader2, X } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
|
||||
function getFilenameFromHeaders(headers: Headers, fallback: string): string {
|
||||
const cd = headers.get("Content-Disposition");
|
||||
@@ -14,6 +15,7 @@ function getFilenameFromHeaders(headers: Headers, fallback: string): string {
|
||||
|
||||
function useFileExport() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const showToast = useToast();
|
||||
|
||||
const download = async (url: string, fallback: string) => {
|
||||
setLoading(true);
|
||||
@@ -29,10 +31,10 @@ function useFileExport() {
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
} else {
|
||||
alert("Error al exportar");
|
||||
showToast("Error al exportar", "error");
|
||||
}
|
||||
} catch {
|
||||
alert("Error al exportar");
|
||||
showToast("Error al exportar", "error");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -56,10 +58,10 @@ function useFileExport() {
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
} else {
|
||||
alert("Error al exportar");
|
||||
showToast("Error al exportar", "error");
|
||||
}
|
||||
} catch {
|
||||
alert("Error al exportar");
|
||||
showToast("Error al exportar", "error");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -175,6 +177,7 @@ function PDFPreviewModal({
|
||||
function usePDFPreview() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [preview, setPreview] = useState<{ url: string; filename: string } | null>(null);
|
||||
const showToast = useToast();
|
||||
|
||||
const open = async (fetcher: () => Promise<Response>, fallback: string) => {
|
||||
setLoading(true);
|
||||
@@ -186,10 +189,10 @@ function usePDFPreview() {
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
setPreview({ url, filename });
|
||||
} else {
|
||||
alert("Error al generar la previsualización");
|
||||
showToast("Error al generar la previsualización", "error");
|
||||
}
|
||||
} catch {
|
||||
alert("Error al generar la previsualización");
|
||||
showToast("Error al generar la previsualización", "error");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { AlertTriangle, CheckCircle2, Info, XCircle, X } from "lucide-react";
|
||||
|
||||
// Sistema de ventanas emergentes PROPIO de la plataforma (con su estilo visual),
|
||||
// para reemplazar los diálogos nativos del navegador (confirm/alert/prompt), que
|
||||
// se ven fuera de la marca ("<dominio> dice…"). Se monta una sola vez en el layout
|
||||
// y se consume con los hooks useConfirm / usePrompt / useToast.
|
||||
|
||||
type ConfirmOptions = {
|
||||
title?: string;
|
||||
message: string;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
danger?: boolean;
|
||||
};
|
||||
|
||||
type PromptOptions = {
|
||||
title?: string;
|
||||
message?: string;
|
||||
label?: string;
|
||||
defaultValue?: string;
|
||||
placeholder?: string;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
};
|
||||
|
||||
type ToastKind = "success" | "error" | "info";
|
||||
type ToastItem = { id: number; message: string; kind: ToastKind };
|
||||
|
||||
type DialogContextValue = {
|
||||
confirm: (opts: ConfirmOptions | string) => Promise<boolean>;
|
||||
prompt: (opts: PromptOptions | string) => Promise<string | null>;
|
||||
toast: (message: string, kind?: ToastKind) => void;
|
||||
};
|
||||
|
||||
const DialogContext = createContext<DialogContextValue | null>(null);
|
||||
|
||||
type ActiveConfirm = { kind: "confirm"; opts: ConfirmOptions; resolve: (v: boolean) => void };
|
||||
type ActivePrompt = { kind: "prompt"; opts: PromptOptions; resolve: (v: string | null) => void };
|
||||
type Active = ActiveConfirm | ActivePrompt | null;
|
||||
|
||||
export function DialogProvider({ children }: { children: React.ReactNode }) {
|
||||
const [active, setActive] = useState<Active>(null);
|
||||
const [promptValue, setPromptValue] = useState("");
|
||||
const [toasts, setToasts] = useState<ToastItem[]>([]);
|
||||
const toastSeq = useRef(0);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const confirmBtnRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const confirm = useCallback((o: ConfirmOptions | string) => {
|
||||
const opts = typeof o === "string" ? { message: o } : o;
|
||||
return new Promise<boolean>((resolve) => setActive({ kind: "confirm", opts, resolve }));
|
||||
}, []);
|
||||
|
||||
const prompt = useCallback((o: PromptOptions | string) => {
|
||||
const opts = typeof o === "string" ? { message: o } : o;
|
||||
setPromptValue(opts.defaultValue ?? "");
|
||||
return new Promise<string | null>((resolve) => setActive({ kind: "prompt", opts, resolve }));
|
||||
}, []);
|
||||
|
||||
const toast = useCallback((message: string, kind: ToastKind = "info") => {
|
||||
const id = ++toastSeq.current;
|
||||
setToasts((t) => [...t, { id, message, kind }]);
|
||||
setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 4500);
|
||||
}, []);
|
||||
|
||||
// Resuelven la promesa del diálogo activo y lo cierran. Se ejecutan en manejadores
|
||||
// de eventos (post-render), capturando el `active` vigente: nada de efectos dentro
|
||||
// del updater de setState (evita dobles resoluciones en StrictMode).
|
||||
const finishConfirm = (v: boolean) => {
|
||||
if (active?.kind === "confirm") active.resolve(v);
|
||||
setActive(null);
|
||||
};
|
||||
const finishPrompt = (v: string | null) => {
|
||||
if (active?.kind === "prompt") active.resolve(v);
|
||||
setActive(null);
|
||||
};
|
||||
const dismiss = () => {
|
||||
if (active?.kind === "confirm") active.resolve(false);
|
||||
else if (active?.kind === "prompt") active.resolve(null);
|
||||
setActive(null);
|
||||
};
|
||||
|
||||
// Foco automático al abrir + cerrar con Escape.
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const t = setTimeout(() => {
|
||||
if (active.kind === "prompt") inputRef.current?.focus();
|
||||
else confirmBtnRef.current?.focus();
|
||||
}, 30);
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key !== "Escape") return;
|
||||
if (active.kind === "confirm") active.resolve(false);
|
||||
else active.resolve(null);
|
||||
setActive(null);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, [active]);
|
||||
|
||||
const value = useMemo(() => ({ confirm, prompt, toast }), [confirm, prompt, toast]);
|
||||
|
||||
return (
|
||||
<DialogContext.Provider value={value}>
|
||||
{children}
|
||||
|
||||
{active && (
|
||||
<div
|
||||
className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 p-4"
|
||||
onClick={dismiss}
|
||||
role="presentation"
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-md rounded-xl bg-card-bg border border-border shadow-2xl overflow-hidden"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
>
|
||||
{active.kind === "confirm" ? (
|
||||
<ConfirmBody
|
||||
opts={active.opts}
|
||||
confirmBtnRef={confirmBtnRef}
|
||||
onCancel={() => finishConfirm(false)}
|
||||
onConfirm={() => finishConfirm(true)}
|
||||
/>
|
||||
) : (
|
||||
<PromptBody
|
||||
opts={active.opts}
|
||||
value={promptValue}
|
||||
setValue={setPromptValue}
|
||||
inputRef={inputRef}
|
||||
onCancel={() => finishPrompt(null)}
|
||||
onSubmit={() => finishPrompt(promptValue)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Avisos (toasts) */}
|
||||
<div className="fixed bottom-4 right-4 z-[110] flex flex-col gap-2 max-w-[calc(100vw-2rem)]">
|
||||
{toasts.map((t) => (
|
||||
<ToastCard key={t.id} item={t} onClose={() => setToasts((ts) => ts.filter((x) => x.id !== t.id))} />
|
||||
))}
|
||||
</div>
|
||||
</DialogContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function ConfirmBody({
|
||||
opts,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
confirmBtnRef,
|
||||
}: {
|
||||
opts: ConfirmOptions;
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void;
|
||||
confirmBtnRef: React.RefObject<HTMLButtonElement | null>;
|
||||
}) {
|
||||
return (
|
||||
<div className="p-5">
|
||||
<div className="flex items-start gap-3">
|
||||
<div
|
||||
className={`mt-0.5 shrink-0 rounded-full p-2 ${
|
||||
opts.danger ? "bg-red-100 text-red-600" : "bg-primary-light text-primary"
|
||||
}`}
|
||||
>
|
||||
{opts.danger ? <AlertTriangle className="w-5 h-5" /> : <Info className="w-5 h-5" />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
{opts.title && <h3 className="font-semibold text-base mb-1">{opts.title}</h3>}
|
||||
<p className="text-sm text-foreground/80 whitespace-pre-line">{opts.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
className="px-4 py-2 rounded-lg border border-border text-sm hover:bg-gray-50"
|
||||
>
|
||||
{opts.cancelText || "Cancelar"}
|
||||
</button>
|
||||
<button
|
||||
ref={confirmBtnRef}
|
||||
type="button"
|
||||
onClick={onConfirm}
|
||||
className={`px-4 py-2 rounded-lg text-sm text-white hover:opacity-90 ${
|
||||
opts.danger ? "bg-red-600" : "bg-primary"
|
||||
}`}
|
||||
>
|
||||
{opts.confirmText || "Aceptar"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PromptBody({
|
||||
opts,
|
||||
value,
|
||||
setValue,
|
||||
inputRef,
|
||||
onCancel,
|
||||
onSubmit,
|
||||
}: {
|
||||
opts: PromptOptions;
|
||||
value: string;
|
||||
setValue: (v: string) => void;
|
||||
inputRef: React.RefObject<HTMLInputElement | null>;
|
||||
onCancel: () => void;
|
||||
onSubmit: () => void;
|
||||
}) {
|
||||
return (
|
||||
<form
|
||||
className="p-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmit();
|
||||
}}
|
||||
>
|
||||
{opts.title && <h3 className="font-semibold text-base mb-1">{opts.title}</h3>}
|
||||
{opts.message && <p className="text-sm text-foreground/80 mb-3">{opts.message}</p>}
|
||||
{opts.label && <label className="block text-xs text-muted mb-1">{opts.label}</label>}
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
placeholder={opts.placeholder}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
/>
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
className="px-4 py-2 rounded-lg border border-border text-sm hover:bg-gray-50"
|
||||
>
|
||||
{opts.cancelText || "Cancelar"}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!value.trim()}
|
||||
className="px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{opts.confirmText || "Aceptar"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
const TOAST_STYLE: Record<ToastKind, { cls: string; icon: React.ReactNode }> = {
|
||||
success: { cls: "border-green-200 bg-green-50 text-green-800", icon: <CheckCircle2 className="w-4 h-4" /> },
|
||||
error: { cls: "border-red-200 bg-red-50 text-red-800", icon: <XCircle className="w-4 h-4" /> },
|
||||
info: { cls: "border-blue-200 bg-blue-50 text-blue-800", icon: <Info className="w-4 h-4" /> },
|
||||
};
|
||||
|
||||
function ToastCard({ item, onClose }: { item: ToastItem; onClose: () => void }) {
|
||||
const s = TOAST_STYLE[item.kind];
|
||||
return (
|
||||
<div
|
||||
className={`flex items-start gap-2 rounded-lg border px-3 py-2 shadow-lg text-sm ${s.cls}`}
|
||||
role="status"
|
||||
>
|
||||
<span className="mt-0.5 shrink-0">{s.icon}</span>
|
||||
<span className="min-w-0 break-words">{item.message}</span>
|
||||
<button onClick={onClose} className="ml-1 shrink-0 opacity-60 hover:opacity-100" aria-label="Cerrar aviso">
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function useDialogs(): DialogContextValue {
|
||||
const ctx = useContext(DialogContext);
|
||||
if (!ctx) throw new Error("useDialogs debe usarse dentro de <DialogProvider>");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export const useConfirm = () => useDialogs().confirm;
|
||||
export const usePrompt = () => useDialogs().prompt;
|
||||
export const useToast = () => useDialogs().toast;
|
||||
Reference in New Issue
Block a user