feat(ui): utilidades transversales del rediseño en app.js
Conserva data-confirmar, data-alternar y data-toast/data-tono, y suma lo genérico de la referencia: data-requiere (botón habilitado cuando lo requerido está), data-contador, data-pista-de, data-distintos, data-ver-contrasena, data-autoenvio en filtros, zona de archivo, descripción de la regla elegida, cajón lateral (<dialog> con un <template>) y Esc para cerrar la barra lateral. Filas enlace: tr.fila-enlace navega al primer enlace de la fila (sin data-href, para no alterar las cuentas de href que hacen los tests). No intercepta clics en enlaces, botones o campos, ni cuando hay texto seleccionado; Ctrl/Cmd/Mayús o el clic central la abren en otra pestaña. Una fila con data-cajon abre el cajón (también con Enter o espacio).
This commit is contained in:
1 parent
b216a4e6e0
commit
0583983fde
1 file changed
+236
-8
+236
-8
@@ -1,17 +1,36 @@
|
||||
// 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`). Chart.js NO se carga aquí: lo trae el laboratorio.
|
||||
// (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)
|
||||
// <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]
|
||||
|
||||
(() => {
|
||||
"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");
|
||||
@@ -19,7 +38,10 @@
|
||||
const toast = document.createElement("div");
|
||||
toast.className = `toast toast--${tono}`;
|
||||
toast.setAttribute("role", tono === "peligro" ? "alert" : "status");
|
||||
toast.textContent = mensaje;
|
||||
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);
|
||||
};
|
||||
@@ -32,25 +54,231 @@
|
||||
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 enlace = evento.target.closest("a[data-confirmar]");
|
||||
const objetivo = evento.target;
|
||||
|
||||
const enlace = objetivo.closest("a[data-confirmar]");
|
||||
if (enlace && !pld.confirmar(enlace.dataset.confirmar)) {
|
||||
evento.preventDefault();
|
||||
return;
|
||||
}
|
||||
const alternador = evento.target.closest("[data-alternar]");
|
||||
|
||||
const alternador = objetivo.closest("[data-alternar]");
|
||||
if (alternador) {
|
||||
const objetivo = document.querySelector(alternador.dataset.alternar);
|
||||
if (objetivo) {
|
||||
const visible = objetivo.classList.toggle("es-visible");
|
||||
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");
|
||||
}),
|
||||
);
|
||||
|
||||
// --- 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();
|
||||
});
|
||||
})();
|
||||
Reference in new issue
Block a user