// ── Leer QR con la cámara (v1.34; animados desde la v1.35) ───────────────────────────────────── // 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 ( <> {abierto && 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); // QR animados (v1.35): los trozos se van juntando mientras la cámara // sigue abierta. El colector vive fuera del estado de React. const colectorRef = useRef(null); const [progreso, setProgreso] = useState(null); // { formato, hechos, total } 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 => mostrar(clasificarQR(texto)); const mostrar = r => { pararCamara(); setAviso(""); setProgreso(null); 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; } }; // Lo que lee la cámara pasa primero por el colector de QR animados. Si // no es un trozo de uno, se trata como un QR normal. const recibir = (t, enFoto) => { const c = colectorRef.current || (colectorRef.current = crearColectorQR()); const e = c.recibir(t); if (e.estado === "nada") { if (c.formato && !enFoto) return false; procesar(t); return true; } if (e.estado === "secreto") { mostrar({ tipo: "secreto" }); return true; } if (e.estado === "error") { setAviso(`Un trozo no se ha podido leer (${e.mensaje}). Sigue apuntando: se vuelve a empezar.`); setProgreso(null); return false; } if (e.estado === "progreso") { if (enFoto) { c.reiniciar(); setAviso(`Es un trozo (${e.hechos} de ${e.total}) de un QR animado: hace falta la cámara en directo, que vaya leyendo los trozos mientras pasan.`); return true; } setProgreso(p => p && p.hechos === e.hechos && p.total === e.total && p.formato === e.formato ? p : { formato: e.formato, hechos: e.hechos, total: e.total }); return false; } // listo pararCamara(); c.resultado().then(r => { if (vivoRef.current) mostrar(r); }) .catch(err => { if (!vivoRef.current) return; setProgreso(null); setLeido(null); setFase("otro"); setAviso(`No se ha podido reconstruir el QR animado: ${err.message}`); }) .finally(() => { colectorRef.current = null; }); return true; }; const arrancar = async () => { setAviso(""); setLeido(null); setProgreso(null); setFase("cargando"); colectorRef.current = crearColectorQR(); 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 && recibir(t, false)) 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) { colectorRef.current = crearColectorQR(); recibir(t, true); } 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) => ( ); return (
{ if (e.target === e.currentTarget) onCerrar(); }}>
LEER UN QR
{(fase === "camara" || fase === "cargando") && (
); }