UNPKG

nostr-web-components

Version:

collection of web components that provide quick access to basic nostr things

86 lines (85 loc) 2.2 kB
function debounce(fn, wait = 100) { let timeoutId; let timestamp; let storedArguments; function later() { const last = Date.now() - timestamp; if (last < wait && last >= 0) { timeoutId = setTimeout(later, wait - last); } else { timeoutId = void 0; fn(...storedArguments); } } return function(...args) { timestamp = Date.now(); storedArguments = args; if (!timeoutId) { timeoutId = setTimeout(later, wait); } }; } function nostrLink(code) { let res = window.nwc?.nostrLink?.(code); if (res) return res; return "https://njump.me/" + code; } function relayLink(url) { let res = window.nwc?.relayLink?.(url); if (res) return res; return "https://njump.me/r/" + encodeURIComponent(url); } const transparentPixel = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; function handleImageError(ev) { const el = ev.target; console.warn("error loading image", ev); if (el.src !== transparentPixel) { el.src = transparentPixel; } } function splitComma(value) { return value ? value.split(" ").map((v) => v.trim()).filter((v) => v.length) : []; } function shorten(nip19code) { let idx = nip19code.indexOf("1"); return nip19code.substring(0, idx + 3) + "\u2026" + nip19code.substring(nip19code.length - 5); } function shortenURL(url) { if (url.length <= 30) return url; try { let u = new URL(url); if (url.length <= 40) { return `${u.host}${u.pathname}${u.search.length ? "?" : ""}${u.search}`; } if (url.length <= 50 && u.pathname.length < 20) { return `${u.host}${u.pathname}`; } let pathname = u.pathname; let parts = u.pathname.split("/"); let lastPart = parts[parts.length - 1]; if (lastPart.length > 10) { lastPart = `\u2026${lastPart.substring(lastPart.length - 6)}`; } if (parts.length > 2) { pathname = `/\u2026/${lastPart}`; } else { pathname = `/${lastPart}`; } return `${u.host}${pathname}`; } catch (_err) { return url; } } export { debounce, handleImageError, nostrLink, relayLink, shorten, shortenURL, splitComma, transparentPixel };