- app.js: <details data-abrir-al-imprimir> se abre en beforeprint y vuelve a su estado en afterprint (también si la persona lo había cerrado o abierto a mano). - app.css, @media print: sin barra lateral, menú, Salir, migas ni acciones del encabezado; el encabezado conserva el tenant y el usuario. Las tablas pierden el scroll, la altura máxima y el ancho mínimo para que ninguna columna se corte en papel o en PDF.
303 lines
12 KiB
JavaScript
303 lines
12 KiB
JavaScript
// collina-pld · utilidades transversales. Sin framework ni dependencias.
|
|
// Solo lo que comparten todas las pantallas; el código de una pantalla va en su plantilla
|
|
// (bloque `scripts`) o en su propio archivo (static/alta.js, static/laboratorio.js).
|
|
// Chart.js NO se carga aquí: lo trae el laboratorio. Todo es mejora progresiva: sin JS, los
|
|
// formularios se envían y los enlaces navegan igual.
|
|
//
|
|
// pld.toast("Guardado", "exito") tono: info | exito | aviso | peligro
|
|
// <form data-confirmar="¿Cerrar el caso?"> pide confirmación antes de enviar
|
|
// <button data-confirmar="…"> / <a data-confirmar="…"> igual, por botón o enlace
|
|
// <button data-alternar="#id"> muestra u oculta el elemento (clase es-visible);
|
|
// Esc cierra la barra lateral abierta
|
|
// <div data-toast="Guardado" data-tono="exito" hidden></div> toast al cargar la página
|
|
// <button data-requiere="#a,#b"> se habilita cuando #a tiene texto (≥ data-min o
|
|
// minlength) y #b, si es casilla, está marcada
|
|
// <span data-contador="#id" data-min="20"> "12 / 20 mín." → "34 caracteres"
|
|
// <span data-pista-de="#boton" data-pistas="a|b" data-listo="…"> ayuda según lo que falta
|
|
// <button data-distintos="#a,#b"> deshabilitado si los dos selects valen lo mismo
|
|
// <button data-ver-contrasena> Ver / Ocultar la contraseña del mismo campo
|
|
// <tr class="fila-enlace"> la fila navega al primer enlace que contiene
|
|
// <tr data-cajon="#dialogo" data-plantilla="#tpl"> abre el cajón lateral con el <template>
|
|
// <form data-autoenvio> envía los filtros al cambiar un select, fecha,
|
|
// número o casilla
|
|
// <label data-zona-archivo> … [data-zona-nombre] nombre del archivo elegido y arrastre
|
|
// <input type="radio" data-descripcion="…"> pinta la descripción en [data-descripcion-regla]
|
|
// <details data-abrir-al-imprimir> se abre al imprimir (o guardar en PDF) y vuelve a
|
|
// su estado al terminar
|
|
|
|
(() => {
|
|
"use strict";
|
|
|
|
const pld = (window.pld = window.pld || {});
|
|
const $ = (selector, raiz = document) => raiz.querySelector(selector);
|
|
const $$ = (selector, raiz = document) => [...raiz.querySelectorAll(selector)];
|
|
|
|
// --- Toasts y confirmaciones ---------------------------------------------------------------
|
|
|
|
pld.toast = (mensaje, tono = "info", duracionMs = 4500) => {
|
|
const contenedor = document.getElementById("toasts");
|
|
if (!contenedor) return;
|
|
const toast = document.createElement("div");
|
|
toast.className = `toast toast--${tono}`;
|
|
toast.setAttribute("role", tono === "peligro" ? "alert" : "status");
|
|
if (tono !== "peligro" && document.getElementById("i-check")) {
|
|
toast.innerHTML = '<svg class="icono icono--15" aria-hidden="true"><use href="#i-check"/></svg>';
|
|
}
|
|
toast.append(document.createTextNode(mensaje));
|
|
contenedor.append(toast);
|
|
window.setTimeout(() => toast.remove(), duracionMs);
|
|
};
|
|
|
|
pld.confirmar = (mensaje) => window.confirm(mensaje);
|
|
|
|
document.addEventListener("submit", (evento) => {
|
|
const mensaje =
|
|
(evento.submitter && evento.submitter.dataset.confirmar) || evento.target.dataset.confirmar;
|
|
if (mensaje && !pld.confirmar(mensaje)) evento.preventDefault();
|
|
});
|
|
|
|
// --- Requisitos, contadores, pistas y selects distintos ------------------------------------
|
|
|
|
const cumple = (el) => {
|
|
if (!el) return false;
|
|
if (el.type === "checkbox" || el.type === "radio") return el.checked;
|
|
const minimo = Number(el.dataset.min || el.getAttribute("minlength") || 1);
|
|
return el.value.trim().length >= minimo;
|
|
};
|
|
|
|
pld.evaluar = (raiz = document) => {
|
|
$$("[data-requiere]", raiz).forEach((boton) => {
|
|
const falta = boton.dataset.requiere
|
|
.split(",")
|
|
.map((s) => cumple($(s.trim())))
|
|
.indexOf(false);
|
|
boton.disabled = falta !== -1 || boton.dataset.bloqueado === "1";
|
|
if (boton.id) {
|
|
const pista = $(`[data-pista-de="#${boton.id}"]`);
|
|
if (pista) {
|
|
pista.textContent =
|
|
falta === -1 ? pista.dataset.listo || "" : (pista.dataset.pistas || "").split("|")[falta] || "";
|
|
}
|
|
}
|
|
});
|
|
$$("[data-contador]", raiz).forEach((contador) => {
|
|
const campo = $(contador.dataset.contador);
|
|
if (!campo) return;
|
|
const n = campo.value.trim().length;
|
|
const minimo = Number(contador.dataset.min || 0);
|
|
contador.textContent = n < minimo ? `${n} / ${minimo} mín.` : `${n} caracteres`;
|
|
contador.classList.toggle("es-suficiente", n >= minimo);
|
|
});
|
|
$$("[data-distintos]", raiz).forEach((boton) => {
|
|
const [a, b] = boton.dataset.distintos.split(",").map((s) => $(s.trim()));
|
|
boton.disabled = Boolean(a && b && a.value === b.value);
|
|
});
|
|
};
|
|
|
|
document.addEventListener("input", () => pld.evaluar());
|
|
|
|
// --- Filas enlace ----------------------------------------------------------------------------
|
|
// La fila navega al primer enlace que contiene (sin data-href: tests/test_cartera.py cuenta los
|
|
// href="/clientes/ de la página). No intercepta clics en controles de la fila ni cuando hay
|
|
// texto seleccionado; Ctrl/Cmd/Mayús o el clic central abren en otra pestaña.
|
|
|
|
const INTERACTIVOS = "a, button, input, select, textarea, label, summary, details, [contenteditable]";
|
|
|
|
const hayTextoSeleccionado = () => {
|
|
const seleccion = window.getSelection && window.getSelection();
|
|
return Boolean(seleccion && seleccion.toString().trim());
|
|
};
|
|
|
|
const destinoDeFila = (evento) => {
|
|
const fila = evento.target.closest && evento.target.closest("tr.fila-enlace");
|
|
if (!fila || fila.hasAttribute("data-cajon")) return null;
|
|
if (evento.target.closest(INTERACTIVOS) || hayTextoSeleccionado()) return null;
|
|
const enlace = $("a[href]", fila);
|
|
return enlace ? enlace.href : null;
|
|
};
|
|
|
|
// --- Cajón lateral (<dialog class="cajon">) ---------------------------------------------------
|
|
|
|
pld.abrirCajon = (selector, plantilla, origen) => {
|
|
const dialogo = $(selector);
|
|
const contenido = plantilla && $(plantilla);
|
|
if (!dialogo || !contenido || typeof dialogo.showModal !== "function") return false;
|
|
dialogo.replaceChildren(contenido.content.cloneNode(true));
|
|
$$("tr.es-seleccionada").forEach((f) => f.classList.remove("es-seleccionada"));
|
|
if (origen && origen.tagName === "TR") origen.classList.add("es-seleccionada");
|
|
dialogo.addEventListener(
|
|
"close",
|
|
() => {
|
|
if (origen) {
|
|
origen.classList.remove("es-seleccionada");
|
|
origen.focus({ preventScroll: true });
|
|
}
|
|
},
|
|
{ once: true },
|
|
);
|
|
dialogo.showModal();
|
|
pld.evaluar(dialogo);
|
|
return true;
|
|
};
|
|
|
|
const disparadorDeCajon = (evento) => {
|
|
const disparador = evento.target.closest && evento.target.closest("[data-cajon]");
|
|
if (!disparador) return null;
|
|
const interactivo = evento.target.closest(INTERACTIVOS);
|
|
if ((interactivo && interactivo !== disparador) || hayTextoSeleccionado()) return null;
|
|
return disparador;
|
|
};
|
|
|
|
// --- Clics y teclado ---------------------------------------------------------------------------
|
|
|
|
document.addEventListener("click", (evento) => {
|
|
const objetivo = evento.target;
|
|
|
|
const enlace = objetivo.closest("a[data-confirmar]");
|
|
if (enlace && !pld.confirmar(enlace.dataset.confirmar)) {
|
|
evento.preventDefault();
|
|
return;
|
|
}
|
|
|
|
const alternador = objetivo.closest("[data-alternar]");
|
|
if (alternador) {
|
|
const elemento = $(alternador.dataset.alternar);
|
|
if (elemento) {
|
|
const visible = elemento.classList.toggle("es-visible");
|
|
alternador.setAttribute("aria-expanded", String(visible));
|
|
}
|
|
}
|
|
|
|
const ver = objetivo.closest("[data-ver-contrasena]");
|
|
if (ver) {
|
|
const campo = ver.parentElement.querySelector("input");
|
|
const mostrar = campo.type === "password";
|
|
campo.type = mostrar ? "text" : "password";
|
|
ver.textContent = mostrar ? "Ocultar" : "Ver";
|
|
ver.setAttribute("aria-pressed", String(mostrar));
|
|
ver.setAttribute("aria-label", mostrar ? "Ocultar contraseña" : "Mostrar contraseña");
|
|
}
|
|
|
|
if (objetivo.closest("[data-cajon-cerrar]")) {
|
|
objetivo.closest("dialog").close();
|
|
return;
|
|
}
|
|
if (objetivo.matches("dialog.cajon")) {
|
|
objetivo.close(); // clic en el fondo, fuera del panel
|
|
return;
|
|
}
|
|
|
|
const disparador = disparadorDeCajon(evento);
|
|
if (disparador) {
|
|
if (pld.abrirCajon(disparador.dataset.cajon, disparador.dataset.plantilla, disparador)) {
|
|
evento.preventDefault();
|
|
}
|
|
return;
|
|
}
|
|
|
|
const destino = destinoDeFila(evento);
|
|
if (destino) {
|
|
if (evento.ctrlKey || evento.metaKey || evento.shiftKey) window.open(destino, "_blank", "noopener");
|
|
else window.location.href = destino;
|
|
}
|
|
});
|
|
|
|
// Clic central sobre una fila: otra pestaña, como en un enlace.
|
|
document.addEventListener("auxclick", (evento) => {
|
|
if (evento.button !== 1) return;
|
|
const destino = destinoDeFila(evento);
|
|
if (destino) {
|
|
evento.preventDefault();
|
|
window.open(destino, "_blank", "noopener");
|
|
}
|
|
});
|
|
|
|
document.addEventListener("keydown", (evento) => {
|
|
const disparador = evento.target.closest && evento.target.closest("[data-cajon]");
|
|
if (disparador && evento.target === disparador && (evento.key === "Enter" || evento.key === " ")) {
|
|
evento.preventDefault();
|
|
pld.abrirCajon(disparador.dataset.cajon, disparador.dataset.plantilla, disparador);
|
|
return;
|
|
}
|
|
if (evento.key === "Escape") {
|
|
const lateral = $(".lateral.es-visible");
|
|
if (lateral) {
|
|
lateral.classList.remove("es-visible");
|
|
const boton = $(`[data-alternar="#${lateral.id}"]`);
|
|
if (boton) {
|
|
boton.setAttribute("aria-expanded", "false");
|
|
boton.focus();
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
// --- Cambios: filtros, archivos, descripción de la regla ----------------------------------------
|
|
|
|
const pintarDescripcion = (opcion) => {
|
|
const grupo = opcion.closest("fieldset") || opcion.form;
|
|
const destino = grupo && $("[data-descripcion-regla]", grupo);
|
|
if (destino) {
|
|
destino.textContent = opcion.dataset.descripcion;
|
|
destino.hidden = !opcion.dataset.descripcion;
|
|
}
|
|
};
|
|
|
|
document.addEventListener("change", (evento) => {
|
|
const objetivo = evento.target;
|
|
const filtros = objetivo.closest("form[data-autoenvio]");
|
|
if (
|
|
filtros &&
|
|
objetivo.matches("select, input[type=checkbox], input[type=radio], input[type=date], input[type=number]")
|
|
) {
|
|
filtros.requestSubmit();
|
|
return;
|
|
}
|
|
if (objetivo.matches("[data-zona-archivo] input[type=file]")) {
|
|
const nombre = $("[data-zona-nombre]", objetivo.closest("[data-zona-archivo]"));
|
|
if (nombre && objetivo.files[0]) nombre.textContent = objetivo.files[0].name;
|
|
}
|
|
if (objetivo.matches("input[data-descripcion]")) pintarDescripcion(objetivo);
|
|
pld.evaluar();
|
|
});
|
|
|
|
["dragenter", "dragover"].forEach((tipo) =>
|
|
document.addEventListener(tipo, (evento) => {
|
|
const zona = evento.target.closest && evento.target.closest("[data-zona-archivo]");
|
|
if (zona) zona.classList.add("es-arrastrando");
|
|
}),
|
|
);
|
|
["dragleave", "drop"].forEach((tipo) =>
|
|
document.addEventListener(tipo, (evento) => {
|
|
const zona = evento.target.closest && evento.target.closest("[data-zona-archivo]");
|
|
if (zona) zona.classList.remove("es-arrastrando");
|
|
}),
|
|
);
|
|
|
|
// --- Impresión ---------------------------------------------------------------------------------
|
|
// Lo que se entrega impreso o en PDF (la evidencia) no puede salir con secciones plegadas.
|
|
|
|
const abiertasParaImprimir = [];
|
|
window.addEventListener("beforeprint", () => {
|
|
$$("details[data-abrir-al-imprimir]:not([open])").forEach((detalle) => {
|
|
detalle.open = true;
|
|
abiertasParaImprimir.push(detalle);
|
|
});
|
|
});
|
|
window.addEventListener("afterprint", () => {
|
|
abiertasParaImprimir.splice(0).forEach((detalle) => {
|
|
detalle.open = false;
|
|
});
|
|
});
|
|
|
|
// --- Al cargar ---------------------------------------------------------------------------------
|
|
|
|
document.addEventListener("DOMContentLoaded", () => {
|
|
document.querySelectorAll("[data-toast]").forEach((el) => {
|
|
pld.toast(el.dataset.toast, el.dataset.tono || "info");
|
|
});
|
|
$$("input[data-descripcion]:checked").forEach(pintarDescripcion);
|
|
pld.evaluar();
|
|
});
|
|
})();
|