@forgenex/cli 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GUIA-IA.md +84 -5
- package/README.md +20 -0
- package/REFERENCIA.md +196 -0
- package/dist/forgenex.js +23 -18
- package/dist/locales/ca.js +1 -1
- package/dist/locales/en.js +1 -1
- package/dist/locales/es.js +1 -1
- package/ejemplos/escuela-natacion/README.md +26 -0
- package/ejemplos/escuela-natacion/extension.json +83 -0
- package/ejemplos/escuela-natacion/funciones/opciones.js +3 -0
- package/ejemplos/escuela-natacion/interfaz/agenda.html +5 -0
- package/ejemplos/escuela-natacion/interfaz/alta.html +2 -0
- package/ejemplos/escuela-natacion/interfaz/alta.js +31 -0
- package/ejemplos/escuela-natacion/interfaz/horario.js +64 -0
- package/ejemplos/escuela-natacion/interfaz/inscripcion.html +4 -0
- package/ejemplos/escuela-natacion/interfaz/inscripcion.js +29 -0
- package/ejemplos/escuela-natacion/interfaz/panel.html +7 -0
- package/ejemplos/escuela-natacion/interfaz/panel.js +103 -0
- package/ejemplos/escuela-natacion/interfaz/piscina.html +5 -0
- package/ejemplos/escuela-natacion/solucion.json +399 -0
- package/ejemplos/kit-visual/extension.json +13 -0
- package/ejemplos/kit-visual/interfaz/galeria.js +71 -0
- package/ejemplos/kit-visual/interfaz/index.html +9 -0
- package/kit/pantalla.mjs +980 -0
- package/licencias.txt +1 -1
- package/package.json +2 -1
package/kit/pantalla.mjs
ADDED
|
@@ -0,0 +1,980 @@
|
|
|
1
|
+
const h = (tag, texto, clase) => {
|
|
2
|
+
const nodo = document.createElement(tag);
|
|
3
|
+
if (texto != null) nodo.textContent = String(texto);
|
|
4
|
+
if (clase) nodo.className = clase;
|
|
5
|
+
return nodo;
|
|
6
|
+
};
|
|
7
|
+
const boton = (texto, pulsar) => {
|
|
8
|
+
const b = h("button", texto, "fx-boton fx-boton-suave");
|
|
9
|
+
b.type = "button";
|
|
10
|
+
b.onclick = pulsar;
|
|
11
|
+
return b;
|
|
12
|
+
};
|
|
13
|
+
const estado = () => {
|
|
14
|
+
const p = h("p");
|
|
15
|
+
p.setAttribute("role", "status");
|
|
16
|
+
return p;
|
|
17
|
+
};
|
|
18
|
+
function montar(raiz, ...nodos) {
|
|
19
|
+
const caja = h("section", null, "fx-tarjeta");
|
|
20
|
+
caja.append(...nodos);
|
|
21
|
+
raiz.append(caja);
|
|
22
|
+
return () => caja.remove();
|
|
23
|
+
}
|
|
24
|
+
function elegir(nombre, opciones) {
|
|
25
|
+
const select = h("select", null, "fx-campo");
|
|
26
|
+
select.setAttribute("aria-label", nombre);
|
|
27
|
+
for (const { valor, etiqueta } of opciones) {
|
|
28
|
+
const option = h("option", etiqueta);
|
|
29
|
+
option.value = valor;
|
|
30
|
+
select.append(option);
|
|
31
|
+
}
|
|
32
|
+
return select;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function listar(crm, modulo, consulta = {}) {
|
|
36
|
+
const { data, meta } = await crm.pedir(`mod_${modulo}.listar`, consulta);
|
|
37
|
+
return { filas: data.resultados, siguiente: meta?.siguiente ?? data.siguiente ?? data.cursor ?? null };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let siguienteGrupo = 0;
|
|
41
|
+
export function tabla(raiz, { crm, modulo, columnas, filtros = [], limite = 25, alSeleccionar, seleccionUnica = false }) {
|
|
42
|
+
const controles = h("div", null, "fx-fila");
|
|
43
|
+
const buscar = h("input", null, "fx-campo");
|
|
44
|
+
buscar.type = "search";
|
|
45
|
+
buscar.setAttribute("aria-label", "Buscar registros");
|
|
46
|
+
buscar.placeholder = "Buscar registros";
|
|
47
|
+
const aplicar = boton("Buscar", () => void reiniciar());
|
|
48
|
+
buscar.onkeydown = (e) => { if (e.key === "Enter") void reiniciar(); };
|
|
49
|
+
controles.append(buscar, aplicar);
|
|
50
|
+
const selectores = filtros.map(({ campo, etiqueta, opciones }) => {
|
|
51
|
+
const select = elegir(etiqueta, [{ valor: "", etiqueta }, ...opciones]);
|
|
52
|
+
controles.append(select);
|
|
53
|
+
select.onchange = () => void reiniciar();
|
|
54
|
+
return [campo, select];
|
|
55
|
+
});
|
|
56
|
+
const nota = estado();
|
|
57
|
+
const scroll = h("div");
|
|
58
|
+
scroll.style.overflowX = "auto";
|
|
59
|
+
const lista = h("table", null, "fx-tabla");
|
|
60
|
+
scroll.append(lista);
|
|
61
|
+
const cabecera = lista.createTHead().insertRow();
|
|
62
|
+
const cuerpo = lista.createTBody();
|
|
63
|
+
const pie = h("div", null, "fx-fila");
|
|
64
|
+
let orden, sentido = "asc", pagina = 0, cursores = [null], siguiente, solicitud = 0;
|
|
65
|
+
const seleccion = new Map();
|
|
66
|
+
const grupo = seleccionUnica ? `fx-seleccion-${++siguienteGrupo}` : "";
|
|
67
|
+
const columnasBotones = new Map();
|
|
68
|
+
if (alSeleccionar) cabecera.append(h("th", "Selección"));
|
|
69
|
+
for (const { campo, etiqueta, ordenable } of columnas) {
|
|
70
|
+
const th = h("th");
|
|
71
|
+
th.scope = "col";
|
|
72
|
+
if (ordenable) {
|
|
73
|
+
const b = boton(etiqueta, () => {
|
|
74
|
+
sentido = orden === campo && sentido === "asc" ? "desc" : "asc";
|
|
75
|
+
orden = campo;
|
|
76
|
+
for (const [clave, celda] of columnasBotones) {
|
|
77
|
+
if (clave === campo) celda.setAttribute("aria-sort", sentido === "asc" ? "ascending" : "descending");
|
|
78
|
+
else celda.removeAttribute("aria-sort");
|
|
79
|
+
}
|
|
80
|
+
void reiniciar();
|
|
81
|
+
});
|
|
82
|
+
th.append(b);
|
|
83
|
+
columnasBotones.set(campo, th);
|
|
84
|
+
} else th.textContent = etiqueta;
|
|
85
|
+
cabecera.append(th);
|
|
86
|
+
}
|
|
87
|
+
const atras = boton("Anterior", () => { pagina--; void cargar(); });
|
|
88
|
+
const adelante = boton("Siguiente", () => {
|
|
89
|
+
cursores[++pagina] = siguiente;
|
|
90
|
+
void cargar();
|
|
91
|
+
});
|
|
92
|
+
pie.append(atras, adelante);
|
|
93
|
+
const quitar = montar(raiz, controles, nota, scroll, pie);
|
|
94
|
+
function reiniciar() {
|
|
95
|
+
pagina = 0;
|
|
96
|
+
cursores = [null];
|
|
97
|
+
return cargar();
|
|
98
|
+
}
|
|
99
|
+
async function cargar() {
|
|
100
|
+
const turno = ++solicitud;
|
|
101
|
+
nota.textContent = "Cargando…";
|
|
102
|
+
atras.disabled = adelante.disabled = true;
|
|
103
|
+
const filtro = Object.fromEntries(selectores.filter(([, s]) => s.value).map(([campo, s]) => [`${campo}@eq`, s.value]));
|
|
104
|
+
try {
|
|
105
|
+
const r = await listar(crm, modulo, {
|
|
106
|
+
limite, ...(buscar.value.trim() && { q: buscar.value.trim() }),
|
|
107
|
+
...(orden && { orden, sentido }),
|
|
108
|
+
...(Object.keys(filtro).length && { filtro: JSON.stringify(filtro) }),
|
|
109
|
+
...(cursores[pagina] && { cursor: cursores[pagina] }),
|
|
110
|
+
});
|
|
111
|
+
if (turno !== solicitud) return;
|
|
112
|
+
cuerpo.replaceChildren();
|
|
113
|
+
for (const fila of r.filas) {
|
|
114
|
+
const tr = cuerpo.insertRow();
|
|
115
|
+
if (alSeleccionar) {
|
|
116
|
+
const control = h("input");
|
|
117
|
+
control.type = seleccionUnica ? "radio" : "checkbox";
|
|
118
|
+
if (seleccionUnica) control.name = grupo;
|
|
119
|
+
control.setAttribute("aria-label", `Seleccionar registro ${fila.id}`);
|
|
120
|
+
control.checked = seleccion.has(fila.id);
|
|
121
|
+
control.onchange = () => {
|
|
122
|
+
if (seleccionUnica) seleccion.clear();
|
|
123
|
+
if (control.checked) seleccion.set(fila.id, fila);
|
|
124
|
+
else seleccion.delete(fila.id);
|
|
125
|
+
alSeleccionar([...seleccion.values()]);
|
|
126
|
+
};
|
|
127
|
+
tr.insertCell().append(control);
|
|
128
|
+
}
|
|
129
|
+
for (const { campo, mostrar } of columnas) {
|
|
130
|
+
tr.insertCell().textContent = String((mostrar ? mostrar(fila) : fila[campo] ?? fila.campos?.[campo]) ?? "");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
siguiente = r.siguiente;
|
|
134
|
+
adelante.disabled = !siguiente;
|
|
135
|
+
nota.textContent = r.filas.length ? `Página ${pagina + 1}` : "Sin registros";
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (turno !== solicitud) return;
|
|
138
|
+
cuerpo.replaceChildren();
|
|
139
|
+
nota.textContent = error.detalle || "No se han podido cargar los registros.";
|
|
140
|
+
} finally {
|
|
141
|
+
if (turno === solicitud) atras.disabled = pagina === 0;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
void cargar();
|
|
145
|
+
return { actualizar: cargar, destruir() { solicitud++; quitar(); } };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function selectorRegistros(raiz, { crm, modulo, titulo = "Elegir registro", etiqueta, alElegir }) {
|
|
149
|
+
const lista = h("div");
|
|
150
|
+
const leyenda = h("h2", titulo);
|
|
151
|
+
const aceptar = boton("Elegir", () => { if (fila) alElegir(fila); });
|
|
152
|
+
const quitar = montar(raiz, leyenda, lista, aceptar);
|
|
153
|
+
let fila;
|
|
154
|
+
aceptar.disabled = true;
|
|
155
|
+
const t = tabla(lista, { crm, modulo, seleccionUnica: true, columnas: [{ campo: "etiqueta", etiqueta: "Registro", mostrar: etiqueta }],
|
|
156
|
+
alSeleccionar(filas) {
|
|
157
|
+
fila = filas.at(-1);
|
|
158
|
+
aceptar.disabled = !fila;
|
|
159
|
+
} });
|
|
160
|
+
return { actualizar: t.actualizar, destruir() { t.destruir(); quitar(); } };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function cuadrante(raiz, { dias, recursos, bloques, alCambiar }) {
|
|
164
|
+
const envoltorio = h("div");
|
|
165
|
+
envoltorio.style.overflowX = "auto";
|
|
166
|
+
const rejilla = h("table", null, "fx-tabla");
|
|
167
|
+
envoltorio.append(rejilla);
|
|
168
|
+
const nota = estado();
|
|
169
|
+
let compacto = raiz.clientWidth < 600;
|
|
170
|
+
const diaVisible = elegir("Día del cuadrante", dias.map(({ id, etiqueta }) => ({ valor: id, etiqueta })));
|
|
171
|
+
diaVisible.value = dias.find((d) => bloques.some((b) => b.dia === d.id))?.id ?? dias[0]?.id ?? "";
|
|
172
|
+
diaVisible.hidden = !compacto;
|
|
173
|
+
diaVisible.onchange = () => pintar();
|
|
174
|
+
const quitar = montar(raiz, diaVisible, envoltorio, nota);
|
|
175
|
+
let arrastre, ocupado = false;
|
|
176
|
+
let editor = null;
|
|
177
|
+
const tono = (nodo, bloque) => {
|
|
178
|
+
const color = bloque.color;
|
|
179
|
+
if (typeof color === "string" && /^#[0-9a-f]{6}$/i.test(color)) nodo.style.borderInlineStart = `0.35rem solid ${color}`;
|
|
180
|
+
};
|
|
181
|
+
const etiqueta = ({ titulo, estado }) => estado ? `${titulo} · ${estado}` : titulo;
|
|
182
|
+
async function cambiar(bloque, cambio) {
|
|
183
|
+
if (ocupado) return;
|
|
184
|
+
ocupado = true;
|
|
185
|
+
try {
|
|
186
|
+
await alCambiar({ ...bloque, ...cambio });
|
|
187
|
+
bloques = bloques.map((b) => b.id === bloque.id ? { ...b, ...cambio } : b);
|
|
188
|
+
editor = null;
|
|
189
|
+
if (compacto && cambio.dia) diaVisible.value = cambio.dia;
|
|
190
|
+
pintar();
|
|
191
|
+
envoltorio.querySelectorAll("button[data-bloque]").forEach((b) => { if (b.dataset.bloque === String(bloque.id)) b.focus({ preventScroll: true }); });
|
|
192
|
+
nota.textContent = "Cambio guardado.";
|
|
193
|
+
} catch (error) {
|
|
194
|
+
nota.textContent = error.detalle || error.message || "No se ha podido guardar.";
|
|
195
|
+
} finally { ocupado = false; }
|
|
196
|
+
}
|
|
197
|
+
function editar(celda, bloque) {
|
|
198
|
+
editor?.remove();
|
|
199
|
+
const form = h("div", null, "fx-fila");
|
|
200
|
+
editor = form;
|
|
201
|
+
const dia = elegir("Día", dias.map(({ id, etiqueta }) => ({ valor: id, etiqueta })));
|
|
202
|
+
const recurso = elegir("Recurso", recursos.map(({ id, etiqueta }) => ({ valor: id, etiqueta })));
|
|
203
|
+
dia.value = bloque.dia;
|
|
204
|
+
recurso.value = bloque.recurso;
|
|
205
|
+
const duracion = h("input", null, "fx-campo");
|
|
206
|
+
duracion.type = "number";
|
|
207
|
+
duracion.min = "1";
|
|
208
|
+
duracion.max = "1440";
|
|
209
|
+
duracion.required = true;
|
|
210
|
+
duracion.value = bloque.duracion;
|
|
211
|
+
duracion.setAttribute("aria-label", "Duración en minutos");
|
|
212
|
+
const tamano = h("input", null, "fx-campo");
|
|
213
|
+
tamano.type = "range";
|
|
214
|
+
tamano.min = duracion.min;
|
|
215
|
+
tamano.max = duracion.max;
|
|
216
|
+
tamano.value = duracion.value;
|
|
217
|
+
tamano.setAttribute("aria-label", "Redimensionar duración");
|
|
218
|
+
tamano.oninput = () => { duracion.value = tamano.value; };
|
|
219
|
+
duracion.oninput = () => { if (duracion.validity.valid) tamano.value = duracion.value; };
|
|
220
|
+
const guardar = boton("Guardar", () => {
|
|
221
|
+
if (!duracion.reportValidity()) return;
|
|
222
|
+
void cambiar(bloque, { dia: dia.value, recurso: recurso.value, duracion: Number(duracion.value) });
|
|
223
|
+
});
|
|
224
|
+
form.append(dia, recurso, duracion, tamano, guardar, boton("Cancelar", () => {
|
|
225
|
+
form.remove();
|
|
226
|
+
editor = null;
|
|
227
|
+
celda.querySelector("button").focus();
|
|
228
|
+
}));
|
|
229
|
+
celda.append(form);
|
|
230
|
+
dia.focus();
|
|
231
|
+
}
|
|
232
|
+
function pintar() {
|
|
233
|
+
rejilla.replaceChildren();
|
|
234
|
+
editor = null;
|
|
235
|
+
const visibles = compacto ? dias.filter((d) => String(d.id) === diaVisible.value) : dias;
|
|
236
|
+
const head = rejilla.createTHead().insertRow();
|
|
237
|
+
head.append(h("th", "Recurso"));
|
|
238
|
+
for (const dia of visibles) {
|
|
239
|
+
const th = h("th", dia.etiqueta);
|
|
240
|
+
th.scope = "col";
|
|
241
|
+
head.append(th);
|
|
242
|
+
}
|
|
243
|
+
const body = rejilla.createTBody();
|
|
244
|
+
for (const recurso of recursos) {
|
|
245
|
+
const fila = body.insertRow();
|
|
246
|
+
const th = h("th", recurso.etiqueta);
|
|
247
|
+
th.scope = "row";
|
|
248
|
+
fila.append(th);
|
|
249
|
+
for (const dia of visibles) {
|
|
250
|
+
const celda = fila.insertCell();
|
|
251
|
+
celda.style.minWidth = "9rem";
|
|
252
|
+
celda.style.verticalAlign = "top";
|
|
253
|
+
celda.ondragover = (e) => { if (arrastre) e.preventDefault(); };
|
|
254
|
+
celda.ondrop = (e) => {
|
|
255
|
+
e.preventDefault();
|
|
256
|
+
if (arrastre) void cambiar(arrastre, { dia: dia.id, recurso: recurso.id });
|
|
257
|
+
arrastre = null;
|
|
258
|
+
};
|
|
259
|
+
for (const bloque of bloques.filter((b) => b.dia === dia.id && b.recurso === recurso.id)) {
|
|
260
|
+
const tarjeta = h("div", null, "fx-aviso");
|
|
261
|
+
tono(tarjeta, bloque);
|
|
262
|
+
tarjeta.draggable = true;
|
|
263
|
+
tarjeta.ondragstart = (e) => {
|
|
264
|
+
arrastre = bloque;
|
|
265
|
+
e.dataTransfer.setData("text/plain", String(bloque.id));
|
|
266
|
+
e.dataTransfer.effectAllowed = "move";
|
|
267
|
+
};
|
|
268
|
+
tarjeta.ondragend = () => { arrastre = null; };
|
|
269
|
+
if (bloque.hora) tarjeta.append(h("p", `${bloque.hora} · ${bloque.duracion} min`));
|
|
270
|
+
tarjeta.append(h("p", etiqueta(bloque)));
|
|
271
|
+
const mover = boton("Mover", () => editar(tarjeta, bloque));
|
|
272
|
+
mover.dataset.bloque = bloque.id;
|
|
273
|
+
mover.setAttribute("aria-label", `Mover ${bloque.titulo}`);
|
|
274
|
+
tarjeta.append(mover);
|
|
275
|
+
celda.append(tarjeta);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
pintar();
|
|
281
|
+
const redimension = new ResizeObserver(([entrada]) => {
|
|
282
|
+
const estrecho = entrada.contentRect.width < 600;
|
|
283
|
+
if (estrecho === compacto) return;
|
|
284
|
+
compacto = estrecho;
|
|
285
|
+
diaVisible.hidden = !compacto;
|
|
286
|
+
pintar();
|
|
287
|
+
});
|
|
288
|
+
redimension.observe(raiz);
|
|
289
|
+
return { destruir() { redimension.disconnect(); quitar(); } };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const fechaIso = (d) => [d.getFullYear(), String(d.getMonth() + 1).padStart(2, "0"), String(d.getDate()).padStart(2, "0")].join("-");
|
|
293
|
+
export function calendario(raiz, { eventos, fecha = fechaIso(new Date()), modo = "semana", locale = "es" }) {
|
|
294
|
+
let actual = new Date(`${fecha}T12:00:00`);
|
|
295
|
+
const controles = h("div", null, "fx-fila"), nota = estado();
|
|
296
|
+
const scroll = h("div");
|
|
297
|
+
scroll.style.overflowX = "auto";
|
|
298
|
+
const lista = h("table", null, "fx-tabla");
|
|
299
|
+
// Reparto automático y un mínimo por día: en pantallas estrechas se desplaza en
|
|
300
|
+
// horizontal y cada columna crece lo que pida su palabra más larga (no se parte).
|
|
301
|
+
lista.style.minWidth = "49rem";
|
|
302
|
+
scroll.append(lista);
|
|
303
|
+
const tipo = elegir("Vista", [{ valor: "semana", etiqueta: "Semana" }, { valor: "mes", etiqueta: "Mes" }]);
|
|
304
|
+
tipo.value = modo;
|
|
305
|
+
tipo.style.width = "auto";
|
|
306
|
+
tipo.onchange = pintar;
|
|
307
|
+
function navegar(n) {
|
|
308
|
+
if (tipo.value === "mes") actual = new Date(actual.getFullYear(), actual.getMonth() + n, 1, 12);
|
|
309
|
+
else actual.setDate(actual.getDate() + 7 * n);
|
|
310
|
+
pintar();
|
|
311
|
+
}
|
|
312
|
+
controles.append(boton("Anterior", () => navegar(-1)), tipo, boton("Siguiente", () => navegar(1)));
|
|
313
|
+
const quitar = montar(raiz, controles, nota, scroll);
|
|
314
|
+
function pintar() {
|
|
315
|
+
const inicio = new Date(actual);
|
|
316
|
+
const mes = tipo.value === "mes";
|
|
317
|
+
if (mes) inicio.setDate(1);
|
|
318
|
+
else inicio.setDate(inicio.getDate() - (inicio.getDay() + 6) % 7);
|
|
319
|
+
const cantidad = mes ? new Date(inicio.getFullYear(), inicio.getMonth() + 1, 0).getDate() : 7;
|
|
320
|
+
const formato = new Intl.DateTimeFormat(locale, { weekday: "short", day: "numeric", month: "short" });
|
|
321
|
+
nota.textContent = mes ? new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(inicio) : formato.format(inicio);
|
|
322
|
+
lista.replaceChildren();
|
|
323
|
+
const primerDia = (inicio.getDay() + 6) % 7;
|
|
324
|
+
const cabecera = lista.createTHead().insertRow();
|
|
325
|
+
const formatoSemana = new Intl.DateTimeFormat(locale, { weekday: "short" });
|
|
326
|
+
for (let i = 0; i < 7; i++) {
|
|
327
|
+
const lunes = new Date(2026, 0, 5 + i, 12);
|
|
328
|
+
const th = h("th", formatoSemana.format(lunes));
|
|
329
|
+
th.scope = "col";
|
|
330
|
+
cabecera.append(th);
|
|
331
|
+
}
|
|
332
|
+
const cuerpo = lista.createTBody();
|
|
333
|
+
for (let fila = 0; fila < Math.ceil((cantidad + primerDia) / 7); fila++) {
|
|
334
|
+
const tr = cuerpo.insertRow();
|
|
335
|
+
for (let col = 0; col < 7; col++) {
|
|
336
|
+
const i = fila * 7 + col - primerDia;
|
|
337
|
+
const td = tr.insertCell();
|
|
338
|
+
td.style.verticalAlign = "top";
|
|
339
|
+
td.style.padding = "0.375rem 0.25rem";
|
|
340
|
+
td.style.minWidth = "6.5rem";
|
|
341
|
+
if (i < 0 || i >= cantidad) continue;
|
|
342
|
+
const dia = new Date(inicio);
|
|
343
|
+
dia.setDate(dia.getDate() + i);
|
|
344
|
+
td.append(h("strong", formato.format(dia)));
|
|
345
|
+
if (fechaIso(dia) === fechaIso(new Date())) {
|
|
346
|
+
td.setAttribute("aria-current", "date");
|
|
347
|
+
td.style.boxShadow = "inset 0 2px 0 var(--primary)";
|
|
348
|
+
}
|
|
349
|
+
for (const e of eventos.filter((e) => e.fecha === fechaIso(dia))) {
|
|
350
|
+
const aviso = h("p", [e.hora, e.titulo].filter(Boolean).join(" · "), "fx-aviso");
|
|
351
|
+
aviso.style.padding = "0.5rem";
|
|
352
|
+
td.append(aviso);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
requestAnimationFrame(() => {
|
|
357
|
+
const hoy = lista.querySelector("[aria-current=date]");
|
|
358
|
+
scroll.scrollLeft = hoy ? hoy.getBoundingClientRect().left - lista.getBoundingClientRect().left : 0;
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
pintar();
|
|
362
|
+
return { destruir: quitar };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
export const interfaz = (crm) => ({
|
|
366
|
+
dialogo: (titulo, texto) => crm.pedir("interfaz.dialogo", { titulo, texto }, { espera: 600000 }),
|
|
367
|
+
confirmar: (titulo, texto) => crm.pedir("interfaz.preguntar", { titulo, texto }, { espera: 600000 }),
|
|
368
|
+
aviso: (texto) => crm.pedir("interfaz.aviso", { texto }),
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
export function kitReact({ createElement, useLayoutEffect, useRef }) {
|
|
372
|
+
const componente = (monta) => function Pieza(props) {
|
|
373
|
+
const ref = useRef(null);
|
|
374
|
+
useLayoutEffect(() => {
|
|
375
|
+
const pieza = monta(ref.current, props);
|
|
376
|
+
return () => pieza.destruir();
|
|
377
|
+
}, [props]);
|
|
378
|
+
return createElement("div", { ref });
|
|
379
|
+
};
|
|
380
|
+
return { Tabla: componente(tabla), SelectorRegistros: componente(selectorRegistros),
|
|
381
|
+
Cuadrante: componente(cuadrante), Calendario: componente(calendario),
|
|
382
|
+
Grafico: componente(grafico), Indicador: componente(indicador), Kanban: componente(kanban),
|
|
383
|
+
LineaTiempo: componente(lineaTiempo), Mapa: componente(mapa), Progreso: componente(progreso),
|
|
384
|
+
Chispa: componente(chispa), Asistente: componente(asistente) };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const svg = (tag, atributos = {}) => {
|
|
388
|
+
const nodo = document.createElementNS("http://www.w3.org/2000/svg", tag);
|
|
389
|
+
for (const [clave, valor] of Object.entries(atributos)) nodo.setAttribute(clave, valor);
|
|
390
|
+
return nodo;
|
|
391
|
+
};
|
|
392
|
+
const tonos = ["var(--chispa-1)", "var(--chispa-2)", "var(--chispa-3)"];
|
|
393
|
+
const tono = (i) => tonos[i % tonos.length];
|
|
394
|
+
const formatear = (valor) => Number(valor).toLocaleString(document.documentElement.lang || "es");
|
|
395
|
+
const caja = (titulo) => {
|
|
396
|
+
const nodo = h("section", null, "fx-tarjeta");
|
|
397
|
+
nodo.append(h("h2", titulo));
|
|
398
|
+
return nodo;
|
|
399
|
+
};
|
|
400
|
+
function insertar(raiz, nodo) {
|
|
401
|
+
raiz.append(nodo);
|
|
402
|
+
return { destruir: () => nodo.remove() };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export function indicador(raiz, { titulo, valor, tendencia }) {
|
|
406
|
+
const tarjeta = caja(titulo);
|
|
407
|
+
tarjeta.append(h("p", valor, "fx-cifra"));
|
|
408
|
+
if (tendencia) tarjeta.append(h("p", tendencia, "fx-chapa"));
|
|
409
|
+
return insertar(raiz, tarjeta);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// SVG nativo para compartir la misma pieza sin cargar React en las apps vanilla.
|
|
413
|
+
export function grafico(raiz, { titulo, tipo = "barras", datos, unidad = "" }) {
|
|
414
|
+
const tarjeta = caja(titulo);
|
|
415
|
+
const puntos = datos.filter(({ valor }) => Number.isFinite(valor));
|
|
416
|
+
if (!puntos.length) {
|
|
417
|
+
tarjeta.append(h("p", "Sin datos"));
|
|
418
|
+
return insertar(raiz, tarjeta);
|
|
419
|
+
}
|
|
420
|
+
const alto = tipo === "embudo" ? Math.max(148, puntos.length * 24) : 148;
|
|
421
|
+
const lienzo = svg("svg", { viewBox: `0 0 360 ${alto}`, "aria-hidden": "true" });
|
|
422
|
+
lienzo.classList.add("fx-grafico");
|
|
423
|
+
const leyenda = h("ul", null, "fx-leyenda");
|
|
424
|
+
const tooltip = estado();
|
|
425
|
+
tooltip.className = "fx-tooltip";
|
|
426
|
+
const max = Math.max(1, ...puntos.map(({ valor }) => valor));
|
|
427
|
+
const min = Math.min(0, ...puntos.map(({ valor }) => valor));
|
|
428
|
+
const y = (v) => 130 - (v - min) / (max - min) * 112;
|
|
429
|
+
const margenEje = 40;
|
|
430
|
+
const ancho = (344 - margenEje) / puntos.length;
|
|
431
|
+
const x = (i) => margenEje + ancho * (i + 0.5);
|
|
432
|
+
const circular = tipo === "anillo" || tipo === "tarta";
|
|
433
|
+
const conEje = !circular && tipo !== "embudo";
|
|
434
|
+
if (conEje) {
|
|
435
|
+
leyenda.className = "fx-eje-grafico";
|
|
436
|
+
leyenda.style.gridTemplateColumns = `${margenEje}fr repeat(${puntos.length}, minmax(0, ${ancho}fr)) 16fr`;
|
|
437
|
+
lienzo.classList.add("fx-grafico-con-eje");
|
|
438
|
+
}
|
|
439
|
+
const total = puntos.reduce((s, { valor }) => s + Math.max(0, valor), 0);
|
|
440
|
+
let acumulado = 0;
|
|
441
|
+
if (conEje) {
|
|
442
|
+
const escala = new Intl.NumberFormat(document.documentElement.lang || "es", {
|
|
443
|
+
notation: "compact", maximumFractionDigits: 2,
|
|
444
|
+
});
|
|
445
|
+
for (const valor of [min, (min + max) / 2, max]) {
|
|
446
|
+
const marcaY = y(valor);
|
|
447
|
+
const rotulo = svg("text", { x: margenEje - 5, y: marcaY, "text-anchor": "end", "dominant-baseline": "middle" });
|
|
448
|
+
rotulo.textContent = escala.format(valor) + (unidad === "%" ? "%" : "");
|
|
449
|
+
lienzo.append(svg("line", { x1: margenEje, x2: 344, y1: marcaY, y2: marcaY, stroke: "var(--border)" }), rotulo);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (tipo === "lineas" || tipo === "area") {
|
|
453
|
+
const posiciones = puntos.map(({ valor }, i) => `${x(i)},${y(valor)}`).join(" ");
|
|
454
|
+
if (tipo === "area") lienzo.append(svg("polygon", {
|
|
455
|
+
points: `${x(0)},${y(0)} ${posiciones} ${x(puntos.length - 1)},${y(0)}`,
|
|
456
|
+
fill: tono(0), "fill-opacity": 0.25,
|
|
457
|
+
}));
|
|
458
|
+
lienzo.append(svg("polyline", { points: posiciones, fill: "none", stroke: tono(0), "stroke-width": 2 }));
|
|
459
|
+
}
|
|
460
|
+
puntos.forEach(({ etiqueta, valor }, i) => {
|
|
461
|
+
const color = tipo === "lineas" || tipo === "area" ? tono(0) : tono(i);
|
|
462
|
+
let marca;
|
|
463
|
+
if (circular) {
|
|
464
|
+
const proporcion = total ? Math.max(0, valor) / total : 0;
|
|
465
|
+
const tarta = tipo === "tarta";
|
|
466
|
+
const angulo = (fraccion) => fraccion * 2 * Math.PI - Math.PI / 2;
|
|
467
|
+
const extremo = (fraccion, radio) =>
|
|
468
|
+
`${180 + Math.cos(angulo(fraccion)) * radio} ${74 + Math.sin(angulo(fraccion)) * radio}`;
|
|
469
|
+
if (tarta && proporcion >= 1) marca = svg("circle", { cx: 180, cy: 74, r: 60, fill: color });
|
|
470
|
+
else if (tarta) marca = svg("path", {
|
|
471
|
+
d: `M180 74 L${extremo(acumulado, 60)} A60 60 0 ${proporcion > 0.5 ? 1 : 0} 1 ${extremo(acumulado + proporcion, 60)} Z`,
|
|
472
|
+
fill: color,
|
|
473
|
+
});
|
|
474
|
+
else marca = svg("circle", {
|
|
475
|
+
cx: 180, cy: 74, r: 50, fill: "none", stroke: color, "stroke-width": 24, pathLength: 1,
|
|
476
|
+
"stroke-dasharray": `${proporcion} 1`, "stroke-dashoffset": -acumulado,
|
|
477
|
+
transform: "rotate(-90 180 74)",
|
|
478
|
+
});
|
|
479
|
+
acumulado += proporcion;
|
|
480
|
+
} else if (tipo === "embudo") {
|
|
481
|
+
const anchura = Math.max(0, valor) / max * 320;
|
|
482
|
+
marca = svg("rect", { x: (360 - anchura) / 2, y: i * 24 + 5, width: anchura, height: 18, rx: 4, fill: color });
|
|
483
|
+
} else if (tipo === "lineas" || tipo === "area") {
|
|
484
|
+
marca = svg("circle", { cx: x(i), cy: y(valor), r: 5, fill: color });
|
|
485
|
+
} else {
|
|
486
|
+
marca = svg("rect", {
|
|
487
|
+
x: x(i) - ancho * 0.32, y: Math.min(y(0), y(valor)), width: ancho * 0.64,
|
|
488
|
+
height: Math.max(1, Math.abs(y(0) - y(valor))), rx: 3, fill: color,
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
const texto = `${etiqueta} · ${formatear(valor)}${unidad ? ` ${unidad}` : ""}`;
|
|
492
|
+
const tituloMarca = svg("title");
|
|
493
|
+
tituloMarca.textContent = texto;
|
|
494
|
+
marca.append(tituloMarca);
|
|
495
|
+
lienzo.append(marca);
|
|
496
|
+
const mostrar = () => {
|
|
497
|
+
tooltip.textContent = texto;
|
|
498
|
+
for (const m of lienzo.querySelectorAll("[data-destacado]")) m.removeAttribute("data-destacado");
|
|
499
|
+
marca.setAttribute("data-destacado", "");
|
|
500
|
+
};
|
|
501
|
+
const item = h("li");
|
|
502
|
+
const entrada = boton(conEje ? etiqueta : texto, mostrar);
|
|
503
|
+
if (conEje) {
|
|
504
|
+
entrada.setAttribute("aria-label", texto);
|
|
505
|
+
entrada.title = texto;
|
|
506
|
+
}
|
|
507
|
+
entrada.style.setProperty("--fx-marca", color);
|
|
508
|
+
entrada.onfocus = mostrar;
|
|
509
|
+
marca.onpointerenter = mostrar;
|
|
510
|
+
entrada.onpointerenter = mostrar;
|
|
511
|
+
item.append(entrada);
|
|
512
|
+
leyenda.append(item);
|
|
513
|
+
});
|
|
514
|
+
tarjeta.append(lienzo, leyenda, tooltip);
|
|
515
|
+
return insertar(raiz, tarjeta);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export function kanban(raiz, { titulo, columnas, tarjetas, alCambiar }) {
|
|
519
|
+
const tablero = caja(titulo);
|
|
520
|
+
const rejilla = h("div", null, "fx-rejilla");
|
|
521
|
+
const nota = estado();
|
|
522
|
+
tablero.append(rejilla, nota);
|
|
523
|
+
const hueco = h("div", null, "fx-kanban-hueco");
|
|
524
|
+
hueco.setAttribute("aria-hidden", "true");
|
|
525
|
+
const mandos = new Map();
|
|
526
|
+
let arrastre, ocupado = false, destruido = false;
|
|
527
|
+
function terminarArrastre() {
|
|
528
|
+
hueco.remove();
|
|
529
|
+
arrastre?.ficha.removeAttribute("data-arrastrando");
|
|
530
|
+
arrastre = null;
|
|
531
|
+
}
|
|
532
|
+
async function mover(tarjeta, destino) {
|
|
533
|
+
if (ocupado || destino === tarjeta.estado) return;
|
|
534
|
+
ocupado = rejilla.inert = true;
|
|
535
|
+
nota.textContent = "";
|
|
536
|
+
const siguiente = { ...tarjeta, estado: destino };
|
|
537
|
+
try {
|
|
538
|
+
await alCambiar(siguiente);
|
|
539
|
+
if (destruido) return;
|
|
540
|
+
tarjetas = tarjetas.map((t) => t.id === tarjeta.id ? siguiente : t);
|
|
541
|
+
pintar();
|
|
542
|
+
nota.textContent = "Cambio guardado.";
|
|
543
|
+
} catch (error) {
|
|
544
|
+
nota.textContent = error?.detalle || error?.message || "No se ha podido guardar.";
|
|
545
|
+
} finally {
|
|
546
|
+
ocupado = rejilla.inert = false;
|
|
547
|
+
if (!destruido) mandos.get(tarjeta.id)?.focus({ preventScroll: true });
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
function acciones(tarjeta) {
|
|
551
|
+
const menu = h("div", null, "fx-kanban-menu");
|
|
552
|
+
menu.popover = "auto";
|
|
553
|
+
menu.setAttribute("role", "group");
|
|
554
|
+
menu.setAttribute("aria-label", "Mover a…");
|
|
555
|
+
menu.append(h("p", "Mover a…"));
|
|
556
|
+
for (const destino of columnas.filter(({ id }) => id !== tarjeta.estado)) {
|
|
557
|
+
menu.append(boton(destino.etiqueta, () => {
|
|
558
|
+
menu.hidePopover();
|
|
559
|
+
void mover(tarjeta, destino.id);
|
|
560
|
+
}));
|
|
561
|
+
}
|
|
562
|
+
const mando = boton("⋯", null);
|
|
563
|
+
mando.classList.add("fx-kanban-acciones");
|
|
564
|
+
mando.setAttribute("aria-label", `Acciones de ${tarjeta.titulo}`);
|
|
565
|
+
mando.popoverTargetElement = menu;
|
|
566
|
+
menu.addEventListener("toggle", () => {
|
|
567
|
+
if (!menu.matches(":popover-open")) return;
|
|
568
|
+
const rect = mando.getBoundingClientRect();
|
|
569
|
+
menu.style.left = `${Math.max(4, rect.right - menu.offsetWidth)}px`;
|
|
570
|
+
menu.style.top = `${rect.bottom + menu.offsetHeight + 4 <= window.innerHeight
|
|
571
|
+
? rect.bottom + 4 : Math.max(4, rect.top - menu.offsetHeight - 4)}px`;
|
|
572
|
+
menu.querySelector("button")?.focus();
|
|
573
|
+
});
|
|
574
|
+
mandos.set(tarjeta.id, mando);
|
|
575
|
+
return [mando, menu];
|
|
576
|
+
}
|
|
577
|
+
function pintar() {
|
|
578
|
+
rejilla.replaceChildren();
|
|
579
|
+
mandos.clear();
|
|
580
|
+
for (const [i, columna] of columnas.entries()) {
|
|
581
|
+
const grupo = h("section", null, "fx-kanban");
|
|
582
|
+
const color = columna.color;
|
|
583
|
+
grupo.style.setProperty("--fx-marca", /^#[0-9a-f]{6}$/i.test(color || "") ? color : tono(i));
|
|
584
|
+
const filas = tarjetas.filter(({ estado }) => estado === columna.id);
|
|
585
|
+
const cabecera = h("header", null, "fx-kanban-cabecera");
|
|
586
|
+
cabecera.append(h("h3", columna.etiqueta), h("span", filas.length, "fx-kanban-contador"));
|
|
587
|
+
const cuerpo = h("div", null, "fx-kanban-cuerpo");
|
|
588
|
+
grupo.append(cabecera, cuerpo);
|
|
589
|
+
grupo.dataset.columna = columna.id;
|
|
590
|
+
grupo.ondragover = (e) => {
|
|
591
|
+
if (!arrastre || arrastre.tarjeta.estado === columna.id) return;
|
|
592
|
+
e.preventDefault();
|
|
593
|
+
e.dataTransfer.dropEffect = "move";
|
|
594
|
+
if (hueco.parentElement !== cuerpo) cuerpo.append(hueco);
|
|
595
|
+
};
|
|
596
|
+
grupo.ondragleave = (e) => {
|
|
597
|
+
if (hueco.parentElement === cuerpo && !grupo.contains(e.relatedTarget)) hueco.remove();
|
|
598
|
+
};
|
|
599
|
+
grupo.ondrop = (e) => {
|
|
600
|
+
if (!arrastre) return;
|
|
601
|
+
e.preventDefault();
|
|
602
|
+
const { tarjeta } = arrastre;
|
|
603
|
+
terminarArrastre();
|
|
604
|
+
void mover(tarjeta, columna.id);
|
|
605
|
+
};
|
|
606
|
+
for (const tarjeta of filas) {
|
|
607
|
+
const ficha = h("article", null, "fx-tarjeta fx-kanban-ficha");
|
|
608
|
+
ficha.draggable = columnas.length > 1;
|
|
609
|
+
ficha.ondragstart = (e) => {
|
|
610
|
+
arrastre = { tarjeta, ficha };
|
|
611
|
+
ficha.setAttribute("data-arrastrando", "");
|
|
612
|
+
hueco.style.minHeight = `${ficha.offsetHeight}px`;
|
|
613
|
+
e.dataTransfer.effectAllowed = "move";
|
|
614
|
+
e.dataTransfer.setData("text/plain", String(tarjeta.id));
|
|
615
|
+
};
|
|
616
|
+
ficha.ondragend = terminarArrastre;
|
|
617
|
+
const texto = h("div");
|
|
618
|
+
texto.append(h("strong", tarjeta.titulo));
|
|
619
|
+
if (tarjeta.detalle) texto.append(h("p", tarjeta.detalle));
|
|
620
|
+
ficha.append(texto);
|
|
621
|
+
if (columnas.length > 1) ficha.append(...acciones(tarjeta));
|
|
622
|
+
cuerpo.append(ficha);
|
|
623
|
+
}
|
|
624
|
+
rejilla.append(grupo);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
pintar();
|
|
628
|
+
raiz.append(tablero);
|
|
629
|
+
return { destruir() { destruido = true; tablero.remove(); } };
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
export function lineaTiempo(raiz, { titulo, inicio, dias, tareas, alCambiar }) {
|
|
633
|
+
const tarjeta = caja(titulo);
|
|
634
|
+
const nota = estado();
|
|
635
|
+
const lista = h("div", null, "fx-cronograma");
|
|
636
|
+
tarjeta.append(lista, nota);
|
|
637
|
+
const fecha = (dia) => new Date(Date.parse(inicio + "T00:00:00Z") + dia * 86400000).toISOString().slice(0, 10);
|
|
638
|
+
let ocupado = false;
|
|
639
|
+
async function guardar(tarea, desde, duracion) {
|
|
640
|
+
if (ocupado || !Number.isInteger(desde) || !Number.isInteger(duracion) ||
|
|
641
|
+
desde < 0 || duracion < 1 || desde + duracion > dias) {
|
|
642
|
+
nota.textContent = "Elige fechas dentro del intervalo.";
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
const anterior = tareas.find((t) => t.id === tarea.dependeDe);
|
|
646
|
+
const siguientes = tareas.filter((t) => t.dependeDe === tarea.id);
|
|
647
|
+
if ((anterior && anterior.desde + anterior.duracion > desde) ||
|
|
648
|
+
siguientes.some((t) => desde + duracion > t.desde)) {
|
|
649
|
+
nota.textContent = "El cambio se solapa con una tarea dependiente.";
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
ocupado = lista.inert = true;
|
|
653
|
+
const cambio = { ...tarea, desde, duracion };
|
|
654
|
+
try {
|
|
655
|
+
await alCambiar(cambio);
|
|
656
|
+
tareas = tareas.map((t) => t.id === tarea.id ? cambio : t);
|
|
657
|
+
pintar();
|
|
658
|
+
nota.textContent = "Cambio guardado.";
|
|
659
|
+
} catch (error) {
|
|
660
|
+
nota.textContent = error.detalle || error.message || "No se ha podido guardar.";
|
|
661
|
+
} finally {
|
|
662
|
+
ocupado = lista.inert = false;
|
|
663
|
+
[...lista.querySelectorAll("button[data-tarea]")].find((s) => s.dataset.tarea === String(tarea.id))?.focus();
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
function pintar() {
|
|
667
|
+
lista.replaceChildren();
|
|
668
|
+
const fechas = h("div", null, "fx-crono-fechas");
|
|
669
|
+
const formato = new Intl.DateTimeFormat(document.documentElement.lang || "es", { day: "numeric", month: "short", timeZone: "UTC" });
|
|
670
|
+
fechas.append(h("span", formato.format(new Date(fecha(0)))), h("span", formato.format(new Date(fecha(dias - 1)))));
|
|
671
|
+
lista.append(fechas);
|
|
672
|
+
for (const tarea of tareas) {
|
|
673
|
+
const fila = h("article", null, "fx-crono-fila");
|
|
674
|
+
const editor = h("div", null, "fx-fila");
|
|
675
|
+
editor.hidden = true;
|
|
676
|
+
const abrir = boton(tarea.titulo, () => {
|
|
677
|
+
editor.hidden = !editor.hidden;
|
|
678
|
+
abrir.setAttribute("aria-expanded", String(!editor.hidden));
|
|
679
|
+
if (!editor.hidden) desde.focus();
|
|
680
|
+
});
|
|
681
|
+
abrir.dataset.tarea = tarea.id;
|
|
682
|
+
abrir.setAttribute("aria-expanded", "false");
|
|
683
|
+
const anterior = tareas.find((t) => t.id === tarea.dependeDe);
|
|
684
|
+
fila.append(abrir);
|
|
685
|
+
if (anterior) fila.append(h("p", `Después de ${anterior.titulo}`));
|
|
686
|
+
const pista = h("div", null, "fx-crono-pista");
|
|
687
|
+
const barra = h("div", null, "fx-crono-barra");
|
|
688
|
+
barra.style.left = `${tarea.desde / dias * 100}%`;
|
|
689
|
+
barra.style.width = `${tarea.duracion / dias * 100}%`;
|
|
690
|
+
barra.title = `${tarea.titulo} · ${fecha(tarea.desde)} – ${fecha(tarea.desde + tarea.duracion - 1)}`;
|
|
691
|
+
const asa = h("span", null, "fx-crono-asa");
|
|
692
|
+
barra.append(asa);
|
|
693
|
+
pista.append(barra);
|
|
694
|
+
let gesto;
|
|
695
|
+
barra.onpointerdown = (e) => {
|
|
696
|
+
if (e.button !== 0 || ocupado) return;
|
|
697
|
+
gesto = { x: e.clientX, alargar: e.target === asa };
|
|
698
|
+
barra.setPointerCapture(e.pointerId);
|
|
699
|
+
};
|
|
700
|
+
barra.onpointercancel = () => { gesto = null; };
|
|
701
|
+
barra.onpointerup = (e) => {
|
|
702
|
+
if (!gesto) return;
|
|
703
|
+
const { x, alargar } = gesto;
|
|
704
|
+
gesto = null;
|
|
705
|
+
const delta = Math.round((e.clientX - x) / pista.clientWidth * dias);
|
|
706
|
+
if (delta) void guardar(tarea, tarea.desde + (alargar ? 0 : delta), tarea.duracion + (alargar ? delta : 0));
|
|
707
|
+
};
|
|
708
|
+
const desde = h("input", null, "fx-campo");
|
|
709
|
+
desde.type = "date";
|
|
710
|
+
desde.value = fecha(tarea.desde);
|
|
711
|
+
const duracion = h("input", null, "fx-campo");
|
|
712
|
+
duracion.type = "number";
|
|
713
|
+
duracion.min = "1";
|
|
714
|
+
duracion.max = String(dias);
|
|
715
|
+
duracion.value = String(tarea.duracion);
|
|
716
|
+
const etiquetaDesde = h("label", "Inicio");
|
|
717
|
+
etiquetaDesde.append(desde);
|
|
718
|
+
const etiquetaDuracion = h("label", "Duración en días");
|
|
719
|
+
etiquetaDuracion.append(duracion);
|
|
720
|
+
editor.append(etiquetaDesde, etiquetaDuracion, boton("Guardar", () => {
|
|
721
|
+
const desplazamiento = (Date.parse(desde.value) - Date.parse(inicio)) / 86400000;
|
|
722
|
+
void guardar(tarea, desplazamiento, duracion.valueAsNumber);
|
|
723
|
+
}));
|
|
724
|
+
fila.append(pista, editor);
|
|
725
|
+
lista.append(fila);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
pintar();
|
|
729
|
+
return insertar(raiz, tarjeta);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
export function mapa(raiz, { titulo, fondo, puntos, alElegir }) {
|
|
733
|
+
const tarjeta = caja(titulo);
|
|
734
|
+
const plano = h("div", null, "fx-mapa");
|
|
735
|
+
if (fondo) {
|
|
736
|
+
const imagen = h("img");
|
|
737
|
+
imagen.alt = "";
|
|
738
|
+
imagen.src = fondo;
|
|
739
|
+
plano.append(imagen);
|
|
740
|
+
}
|
|
741
|
+
const leyenda = h("ol", null, "fx-leyenda");
|
|
742
|
+
const nota = estado();
|
|
743
|
+
for (const [i, punto] of puntos.entries()) {
|
|
744
|
+
const numero = i + 1;
|
|
745
|
+
const marcar = () => {
|
|
746
|
+
nota.textContent = punto.etiqueta;
|
|
747
|
+
alElegir?.(punto);
|
|
748
|
+
};
|
|
749
|
+
const pin = boton(numero, marcar);
|
|
750
|
+
pin.classList.add("fx-mapa-pin");
|
|
751
|
+
pin.setAttribute("aria-label", punto.etiqueta);
|
|
752
|
+
pin.style.left = `${Math.min(100, Math.max(0, punto.x))}%`;
|
|
753
|
+
pin.style.top = `${Math.min(100, Math.max(0, punto.y))}%`;
|
|
754
|
+
plano.append(pin);
|
|
755
|
+
const item = h("li");
|
|
756
|
+
item.append(boton(`${numero} · ${punto.etiqueta}`, marcar));
|
|
757
|
+
leyenda.append(item);
|
|
758
|
+
}
|
|
759
|
+
tarjeta.append(plano, leyenda, nota);
|
|
760
|
+
return insertar(raiz, tarjeta);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
export function progreso(raiz, { actual, total, titulo = "Progreso" }) {
|
|
764
|
+
const bloque = h("div", null, "fx-progreso");
|
|
765
|
+
const texto = h("span");
|
|
766
|
+
const medidor = h("progress");
|
|
767
|
+
medidor.setAttribute("aria-label", titulo);
|
|
768
|
+
const actualizar = (paso) => {
|
|
769
|
+
medidor.max = total;
|
|
770
|
+
medidor.value = paso;
|
|
771
|
+
texto.textContent = `${paso} de ${total}`;
|
|
772
|
+
};
|
|
773
|
+
actualizar(actual);
|
|
774
|
+
bloque.append(texto, medidor);
|
|
775
|
+
return { ...insertar(raiz, bloque), actualizar };
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
export function chispa(raiz, { tipo = "bienvenida", titulo, texto, accion }) {
|
|
779
|
+
const tarjeta = caja(titulo);
|
|
780
|
+
tarjeta.classList.add("fx-chispa");
|
|
781
|
+
const dibujo = svg("svg", { viewBox: "0 0 48 48", width: 48, height: 48, "aria-hidden": "true" });
|
|
782
|
+
dibujo.append(svg("path", {
|
|
783
|
+
d: tipo === "vacio" ? "M5 27 12 12h24l7 15v12H5z M5 27h12l3 5h8l3-5h12" :
|
|
784
|
+
"M24 4l4 15 15 5-15 4-4 15-5-15-15-4 15-5z M39 5v10 M34 10h10",
|
|
785
|
+
fill: "none", stroke: "var(--chispa-1)", "stroke-width": 2, "stroke-linejoin": "round",
|
|
786
|
+
}));
|
|
787
|
+
tarjeta.prepend(dibujo);
|
|
788
|
+
if (texto) tarjeta.append(h("p", texto));
|
|
789
|
+
if (accion) {
|
|
790
|
+
const fila = h("div", null, "fx-fila");
|
|
791
|
+
fila.append(boton(accion.etiqueta, accion.alPulsar));
|
|
792
|
+
tarjeta.append(fila);
|
|
793
|
+
}
|
|
794
|
+
return insertar(raiz, tarjeta);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
let idCampo = 0;
|
|
798
|
+
function campoAsistente(campo, valor, cambiar, crm) {
|
|
799
|
+
const grupo = h("div", null, "fx-campo-rico");
|
|
800
|
+
const etiqueta = h("label", campo.etiqueta + (campo.obligatorio ? " *" : ""));
|
|
801
|
+
const id = `fx-campo-${++idCampo}`;
|
|
802
|
+
etiqueta.htmlFor = id;
|
|
803
|
+
grupo.append(etiqueta);
|
|
804
|
+
let control;
|
|
805
|
+
let destruir = () => {};
|
|
806
|
+
let retirado = false;
|
|
807
|
+
let validar = () => control.reportValidity();
|
|
808
|
+
if (campo.tipo === "archivo" || campo.tipo === "registro") {
|
|
809
|
+
const mensaje = estado();
|
|
810
|
+
const error = estado();
|
|
811
|
+
const selector = h("div");
|
|
812
|
+
const actualizar = (v) => {
|
|
813
|
+
valor = v;
|
|
814
|
+
cambiar(v);
|
|
815
|
+
mensaje.textContent = v?.nombre ?? (v ? `Registro ${v.id}` : "Sin seleccionar");
|
|
816
|
+
error.textContent = "";
|
|
817
|
+
selector.hidden = true;
|
|
818
|
+
};
|
|
819
|
+
control = boton(campo.tipo === "archivo" ? "Elegir archivo" : "Buscar registro", async () => {
|
|
820
|
+
if (campo.tipo === "registro") {
|
|
821
|
+
selector.hidden = !selector.hidden;
|
|
822
|
+
if (!selector.hidden && !selector.hasChildNodes()) {
|
|
823
|
+
const pieza = selectorRegistros(selector, {
|
|
824
|
+
crm, modulo: campo.modulo, etiqueta: campo.mostrar ?? ((f) => f.nombre ?? f.id),
|
|
825
|
+
alElegir(fila) { actualizar(fila); control.focus(); },
|
|
826
|
+
});
|
|
827
|
+
destruir = pieza.destruir;
|
|
828
|
+
}
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
if (control.disabled) return;
|
|
832
|
+
control.setAttribute("aria-busy", "true");
|
|
833
|
+
control.disabled = true;
|
|
834
|
+
try {
|
|
835
|
+
const elegido = await crm.archivos.elegir({ titulo: campo.etiqueta });
|
|
836
|
+
if (elegido && !retirado) actualizar(elegido);
|
|
837
|
+
} catch (e) {
|
|
838
|
+
error.textContent = e.detalle || "No se ha podido seleccionar el archivo.";
|
|
839
|
+
} finally {
|
|
840
|
+
control.removeAttribute("aria-busy");
|
|
841
|
+
control.disabled = false;
|
|
842
|
+
}
|
|
843
|
+
});
|
|
844
|
+
control.setAttribute("aria-label", `${control.textContent}: ${campo.etiqueta}`);
|
|
845
|
+
selector.hidden = true;
|
|
846
|
+
actualizar(valor);
|
|
847
|
+
grupo.append(control, mensaje, selector, error);
|
|
848
|
+
validar = () => {
|
|
849
|
+
if (!campo.obligatorio || valor) return true;
|
|
850
|
+
error.textContent = `Selecciona ${campo.etiqueta.toLocaleLowerCase()}.`;
|
|
851
|
+
control.focus();
|
|
852
|
+
return false;
|
|
853
|
+
};
|
|
854
|
+
} else {
|
|
855
|
+
control = campo.opciones ? elegir(campo.etiqueta, [{ valor: "", etiqueta: "Selecciona…" }, ...campo.opciones]) :
|
|
856
|
+
h("input", null, "fx-campo");
|
|
857
|
+
if (!campo.opciones) control.type = campo.tipo === "firma" ? "text" : campo.tipo ?? "text";
|
|
858
|
+
control.required = Boolean(campo.obligatorio);
|
|
859
|
+
control.value = campo.tipo === "firma" ? valor?.nombre ?? "" : valor ?? "";
|
|
860
|
+
control.oninput = () => cambiar(campo.tipo === "firma" ?
|
|
861
|
+
(control.value.trim() ? { nombre: control.value.trim() } : null) : control.value);
|
|
862
|
+
grupo.append(control);
|
|
863
|
+
if (campo.tipo === "firma") {
|
|
864
|
+
const pad = svg("svg", { viewBox: "0 0 320 96", "aria-hidden": "true" });
|
|
865
|
+
pad.classList.add("fx-firma");
|
|
866
|
+
const trazos = (valor?.trazos ?? []).map((trazo) => trazo.map((p) => [...p]));
|
|
867
|
+
const dibujar = () => pad.replaceChildren(...trazos.map((trazo) => svg("polyline", {
|
|
868
|
+
points: trazo.map((p) => p.join(",")).join(" "), fill: "none", stroke: "currentColor",
|
|
869
|
+
"stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round",
|
|
870
|
+
})));
|
|
871
|
+
const actualizar = () => {
|
|
872
|
+
const nombre = control.value.trim();
|
|
873
|
+
cambiar(nombre || trazos.length ? { nombre, trazos } : null);
|
|
874
|
+
control.setCustomValidity(campo.obligatorio && !nombre && !trazos.length ? "Firma con tu nombre o dibuja la firma." : "");
|
|
875
|
+
};
|
|
876
|
+
dibujar();
|
|
877
|
+
actualizar();
|
|
878
|
+
control.required = false;
|
|
879
|
+
control.oninput = actualizar;
|
|
880
|
+
let puntero;
|
|
881
|
+
function punto(e) {
|
|
882
|
+
const medida = pad.getBoundingClientRect();
|
|
883
|
+
return [(e.clientX - medida.left) / medida.width * 320, (e.clientY - medida.top) / medida.height * 96];
|
|
884
|
+
}
|
|
885
|
+
pad.onpointerdown = (e) => {
|
|
886
|
+
if (e.button !== 0 || puntero != null) return;
|
|
887
|
+
puntero = e.pointerId;
|
|
888
|
+
pad.setPointerCapture(puntero);
|
|
889
|
+
trazos.push([punto(e)]);
|
|
890
|
+
};
|
|
891
|
+
pad.onpointermove = (e) => {
|
|
892
|
+
if (e.pointerId !== puntero) return;
|
|
893
|
+
trazos.at(-1).push(punto(e));
|
|
894
|
+
dibujar();
|
|
895
|
+
};
|
|
896
|
+
pad.onpointerup = pad.onpointercancel = (e) => {
|
|
897
|
+
if (e.pointerId !== puntero) return;
|
|
898
|
+
puntero = null;
|
|
899
|
+
if (trazos.at(-1).length < 2) trazos.pop();
|
|
900
|
+
actualizar();
|
|
901
|
+
};
|
|
902
|
+
control.placeholder = "Escribe tu nombre o firma abajo";
|
|
903
|
+
grupo.append(pad, boton("Borrar firma dibujada", () => { trazos.length = 0; dibujar(); actualizar(); }));
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
control.id = id;
|
|
907
|
+
if (campo.ayuda) grupo.append(h("p", campo.ayuda));
|
|
908
|
+
return { grupo, validar, destruir() { retirado = true; destruir(); } };
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
export function asistente(raiz, { titulo, pasos, inicial = {}, crm, alEnviar, alCancelar, pantallaCompleta = false }) {
|
|
912
|
+
if (!pasos.length) throw new Error("El asistente necesita al menos un paso.");
|
|
913
|
+
const tarjeta = caja(titulo);
|
|
914
|
+
if (pantallaCompleta) tarjeta.classList.add("fx-asistente-entero");
|
|
915
|
+
const valores = { ...inicial };
|
|
916
|
+
const cuerpo = h("div", null, "fx-asistente-cuerpo");
|
|
917
|
+
const pie = h("div", null, "fx-fila");
|
|
918
|
+
const nota = estado();
|
|
919
|
+
const medidor = progreso(tarjeta, { actual: 1, total: pasos.length, titulo: "Paso actual" });
|
|
920
|
+
let indice = 0, campos = [], cerrado = false;
|
|
921
|
+
const atras = boton("Anterior", () => { indice--; pintar(true); });
|
|
922
|
+
const siguiente = boton("Siguiente", async () => {
|
|
923
|
+
if (campos.some((c) => !c.validar())) return;
|
|
924
|
+
try {
|
|
925
|
+
const error = await validarPaso();
|
|
926
|
+
if (cerrado) return;
|
|
927
|
+
if (error) { nota.textContent = error; return; }
|
|
928
|
+
if (indice < pasos.length - 1) { indice++; pintar(true); return; }
|
|
929
|
+
const resultado = await alEnviar({ ...valores });
|
|
930
|
+
if (cerrado) return;
|
|
931
|
+
limpiar();
|
|
932
|
+
cuerpo.replaceChildren();
|
|
933
|
+
nota.textContent = typeof resultado === "string" ? resultado : "Formulario completado.";
|
|
934
|
+
pie.replaceChildren(...(cancelar ? [cancelar] : []));
|
|
935
|
+
} catch (error) {
|
|
936
|
+
nota.textContent = error.detalle || error.message || "No se ha podido completar el paso.";
|
|
937
|
+
} finally {
|
|
938
|
+
cuerpo.inert = pie.inert = false;
|
|
939
|
+
}
|
|
940
|
+
});
|
|
941
|
+
async function validarPaso() {
|
|
942
|
+
cuerpo.inert = pie.inert = true;
|
|
943
|
+
return pasos[indice].validar?.({ ...valores });
|
|
944
|
+
}
|
|
945
|
+
const cancelar = alCancelar && boton("Cerrar", () => alCancelar());
|
|
946
|
+
pie.append(atras, siguiente, ...(cancelar ? [cancelar] : []));
|
|
947
|
+
tarjeta.append(cuerpo, nota, pie);
|
|
948
|
+
function limpiar() {
|
|
949
|
+
for (const campo of campos) campo.destruir();
|
|
950
|
+
}
|
|
951
|
+
function pintar(enfocar = false) {
|
|
952
|
+
limpiar();
|
|
953
|
+
const paso = pasos[indice];
|
|
954
|
+
campos = paso.campos.map((campo) => campoAsistente(campo, valores[campo.id], (v) => { valores[campo.id] = v; }, crm));
|
|
955
|
+
const encabezado = h("h3", paso.titulo);
|
|
956
|
+
encabezado.tabIndex = -1;
|
|
957
|
+
cuerpo.replaceChildren(encabezado);
|
|
958
|
+
if (paso.resumen) {
|
|
959
|
+
const resumen = h("dl", null, "fx-revision");
|
|
960
|
+
for (const [etiqueta, descripcion] of Object.entries(paso.resumen({ ...valores }))) {
|
|
961
|
+
const fila = h("div", null, "fx-aviso");
|
|
962
|
+
fila.append(h("dt", etiqueta), h("dd", descripcion));
|
|
963
|
+
resumen.append(fila);
|
|
964
|
+
}
|
|
965
|
+
cuerpo.append(resumen);
|
|
966
|
+
}
|
|
967
|
+
cuerpo.append(...campos.map(({ grupo }) => grupo));
|
|
968
|
+
medidor.actualizar(indice + 1);
|
|
969
|
+
atras.disabled = indice === 0;
|
|
970
|
+
siguiente.textContent = indice === pasos.length - 1 ? "Guardar" : "Siguiente";
|
|
971
|
+
nota.textContent = "";
|
|
972
|
+
if (enfocar) {
|
|
973
|
+
cuerpo.inert = false;
|
|
974
|
+
encabezado.focus();
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
pintar();
|
|
978
|
+
raiz.append(tarjeta);
|
|
979
|
+
return { destruir() { cerrado = true; limpiar(); tarjeta.remove(); } };
|
|
980
|
+
}
|