From d156a44f0cb8bc7d294535719719bfc4d03065ba Mon Sep 17 00:00:00 2001 From: Alejandro Gomez Date: Thu, 26 Jan 2023 08:56:13 +0100 Subject: [PATCH] feat: improve webln UX --- src/Element/LNURLTip.tsx | 45 ++++++++++++++++++++++------------------ 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/src/Element/LNURLTip.tsx b/src/Element/LNURLTip.tsx index e02cf7d5..9d197644 100644 --- a/src/Element/LNURLTip.tsx +++ b/src/Element/LNURLTip.tsx @@ -5,6 +5,20 @@ import Modal from "Element/Modal"; import QrCode from "Element/QrCode"; import Copy from "Element/Copy"; +const useWebLn = (enable = true) => { + const maybeWebLn = "webln" in window ? window.webln : null + + useEffect(() => { + if (maybeWebLn && !maybeWebLn.enabled && enable) { + maybeWebLn.enable().catch((error) => { + console.debug("Couldn't enable WebLN") + }) + } + }, [maybeWebLn, enable]) + + return maybeWebLn +} + declare global { interface Window { webln?: { @@ -54,6 +68,7 @@ export default function LNURLTip(props: LNURLTipProps) { const [comment, setComment] = useState(); const [error, setError] = useState(); const [success, setSuccess] = useState(); + const webln = useWebLn(show); useEffect(() => { if (show && !props.invoice) { @@ -136,6 +151,7 @@ export default function LNURLTip(props: LNURLTipProps) { } else { setInvoice(data); setError(""); + payWebLNIfEnabled(data); } } else { setError("Failed to load invoice"); @@ -156,29 +172,19 @@ export default function LNURLTip(props: LNURLTipProps) { ); } - async function payWebLN() { + async function payWebLNIfEnabled(invoice: LNURLInvoice) { try { - if (!window.webln!.enabled) { - await window.webln!.enable(); + if (webln?.enabled) { + let res = await webln.sendPayment(invoice!.pr); + console.log(res); + setSuccess(invoice!.successAction || {}); } - let res = await window.webln!.sendPayment(invoice!.pr); - console.log(res); - setSuccess(invoice!.successAction || {}); } catch (e: any) { setError(e.toString()); console.warn(e); } } - function webLn() { - if ("webln" in window) { - return ( -
payWebLN()}>Pay with WebLN
- ) - } - return null; - } - function invoiceForm() { if (invoice) return null; return ( @@ -198,7 +204,7 @@ export default function LNURLTip(props: LNURLTipProps) { : null} {amount === -1 ? custom() : null} - {(amount ?? 0) > 0 ?
loadInvoice()}>Get Invoice
: null} + {(amount ?? 0) > 0 && } ) } @@ -218,10 +224,9 @@ export default function LNURLTip(props: LNURLTipProps) {
-
window.open(`lightning:${pr}`)}> +
-
{webLn()}
+
)} @@ -236,7 +241,7 @@ export default function LNURLTip(props: LNURLTipProps) { return ( <>

{success?.description ?? "Paid!"}

- {success.url ? {success.url} : null} + {success.url ? {success.url} : null} ) }