Frontend: scroll fix, SSE reconnect, toast global, stale states, theming
5 bloques en una pasada:
A. Scroll fixes (síntoma reportado por el usuario):
- run-timeline: nuevo flag _userScrolledUp con detección por rAF en
bindScroll. Auto-scroll al final SOLO si el usuario está abajo
(umbral 150px) o si él mismo disparó un optimistic bubble. Cuando
el usuario manda mensaje, se resetea el flag y se scrollea.
- conversation-inspector: mismo patrón. ui:chatScroll respeta el
flag userScrolledUp del emisor para no perseguir al usuario que
lee arriba.
- .bubble: + min-width:0, overflow-wrap:anywhere para URLs/JSON
largos sin espacios.
- <pre>: + overflow-x:auto, max-width:100%.
- chat-simulator: textarea con resize:vertical, min/max heights
viewport-friendly. inputs-col con overflow-y:auto.
B. Stale state options:
- conversation-list y conversations-crud: dropdowns ahora muestran
IDLE / CART / SHIPPING / AWAITING_HUMAN. Quitados BROWSING,
BUILDING_ORDER, WAITING_ADDRESS, WAITING_PAYMENT, COMPLETED.
- main.js: simulated plan.next_state pasa a CART.
C. SSE resilience (lib/sse.js):
- connect() con backoff exponencial (1s → 30s).
- safeParse() helper: cada evento envuelve JSON.parse en try-catch
para que un payload malformado no rompa otros listeners.
- reset retryDelay al primer "hello" exitoso.
- ops-shell: indicador con dot (verde "En vivo" / naranja pulsante
"Reconectando…") en lugar de texto plano.
D. Toast service global (public/lib/toast.js):
- API simple: toast({ kind, text, ms }). Apila, animación slide-in,
auto-dismiss 4s. Click para cerrar.
- safeFetch en api.js: wrapper que dispara toast en network error y
non-OK. Migrados simEvolution + retryLast.
- chat-simulator usa toast en lugar de status text efímero.
E. Theming con CSS vars:
- public/styles/theme.css con paleta completa (panels, borders,
text, accents, bubbles, charts, radii, shadows). Linkeado desde
index.html.
- Migrados a var(--*) los 5 componentes más visibles:
run-timeline, chat-simulator, conversation-inspector,
conversation-list, home-dashboard. Custom properties heredan a
través del shadow DOM, así que los demás componentes pueden
migrar gradualmente sin cambios estructurales.
- home-dashboard ya tenía vars locales: ahora apuntan a las globales.
Backend: 192/192 tests pasando. Sin cambios de API.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,35 @@
|
||||
import { toast } from "./toast.js";
|
||||
|
||||
/**
|
||||
* fetch wrapper que dispara toast en error de red o respuesta no-OK.
|
||||
* Devuelve la respuesta parseada como JSON. Si la respuesta tiene
|
||||
* `{ ok: false, error }`, también dispara toast.
|
||||
*/
|
||||
export async function safeFetch(url, opts = {}, { silent = false, label = null } = {}) {
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, opts);
|
||||
} catch (err) {
|
||||
if (!silent) toast({ kind: "error", text: `${label || "Red"}: ${err?.message || "sin conexión"}` });
|
||||
throw err;
|
||||
}
|
||||
if (!res.ok) {
|
||||
let body = null;
|
||||
try { body = await res.json(); } catch (_) {}
|
||||
const msg = body?.error || body?.message || `${res.status} ${res.statusText}`;
|
||||
if (!silent) toast({ kind: "error", text: `${label || "Error"}: ${msg}` });
|
||||
const err = new Error(msg);
|
||||
err.status = res.status;
|
||||
err.body = body;
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
return await res.json();
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
async conversations({ q = "", status = "", state = "" } = {}) {
|
||||
const u = new URL("/conversations", location.origin);
|
||||
@@ -46,16 +78,16 @@ export const api = {
|
||||
},
|
||||
|
||||
async simEvolution(payload) {
|
||||
return fetch("/webhook/evolution", {
|
||||
return safeFetch("/webhook/evolution", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
}).then(r => r.json());
|
||||
}, { label: "Sim Evolution" });
|
||||
},
|
||||
|
||||
async retryLast(chat_id) {
|
||||
if (!chat_id) throw new Error("chat_id_required");
|
||||
return fetch(`/conversations/${encodeURIComponent(chat_id)}/retry-last`, { method: "POST" }).then(r => r.json());
|
||||
return safeFetch(`/conversations/${encodeURIComponent(chat_id)}/retry-last`, { method: "POST" }, { label: "Retry" });
|
||||
},
|
||||
|
||||
// Products CRUD
|
||||
|
||||
@@ -1,15 +1,71 @@
|
||||
import { emit } from "./bus.js";
|
||||
|
||||
export function connectSSE() {
|
||||
const es = new EventSource("/stream");
|
||||
/**
|
||||
* SSE client con reconnect exponencial y try-catch en parseo.
|
||||
* Si el server reinicia o un evento viene malformado, no rompe la app.
|
||||
*/
|
||||
|
||||
es.addEventListener("hello", () => emit("sse:status", { ok: true }));
|
||||
es.addEventListener("conversation.upsert", (e) => emit("conversation:upsert", JSON.parse(e.data)));
|
||||
es.addEventListener("run.created", (e) => emit("run:created", JSON.parse(e.data)));
|
||||
es.addEventListener("takeover.created", (e) => emit("takeover:created", JSON.parse(e.data)));
|
||||
es.addEventListener("order.created", (e) => emit("order:created", JSON.parse(e.data)));
|
||||
let _es = null;
|
||||
let _retryDelay = 1000;
|
||||
let _retryTimer = null;
|
||||
const MAX_RETRY = 30_000;
|
||||
|
||||
es.onerror = () => emit("sse:status", { ok: false });
|
||||
const EVENTS = [
|
||||
["conversation.upsert", "conversation:upsert"],
|
||||
["run.created", "run:created"],
|
||||
["takeover.created", "takeover:created"],
|
||||
["order.created", "order:created"],
|
||||
];
|
||||
|
||||
return es;
|
||||
function safeParse(rawData, evName) {
|
||||
try {
|
||||
return JSON.parse(rawData);
|
||||
} catch (err) {
|
||||
console.error(`[sse] bad payload for ${evName}:`, err?.message || err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function attach(es) {
|
||||
es.addEventListener("hello", () => {
|
||||
_retryDelay = 1000; // reset on success
|
||||
emit("sse:status", { ok: true });
|
||||
});
|
||||
|
||||
for (const [serverName, busName] of EVENTS) {
|
||||
es.addEventListener(serverName, (e) => {
|
||||
const data = safeParse(e.data, serverName);
|
||||
if (data !== null) emit(busName, data);
|
||||
});
|
||||
}
|
||||
|
||||
es.onerror = () => {
|
||||
emit("sse:status", { ok: false });
|
||||
try { es.close(); } catch (_) {}
|
||||
if (_es === es) _es = null;
|
||||
scheduleReconnect();
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleReconnect() {
|
||||
if (_retryTimer) return;
|
||||
const delay = _retryDelay;
|
||||
_retryTimer = setTimeout(() => {
|
||||
_retryTimer = null;
|
||||
connectSSE();
|
||||
}, delay);
|
||||
_retryDelay = Math.min(_retryDelay * 2, MAX_RETRY);
|
||||
}
|
||||
|
||||
export function connectSSE() {
|
||||
if (_retryTimer) {
|
||||
clearTimeout(_retryTimer);
|
||||
_retryTimer = null;
|
||||
}
|
||||
if (_es) {
|
||||
try { _es.close(); } catch (_) {}
|
||||
}
|
||||
_es = new EventSource("/stream");
|
||||
attach(_es);
|
||||
return _es;
|
||||
}
|
||||
|
||||
81
public/lib/toast.js
Normal file
81
public/lib/toast.js
Normal file
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Toast service global. Sin dependencias.
|
||||
* Inyecta un container en <body> y empuja toasts apilados.
|
||||
*
|
||||
* Uso:
|
||||
* import { toast } from "./toast.js";
|
||||
* toast({ kind: "error", text: "No se pudo guardar" });
|
||||
* toast({ kind: "ok", text: "Listo", ms: 2000 });
|
||||
*/
|
||||
|
||||
const KIND_COLORS = {
|
||||
error: { bg: "#241214", border: "#e74c3c", text: "#ffe9ea" },
|
||||
ok: { bg: "#0f2a1a", border: "#1f6f43", text: "#cdebd8" },
|
||||
warn: { bg: "#2a1f0a", border: "#F59E0B", text: "#ffe6b0" },
|
||||
info: { bg: "#0f2030", border: "#1f6feb", text: "#cce0ff" },
|
||||
};
|
||||
|
||||
let _container = null;
|
||||
|
||||
function ensureContainer() {
|
||||
if (_container) return _container;
|
||||
_container = document.createElement("div");
|
||||
_container.id = "toast-stack";
|
||||
Object.assign(_container.style, {
|
||||
position: "fixed",
|
||||
right: "16px",
|
||||
bottom: "16px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "8px",
|
||||
zIndex: "9999",
|
||||
pointerEvents: "none",
|
||||
maxWidth: "420px",
|
||||
});
|
||||
document.body.appendChild(_container);
|
||||
return _container;
|
||||
}
|
||||
|
||||
export function toast({ kind = "error", text = "", ms = 4000 } = {}) {
|
||||
if (!text) return;
|
||||
const colors = KIND_COLORS[kind] || KIND_COLORS.info;
|
||||
const el = document.createElement("div");
|
||||
Object.assign(el.style, {
|
||||
background: colors.bg,
|
||||
border: `1px solid ${colors.border}`,
|
||||
color: colors.text,
|
||||
padding: "10px 12px",
|
||||
borderRadius: "10px",
|
||||
fontSize: "13px",
|
||||
boxShadow: "0 4px 12px rgba(0,0,0,.4)",
|
||||
pointerEvents: "auto",
|
||||
cursor: "pointer",
|
||||
transform: "translateX(120%)",
|
||||
transition: "transform .25s ease, opacity .25s ease",
|
||||
opacity: "0",
|
||||
wordBreak: "break-word",
|
||||
overflowWrap: "anywhere",
|
||||
});
|
||||
el.textContent = String(text);
|
||||
|
||||
const c = ensureContainer();
|
||||
c.appendChild(el);
|
||||
|
||||
// Animar entrada
|
||||
requestAnimationFrame(() => {
|
||||
el.style.transform = "translateX(0)";
|
||||
el.style.opacity = "1";
|
||||
});
|
||||
|
||||
const dismiss = () => {
|
||||
el.style.transform = "translateX(120%)";
|
||||
el.style.opacity = "0";
|
||||
setTimeout(() => el.remove(), 280);
|
||||
};
|
||||
el.addEventListener("click", dismiss);
|
||||
setTimeout(dismiss, Math.max(800, ms));
|
||||
}
|
||||
|
||||
export function toastError(text) { toast({ kind: "error", text }); }
|
||||
export function toastOk(text) { toast({ kind: "ok", text, ms: 2500 }); }
|
||||
export function toastWarn(text) { toast({ kind: "warn", text }); }
|
||||
Reference in New Issue
Block a user