v1.34.0: leer QR con la cámara
Botón ⌗ QR junto a cada campo (direcciones, URI de pago, txid, xpub, PSBT, tx en crudo). Enseña lo leído y pide confirmar. Rechaza semillas y claves privadas sin mostrarlas. Foto de respaldo sin cámara en directo. Librería qr 0.7.2 (Paul Miller) en vendor/qr/, con su huella en SETUP. Pruebas en tests/test22.js. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L5npnUYgSPkAaHkdaeUqBr
This commit is contained in:
@@ -0,0 +1,187 @@
|
||||
// ── Leer QR con la cámara (v1.34) ─────────────────────────────────────
|
||||
// La librería (qr de Paul Miller) vive en vendor/qr/ y solo se carga al
|
||||
// abrir el lector. Todo ocurre en el navegador: la imagen de la cámara no
|
||||
// sale del aparato y leer un QR no hace ninguna consulta de red.
|
||||
let promesaLectorQR = null;
|
||||
// import() dinámico escondido en una función para que Babel no lo toque.
|
||||
const importarModulo = new Function("u", "return import(u)");
|
||||
function cargarLectorQR() {
|
||||
if (!promesaLectorQR) {
|
||||
promesaLectorQR = importarModulo(new URL("vendor/qr/decode.js", location.href).href)
|
||||
.then(m => m.decodeQR || m.default)
|
||||
.catch(e => { promesaLectorQR = null; throw e; });
|
||||
}
|
||||
return promesaLectorQR;
|
||||
}
|
||||
function resumenQR(r) {
|
||||
if (!r) return "";
|
||||
if (r.tipo === "xpub") return `${r.valor.slice(0, 12)}…${r.valor.slice(-8)}${r.huella ? ` · huella ${r.huella}` : ""}${r.ruta ? ` · ${r.ruta}` : ""}`;
|
||||
if (r.tipo === "psbt") return `PSBT de ${r.valor.length.toLocaleString("es-ES")} caracteres`;
|
||||
if (r.tipo === "tx") return `transacción de ${(r.valor.length / 2).toLocaleString("es-ES")} bytes`;
|
||||
return r.valor;
|
||||
}
|
||||
|
||||
function BotonQR({ campo, onLeido, color }) {
|
||||
const [abierto, setAbierto] = useState(false);
|
||||
const col = color || C.purple;
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setAbierto(true)} title="Leer un QR con la cámara" aria-label="Leer un QR con la cámara"
|
||||
style={{ padding: "0 12px", minWidth: 42, background: C.bg, border: `1px solid ${col}40`, borderRadius: 6, color: col, fontSize: "1rem", cursor: "pointer", flexShrink: 0 }}>
|
||||
⌗<span style={{ fontFamily: C.mono, fontSize: "0.6rem", marginLeft: 4 }}>QR</span>
|
||||
</button>
|
||||
{abierto && <LectorQR campo={campo} onCerrar={() => setAbierto(false)} onUsar={v => { setAbierto(false); onLeido(v); }} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function LectorQR({ campo, onCerrar, onUsar }) {
|
||||
const videoRef = useRef(null), streamRef = useRef(null), vivoRef = useRef(true), fotoRef = useRef(null);
|
||||
const [fase, setFase] = useState("cargando"); // cargando · camara · sin-camara · leido · otro · secreto · sin-lector
|
||||
const [aviso, setAviso] = useState("");
|
||||
const [leido, setLeido] = useState(null);
|
||||
|
||||
const pararCamara = () => {
|
||||
if (streamRef.current) { streamRef.current.getTracks().forEach(t => t.stop()); streamRef.current = null; }
|
||||
if (videoRef.current) videoRef.current.srcObject = null;
|
||||
};
|
||||
const procesar = texto => {
|
||||
pararCamara();
|
||||
setAviso("");
|
||||
const r = clasificarQR(texto);
|
||||
if (r.tipo === "secreto") { setLeido(null); setFase("secreto"); return; }
|
||||
const e = encajaQR(r, campo);
|
||||
setLeido(r);
|
||||
if (e.ok) { setFase("leido"); setAviso(""); }
|
||||
else { setFase("otro"); setAviso(e.mensaje); }
|
||||
};
|
||||
const leerImagen = (decode, fuente, w, h, opts) => {
|
||||
const lienzo = document.createElement("canvas");
|
||||
lienzo.width = w; lienzo.height = h;
|
||||
const ctx = lienzo.getContext("2d", { willReadFrequently: true });
|
||||
ctx.drawImage(fuente, 0, 0, w, h);
|
||||
const img = ctx.getImageData(0, 0, w, h);
|
||||
try { return decode({ width: w, height: h, data: img.data }, { textDecoder: textoDeBytesQR, ...opts }); }
|
||||
catch { return null; }
|
||||
};
|
||||
|
||||
const arrancar = async () => {
|
||||
setAviso(""); setLeido(null); setFase("cargando");
|
||||
let decode;
|
||||
try { decode = await cargarLectorQR(); }
|
||||
catch { if (vivoRef.current) setFase("sin-lector"); return; }
|
||||
if (!vivoRef.current) return;
|
||||
if (!window.isSecureContext || !navigator.mediaDevices?.getUserMedia) {
|
||||
setAviso("La cámara en directo solo funciona si abres Txoko por https. Puedes hacer una foto del QR.");
|
||||
setFase("sin-camara"); return;
|
||||
}
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: "environment" } }, audio: false });
|
||||
if (!vivoRef.current) { stream.getTracks().forEach(t => t.stop()); return; }
|
||||
streamRef.current = stream;
|
||||
setFase("camara");
|
||||
const v = videoRef.current;
|
||||
v.srcObject = stream;
|
||||
v.setAttribute("playsinline", ""); v.muted = true;
|
||||
await v.play().catch(() => {});
|
||||
let ultimo = 0;
|
||||
const bucle = ahora => {
|
||||
if (!vivoRef.current || !streamRef.current) return;
|
||||
if (ahora - ultimo > 120 && v.videoWidth) {
|
||||
ultimo = ahora;
|
||||
const esc = Math.min(1, 720 / Math.max(v.videoWidth, v.videoHeight));
|
||||
const t = leerImagen(decode, v, Math.round(v.videoWidth * esc), Math.round(v.videoHeight * esc));
|
||||
if (t != null) { procesar(t); return; }
|
||||
}
|
||||
requestAnimationFrame(bucle);
|
||||
};
|
||||
requestAnimationFrame(bucle);
|
||||
} catch (e) {
|
||||
const n = e && e.name;
|
||||
setAviso(n === "NotAllowedError" ? "No hay permiso para usar la cámara (o el navegador no lo da con este certificado). Puedes hacer una foto del QR."
|
||||
: n === "NotFoundError" || n === "OverconstrainedError" ? "No encuentro ninguna cámara en este aparato. Puedes elegir una imagen con el QR."
|
||||
: "No se ha podido abrir la cámara. Puedes hacer una foto del QR.");
|
||||
setFase("sin-camara");
|
||||
}
|
||||
};
|
||||
|
||||
const leerFoto = async archivo => {
|
||||
if (!archivo) return;
|
||||
setAviso("Buscando el QR en la imagen…");
|
||||
try {
|
||||
const decode = await cargarLectorQR();
|
||||
const bmp = await createImageBitmap(archivo);
|
||||
const esc = Math.min(1, 1600 / Math.max(bmp.width, bmp.height));
|
||||
const t = leerImagen(decode, bmp, Math.round(bmp.width * esc), Math.round(bmp.height * esc), { effort: Infinity, timeLimit: 3000 });
|
||||
if (bmp.close) bmp.close();
|
||||
if (t != null) procesar(t);
|
||||
else setAviso("No encuentro ningún QR en esa imagen. Prueba con otra más cerca y con luz.");
|
||||
} catch {
|
||||
setAviso("No he podido leer esa imagen.");
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
vivoRef.current = true;
|
||||
arrancar();
|
||||
const tecla = e => { if (e.key === "Escape") onCerrar(); };
|
||||
window.addEventListener("keydown", tecla);
|
||||
return () => { vivoRef.current = false; pararCamara(); window.removeEventListener("keydown", tecla); };
|
||||
}, []);
|
||||
|
||||
const boton = (txt, onClick, col, fuerte) => (
|
||||
<button type="button" onClick={onClick} style={{ padding: "9px 14px", background: fuerte ? `${col}22` : "none", border: `1px solid ${col}${fuerte ? "" : "60"}`, borderRadius: 6, color: col, fontFamily: C.mono, fontSize: "0.72rem", cursor: "pointer", fontWeight: fuerte ? 700 : 400 }}>{txt}</button>
|
||||
);
|
||||
return (
|
||||
<div role="dialog" aria-modal="true" aria-label="Leer un QR"
|
||||
style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(0,0,0,0.78)", display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}
|
||||
onClick={e => { if (e.target === e.currentTarget) onCerrar(); }}>
|
||||
<div style={{ width: "100%", maxWidth: 440, background: C.bgCard, border: `1px solid ${C.borderBright}`, borderRadius: 10, padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||||
<div style={{ fontFamily: C.mono, fontSize: "0.7rem", color: C.t1, fontWeight: 700, letterSpacing: "0.08em" }}>LEER UN QR</div>
|
||||
<button type="button" onClick={onCerrar} aria-label="Cerrar el lector" style={{ background: "none", border: "none", color: C.t2, fontSize: "1.1rem", cursor: "pointer" }}>×</button>
|
||||
</div>
|
||||
|
||||
{(fase === "camara" || fase === "cargando") && (
|
||||
<div style={{ position: "relative", width: "100%", aspectRatio: "1 / 1", background: "#000", borderRadius: 8, overflow: "hidden" }}>
|
||||
<video ref={videoRef} playsInline muted style={{ width: "100%", height: "100%", objectFit: "cover", display: fase === "camara" ? "block" : "none" }} />
|
||||
<div style={{ position: "absolute", inset: "14%", border: `2px solid ${C.green}aa`, borderRadius: 10, pointerEvents: "none" }} />
|
||||
{fase === "cargando" && <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", color: C.t2, fontFamily: C.mono, fontSize: "0.7rem" }}>abriendo la cámara…</div>}
|
||||
</div>
|
||||
)}
|
||||
{fase === "camara" && <div style={{ fontSize: "0.66rem", color: C.t2, lineHeight: 1.5 }}>Apunta al QR. La imagen no sale de este aparato.</div>}
|
||||
|
||||
{fase === "sin-lector" && (
|
||||
<div style={{ fontSize: "0.7rem", color: C.amber, lineHeight: 1.6 }}>
|
||||
Falta el lector de QR en el nodo: la carpeta <span style={{ fontFamily: C.mono }}>vendor/qr/</span>. Se instala con el paso 2 de SETUP.md.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fase === "secreto" && (
|
||||
<div style={{ padding: "12px 14px", background: C.redMuted, border: `1px solid ${C.red}60`, borderRadius: 8, fontSize: "0.72rem", color: C.t1, lineHeight: 1.6 }}>
|
||||
<strong style={{ color: C.red }}>Esto parece una semilla o una clave privada.</strong> Txoko no la necesita nunca, así que no la muestra ni la guarda: ya la ha olvidado. Guarda esa tarjeta y asegúrate de que no la ha visto nadie.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(fase === "leido" || fase === "otro") && leido && (
|
||||
<div style={{ padding: "10px 12px", background: C.bg, border: `1px solid ${fase === "leido" ? C.green : C.amber}60`, borderRadius: 8 }}>
|
||||
<div style={{ fontSize: "0.6rem", color: C.t2, fontFamily: C.mono, marginBottom: 4 }}>HE LEÍDO {(QR_NOMBRE[leido.tipo] || "").toUpperCase()}</div>
|
||||
{leido.valor && <div style={{ fontFamily: C.mono, fontSize: "0.72rem", color: C.t1, wordBreak: "break-all" }}>{resumenQR(leido)}</div>}
|
||||
{leido.importe && <div style={{ fontSize: "0.64rem", color: C.t2, marginTop: 4 }}>El QR pedía un pago de {leido.importe} BTC{leido.etiqueta ? ` («${leido.etiqueta}»)` : ""}. Txoko solo usa la dirección.</div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{aviso && <div style={{ fontSize: "0.68rem", color: fase === "otro" ? C.amber : C.t2, lineHeight: 1.6 }}>{aviso}</div>}
|
||||
|
||||
<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
|
||||
{fase === "leido" && boton("Usar esto", () => onUsar(leido.valor), C.green, true)}
|
||||
{(fase === "leido" || fase === "otro" || fase === "secreto") && boton("Leer otro", arrancar, C.purple)}
|
||||
{fase !== "sin-lector" && boton("Hacer una foto o elegir imagen", () => fotoRef.current && fotoRef.current.click(), C.blue)}
|
||||
{boton("Cerrar", onCerrar, C.t2)}
|
||||
<input ref={fotoRef} type="file" accept="image/*" capture="environment" style={{ display: "none" }}
|
||||
onChange={e => { pararCamara(); setFase("sin-camara"); leerFoto(e.target.files[0]); e.target.value = ""; }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user