@j3ehcmz/ui 0.1.2 → 0.2.1

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.
@@ -0,0 +1,230 @@
1
+ "use client";
2
+
3
+ import { Check, Copy, Search, Undo2, X, type LucideIcon } from "lucide-react";
4
+ import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
5
+ import { BotonIcono } from "./controles";
6
+ import { COLOR_TONO, GLIFO_TONO, type Tono } from "./contenido";
7
+
8
+ /* ───────────── CampoBusqueda ───────────── */
9
+
10
+ /** Campo de búsqueda con lupa y botón para limpiar.
11
+ * - Controlado: `valor` + `onCambio`.
12
+ * - Dentro de un <form method="get">: `nombre` + `defaultValue` (funciona sin JS; limpiar vacía el campo y envía el formulario). */
13
+ export function CampoBusqueda({
14
+ valor,
15
+ onCambio,
16
+ nombre,
17
+ defaultValue,
18
+ placeholder,
19
+ etiqueta,
20
+ limpiar = true,
21
+ autoFocus,
22
+ className = "",
23
+ }: {
24
+ valor?: string;
25
+ onCambio?: (valor: string) => void;
26
+ nombre?: string;
27
+ defaultValue?: string;
28
+ placeholder: string;
29
+ /** Nombre accesible del campo («Buscar paciente»). */
30
+ etiqueta: string;
31
+ limpiar?: boolean;
32
+ autoFocus?: boolean;
33
+ className?: string;
34
+ }) {
35
+ const controlado = valor !== undefined;
36
+ const [interno, setInterno] = useState(defaultValue ?? "");
37
+ const actual = controlado ? valor : interno;
38
+ const ref = useRef<HTMLInputElement>(null);
39
+
40
+ const borrar = () => {
41
+ const input = ref.current;
42
+ if (controlado) onCambio?.("");
43
+ else {
44
+ setInterno("");
45
+ if (input) input.value = "";
46
+ onCambio?.("");
47
+ // En un formulario GET, limpiar = quitar el filtro.
48
+ if (input?.form && nombre && defaultValue) input.form.requestSubmit();
49
+ }
50
+ input?.focus();
51
+ };
52
+
53
+ return (
54
+ <div className={`relative flex min-w-0 items-center ${className}`}>
55
+ <Search width={15} height={15} strokeWidth={1.75} aria-hidden="true" className="pointer-events-none absolute left-3 text-tinta-3" />
56
+ <input
57
+ ref={ref}
58
+ type="search"
59
+ name={nombre}
60
+ aria-label={etiqueta}
61
+ placeholder={placeholder}
62
+ autoFocus={autoFocus}
63
+ autoComplete="off"
64
+ {...(controlado ? { value: valor } : { defaultValue })}
65
+ onChange={(e) => {
66
+ if (!controlado) setInterno(e.target.value);
67
+ onCambio?.(e.target.value);
68
+ }}
69
+ onKeyDown={(e) => e.key === "Escape" && actual && limpiar && (e.preventDefault(), borrar())}
70
+ className={`h-9 w-full rounded-[8px] border border-borde-fuerte bg-control pl-9 text-ui-lg text-tinta placeholder:text-tinta-apoyo focus:outline-2 focus:outline-tinta [&::-webkit-search-cancel-button]:appearance-none ${limpiar ? "pr-9" : "pr-3"}`}
71
+ />
72
+ {limpiar && actual && (
73
+ <button
74
+ type="button"
75
+ onClick={borrar}
76
+ aria-label="Limpiar búsqueda"
77
+ title="Limpiar búsqueda"
78
+ className="absolute right-0.5 flex size-8 cursor-pointer items-center justify-center rounded-[7px] bg-transparent text-tinta-3 hover:bg-hundida hover:text-tinta"
79
+ >
80
+ <X width={15} height={15} strokeWidth={1.75} aria-hidden="true" />
81
+ </button>
82
+ )}
83
+ </div>
84
+ );
85
+ }
86
+
87
+ /* ───────────── BotonCopiar ───────────── */
88
+
89
+ async function copiarTexto(texto: string): Promise<boolean> {
90
+ try {
91
+ await navigator.clipboard.writeText(texto);
92
+ return true;
93
+ } catch {
94
+ // http:// (modo local) o permisos: el método viejo.
95
+ try {
96
+ const area = document.createElement("textarea");
97
+ area.value = texto;
98
+ area.setAttribute("readonly", "");
99
+ area.style.position = "fixed";
100
+ area.style.opacity = "0";
101
+ document.body.appendChild(area);
102
+ area.select();
103
+ const ok = document.execCommand("copy");
104
+ area.remove();
105
+ return ok;
106
+ } catch {
107
+ return false;
108
+ }
109
+ }
110
+ }
111
+
112
+ /** Copia `texto` al portapapeles y confirma 1,5 s con ✓ (y «Copiado» para lectores de pantalla).
113
+ * Por omisión es botón de ícono 44×44 (`etiqueta` = su nombre); `conTexto` = botón con «Copiar». */
114
+ export function BotonCopiar({ texto, etiqueta, conTexto, icono = Copy, className = "" }: { texto: string; etiqueta: string; conTexto?: boolean; icono?: LucideIcon; className?: string }) {
115
+ const [estado, setEstado] = useState<"listo" | "copiado" | "error">("listo");
116
+ useEffect(() => {
117
+ if (estado === "listo") return;
118
+ const t = setTimeout(() => setEstado("listo"), 1500);
119
+ return () => clearTimeout(t);
120
+ }, [estado]);
121
+ const copiar = async () => setEstado((await copiarTexto(texto)) ? "copiado" : "error");
122
+ const Glifo = estado === "copiado" ? Check : icono;
123
+ const aviso = estado === "copiado" ? "Copiado" : estado === "error" ? "No se pudo copiar" : "";
124
+
125
+ return (
126
+ <>
127
+ {conTexto ? (
128
+ <button
129
+ type="button"
130
+ onClick={copiar}
131
+ title={etiqueta}
132
+ className={`inline-flex h-8 cursor-pointer items-center justify-center gap-[7px] whitespace-nowrap rounded-[9px] border border-borde-fuerte bg-tarjeta px-3 text-[13px] text-tinta-2 hover:bg-sutil ${className}`}
133
+ >
134
+ <Glifo width={15} height={15} strokeWidth={1.75} aria-hidden="true" className={estado === "copiado" ? "text-aldia" : undefined} />
135
+ {estado === "copiado" ? "Copiado" : estado === "error" ? "No se pudo" : "Copiar"}
136
+ </button>
137
+ ) : (
138
+ <BotonIcono icono={Glifo} titulo={etiqueta} onClick={copiar} size={17} className={`${estado === "copiado" ? "text-aldia" : ""} ${className}`} />
139
+ )}
140
+ <span role="status" className="sr-only">
141
+ {aviso}
142
+ </span>
143
+ </>
144
+ );
145
+ }
146
+
147
+ /* ───────────── Toasts ───────────── */
148
+
149
+ type OpcionesToast = { tono?: Tono; ms?: number; deshacer?: () => void };
150
+ type Toast = OpcionesToast & { id: number; texto: string };
151
+ type FnToast = (texto: string, opciones?: OpcionesToast) => void;
152
+
153
+ const ContextoToast = createContext<FnToast | null>(null);
154
+
155
+ /** Pon <ToastProvider> una vez (en el layout, dentro del Shell o alrededor). Los avisos salen abajo al centro,
156
+ * 4 s (7 s si tienen «Deshacer»); se pausan al pasar el mouse o el foco. Sin `tono` = neutro. */
157
+ export function ToastProvider({ children }: { children: ReactNode }) {
158
+ const [toasts, setToasts] = useState<Toast[]>([]);
159
+ const siguiente = useRef(1);
160
+ const quitar = useCallback((id: number) => setToasts((t) => t.filter((x) => x.id !== id)), []);
161
+ const mostrar = useCallback<FnToast>((texto, opciones = {}) => {
162
+ const id = siguiente.current++;
163
+ setToasts((t) => [...t.slice(-2), { id, texto, ...opciones }]);
164
+ }, []);
165
+
166
+ return (
167
+ <ContextoToast.Provider value={mostrar}>
168
+ {children}
169
+ <div aria-live="polite" className="noprint pointer-events-none fixed inset-x-0 bottom-4 z-[60] flex flex-col items-center gap-2 px-4 max-[760px]:bottom-[calc(80px+env(safe-area-inset-bottom,0px))]">
170
+ {toasts.map((t) => (
171
+ <TarjetaToast key={t.id} toast={t} quitar={quitar} />
172
+ ))}
173
+ </div>
174
+ </ContextoToast.Provider>
175
+ );
176
+ }
177
+
178
+ function TarjetaToast({ toast, quitar }: { toast: Toast; quitar: (id: number) => void }) {
179
+ const [pausa, setPausa] = useState(false);
180
+ const { id } = toast;
181
+ const cerrar = useCallback(() => quitar(id), [quitar, id]);
182
+ const ms = toast.ms ?? (toast.deshacer ? 7000 : 4000);
183
+ useEffect(() => {
184
+ if (pausa) return;
185
+ const t = setTimeout(cerrar, ms);
186
+ return () => clearTimeout(t);
187
+ }, [pausa, ms, cerrar]);
188
+ const Glifo = toast.tono ? GLIFO_TONO[toast.tono] : null;
189
+
190
+ return (
191
+ <div
192
+ role={toast.tono === "fallo" || toast.tono === "suspendido" ? "alert" : "status"}
193
+ onMouseEnter={() => setPausa(true)}
194
+ onMouseLeave={() => setPausa(false)}
195
+ onFocus={() => setPausa(true)}
196
+ onBlur={() => setPausa(false)}
197
+ className="pointer-events-auto flex min-h-11 w-full max-w-[440px] items-center gap-2.5 rounded-panel border border-borde-sutil bg-tarjeta py-1 pl-4 pr-1 text-ui-lg text-tinta shadow-menu"
198
+ >
199
+ {Glifo && toast.tono && <Glifo width={16} height={16} strokeWidth={1.75} aria-hidden="true" className={`flex-none ${COLOR_TONO[toast.tono]}`} />}
200
+ <span className="min-w-0 flex-1 py-1.5 [text-wrap:pretty]">{toast.texto}</span>
201
+ {toast.deshacer && (
202
+ <button
203
+ type="button"
204
+ onClick={() => {
205
+ toast.deshacer?.();
206
+ cerrar();
207
+ }}
208
+ className="inline-flex h-9 flex-none cursor-pointer items-center gap-1.5 rounded-[8px] bg-transparent px-2.5 text-ui font-semibold text-tinta hover:bg-hundida"
209
+ >
210
+ <Undo2 width={14} height={14} strokeWidth={1.75} aria-hidden="true" />
211
+ Deshacer
212
+ </button>
213
+ )}
214
+ <button type="button" onClick={cerrar} aria-label="Cerrar aviso" className="flex size-9 flex-none cursor-pointer items-center justify-center rounded-[8px] bg-transparent text-tinta-3 hover:bg-hundida">
215
+ <X width={15} height={15} strokeWidth={1.75} aria-hidden="true" />
216
+ </button>
217
+ </div>
218
+ );
219
+ }
220
+
221
+ /** `const toast = useToast(); toast("Orden guardada", { tono: "aldia" })`. Fuera de un ToastProvider no hace nada (avisa en desarrollo). */
222
+ export function useToast(): FnToast {
223
+ const fn = useContext(ContextoToast);
224
+ return (
225
+ fn ??
226
+ ((texto: string) => {
227
+ if (process.env.NODE_ENV !== "production") console.warn(`[@j3ehcmz/ui] useToast() sin <ToastProvider>: «${texto}» no se mostró.`);
228
+ })
229
+ );
230
+ }
@@ -0,0 +1,205 @@
1
+ import { ChevronLeft } from "lucide-react";
2
+ import Link from "next/link";
3
+ import type { ReactNode } from "react";
4
+ import { GlifoIcono, type IconoProp } from "../iconos/glifos";
5
+ import { Boton } from "./controles";
6
+ import { COLOR_TONO, CLASES_TONO, GLIFO_TONO, type Tono } from "./contenido";
7
+
8
+ /* Piezas de página sin estado (sirven en componentes de servidor). Solo tokens del paquete. */
9
+
10
+ /** Encabezado de página: título Sora 26/500 (22 en teléfono), descripción y acciones a la derecha.
11
+ * - `volver`: enlace «‹ Texto» arriba (pantallas de detalle).
12
+ * - `etiqueta`: etiqueta mono ENCIMA del título. Úsala solo si da contexto real (el expediente, la unidad); no como adorno.
13
+ * - `vivo`: junto al título (p. ej. <Frescura /> o un ChipEstado). */
14
+ export function EncabezadoPagina({
15
+ titulo,
16
+ descripcion,
17
+ etiqueta,
18
+ volver,
19
+ acciones,
20
+ vivo,
21
+ className = "",
22
+ }: {
23
+ titulo: ReactNode;
24
+ descripcion?: ReactNode;
25
+ etiqueta?: ReactNode;
26
+ volver?: { href: string; texto: string };
27
+ acciones?: ReactNode;
28
+ vivo?: ReactNode;
29
+ className?: string;
30
+ }) {
31
+ return (
32
+ <div className={`flex flex-wrap items-end justify-between gap-x-4 gap-y-3 ${className}`}>
33
+ <div className="grid min-w-0 gap-1.5">
34
+ {volver && (
35
+ <Link href={volver.href} className="inline-flex min-h-6 w-fit items-center gap-1 text-ui text-tinta-3 hover:text-tinta-2">
36
+ <ChevronLeft width={14} height={14} strokeWidth={1.75} aria-hidden="true" />
37
+ {volver.texto}
38
+ </Link>
39
+ )}
40
+ {etiqueta && <span className="font-mono text-etiqueta uppercase tracking-[.12em] text-tinta-3">{etiqueta}</span>}
41
+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1.5">
42
+ <h1 className="m-0 min-w-0 font-display text-seccion font-medium text-tinta [overflow-wrap:anywhere] max-[620px]:text-[22px]">{titulo}</h1>
43
+ {vivo}
44
+ </div>
45
+ {descripcion && <p className="m-0 max-w-[760px] text-ui-lg text-tinta-3 [text-wrap:pretty]">{descripcion}</p>}
46
+ </div>
47
+ {acciones && <div className="flex flex-wrap items-center gap-2">{acciones}</div>}
48
+ </div>
49
+ );
50
+ }
51
+
52
+ /** Tarjeta con encabezado (título, subtítulo, ícono y algo a la derecha) y cuerpo con relleno 18.
53
+ * Sin `titulo` ni `derecha` no dibuja encabezado. `etiqueta` = nombre accesible de la sección cuando no hay título visible. */
54
+ export function Panel({
55
+ titulo,
56
+ subtitulo,
57
+ icono,
58
+ derecha,
59
+ sinRelleno = false,
60
+ etiqueta,
61
+ className = "",
62
+ children,
63
+ }: {
64
+ titulo?: ReactNode;
65
+ subtitulo?: ReactNode;
66
+ icono?: IconoProp;
67
+ derecha?: ReactNode;
68
+ sinRelleno?: boolean;
69
+ etiqueta?: string;
70
+ className?: string;
71
+ children: ReactNode;
72
+ }) {
73
+ const cabeza = titulo !== undefined || derecha !== undefined;
74
+ return (
75
+ <section aria-label={titulo === undefined ? etiqueta : undefined} className={`min-w-0 overflow-hidden rounded-tarjeta border border-borde-sutil bg-tarjeta shadow-plana ${className}`}>
76
+ {cabeza && (
77
+ <header className="flex flex-wrap items-center justify-between gap-3 border-b border-divisor px-[18px] py-[13px]">
78
+ <div className="flex min-w-0 items-center gap-2.5">
79
+ {icono && (
80
+ <span className="flex size-7 flex-none items-center justify-center rounded-[8px] bg-hundida text-tinta-2">
81
+ <GlifoIcono icono={icono} tamano={15} />
82
+ </span>
83
+ )}
84
+ <div className="grid min-w-0">
85
+ {titulo !== undefined && <h2 className="m-0 truncate font-display text-cuerpo font-medium text-tinta">{titulo}</h2>}
86
+ {subtitulo && <p className="m-0 truncate text-mini text-tinta-3">{subtitulo}</p>}
87
+ </div>
88
+ </div>
89
+ {derecha && <div className="flex flex-none items-center gap-2">{derecha}</div>}
90
+ </header>
91
+ )}
92
+ <div className={sinRelleno ? "" : "p-[18px]"}>{children}</div>
93
+ </section>
94
+ );
95
+ }
96
+
97
+ const TINTA_TONO: Record<Tono, string> = {
98
+ aldia: "text-aldia-tinta",
99
+ porvencer: "text-porvencer-tinta",
100
+ fallo: "text-fallo-tinta",
101
+ suspendido: "text-suspendido-tinta",
102
+ sindatos: "text-sindatos-tinta",
103
+ };
104
+
105
+ /** Cifra clave: etiqueta mono, valor Sora 26 con números tabulares y nota. Con `tono`, el valor va en la tinta del
106
+ * estado Y lleva su glifo (el estado nunca va solo en color). `compacto` = valor 20 y menos relleno (filas de 4–6). */
107
+ export function Kpi({
108
+ etiqueta,
109
+ valor,
110
+ nota,
111
+ icono,
112
+ tono,
113
+ compacto,
114
+ className = "",
115
+ }: {
116
+ etiqueta: ReactNode;
117
+ valor: ReactNode;
118
+ nota?: ReactNode;
119
+ icono?: IconoProp;
120
+ tono?: Tono;
121
+ compacto?: boolean;
122
+ className?: string;
123
+ }) {
124
+ const tinta = tono ? TINTA_TONO[tono] : "text-tinta";
125
+ return (
126
+ <div className={`grid min-w-0 content-start gap-1 rounded-tarjeta border border-borde-sutil bg-tarjeta shadow-plana ${compacto ? "px-4 py-3" : "px-5 py-4"} ${className}`}>
127
+ <span className="flex min-w-0 items-center gap-1.5 font-mono text-etiqueta uppercase tracking-[.12em] text-tinta-3">
128
+ {icono && <GlifoIcono icono={icono} tamano={13} />}
129
+ <span className="truncate">{etiqueta}</span>
130
+ </span>
131
+ <span className={`flex items-center gap-2 font-display font-medium tabular-nums ${compacto ? "text-[20px] leading-[1.25] tracking-[-0.01em]" : "text-[26px] leading-[1.15] tracking-[-0.02em]"} ${tinta}`}>
132
+ {tono && <GlifoIcono icono={GLIFO_TONO[tono]} tamano={compacto ? 16 : 18} className={COLOR_TONO[tono]} />}
133
+ {valor}
134
+ </span>
135
+ {nota && <span className="text-mini text-tinta-3">{nota}</span>}
136
+ </div>
137
+ );
138
+ }
139
+
140
+ /** Aviso en línea (banda): fondo del estado, ícono del estado, título y texto, y una acción opcional.
141
+ * «fallo» y «suspendido» se anuncian (role="alert"); los demás, role="status". Sin borde lateral grueso. */
142
+ export function Aviso({
143
+ tono = "porvencer",
144
+ icono,
145
+ titulo,
146
+ accion,
147
+ className = "",
148
+ children,
149
+ }: {
150
+ tono?: Tono;
151
+ icono?: IconoProp | null;
152
+ titulo?: ReactNode;
153
+ accion?: { texto: string; onClick: () => void };
154
+ className?: string;
155
+ children?: ReactNode;
156
+ }) {
157
+ const glifo = icono === undefined ? GLIFO_TONO[tono] : icono;
158
+ const urgente = tono === "fallo" || tono === "suspendido";
159
+ return (
160
+ <div role={urgente ? "alert" : "status"} className={`flex flex-wrap items-start gap-x-3 gap-y-2 rounded-panel px-4 py-3 ${CLASES_TONO[tono]} ${className}`}>
161
+ {glifo && (
162
+ <span className="flex h-[21px] flex-none items-center">
163
+ <GlifoIcono icono={glifo} tamano={16} className={COLOR_TONO[tono]} />
164
+ </span>
165
+ )}
166
+ <div className="grid min-w-0 flex-1 basis-[220px] gap-0.5 text-ui-lg">
167
+ {titulo && <span className="font-medium text-tinta">{titulo}</span>}
168
+ {children && <div className="text-tinta-2 [text-wrap:pretty]">{children}</div>}
169
+ </div>
170
+ {accion && (
171
+ <Boton alto={32} variante="secundario" onClick={accion.onClick} className="-my-1">
172
+ {accion.texto}
173
+ </Boton>
174
+ )}
175
+ </div>
176
+ );
177
+ }
178
+
179
+ /** Bloque de carga en el lugar del contenido. Pulso suave que se apaga con prefers-reduced-motion. */
180
+ export function Esqueleto({ ancho = "100%", alto = 14, redondo, className = "" }: { ancho?: number | string; alto?: number | string; redondo?: boolean; className?: string }) {
181
+ return (
182
+ <span
183
+ aria-hidden="true"
184
+ style={{ width: ancho, height: alto }}
185
+ className={`block flex-none animate-pulse bg-esqueleto motion-reduce:animate-none ${redondo ? "rounded-full" : "rounded-[6px]"} ${className}`}
186
+ />
187
+ );
188
+ }
189
+
190
+ const ANCHOS = ["62%", "88%", "45%", "74%", "56%"];
191
+
192
+ /** Fila de lista cargando: avatar opcional + `lineas` de anchos distintos. Anuncia «Cargando…» a lectores de pantalla. */
193
+ export function FilaEsqueleto({ lineas = 3, avatar, className = "" }: { lineas?: number; avatar?: boolean; className?: string }) {
194
+ return (
195
+ <div role="status" className={`flex items-start gap-3 px-[18px] py-[14px] ${className}`}>
196
+ <span className="sr-only">Cargando…</span>
197
+ {avatar && <Esqueleto ancho={36} alto={36} redondo />}
198
+ <div className="grid min-w-0 flex-1 gap-2 pt-0.5">
199
+ {Array.from({ length: lineas }, (_, i) => (
200
+ <Esqueleto key={i} ancho={i === 0 ? "38%" : ANCHOS[i % ANCHOS.length]} alto={i === 0 ? 14 : 12} />
201
+ ))}
202
+ </div>
203
+ </div>
204
+ );
205
+ }