nostr-web-components
Version:
collection of web components that provide quick access to basic nostr things
40 lines (39 loc) • 1.23 kB
JavaScript
import { debounce, handleImageError, transparentPixel } from "./utils.js";
import { fetchNostrUser, inputToPubkey } from "./nostr.js";
class NostrPicture extends HTMLElement {
static observedAttributes = ["pubkey", "width", "height"];
img;
constructor() {
super();
this.img = document.createElement("img");
this.img.setAttribute("part", "img");
this.img.onerror = handleImageError;
this.attachShadow({ mode: "open" });
const { shadowRoot } = this;
shadowRoot.appendChild(this.img);
}
connectedCallback() {
this.set();
}
attributeChangedCallback(name, _, value) {
if (name === "pubkey")
this.set();
else if (name === "width" || name === "height")
this.img.setAttribute(name, value);
}
set = debounce(async () => {
let input = this.getAttribute("pubkey");
if (input) {
let [pubkey, hints] = await inputToPubkey(input);
if (pubkey) {
let metadata = await fetchNostrUser(pubkey, hints || []);
this.img.src = metadata.image || transparentPixel;
this.img.alt = `picture for "${metadata.shortName}"`;
}
}
}, 200);
}
window.customElements.define("nostr-picture", NostrPicture);
export {
NostrPicture as default
};