UNPKG

@third774/google-font

Version:

A web component for loading fonts from Google Fonts

71 lines (70 loc) 2.19 kB
// src/google-font.ts var GoogleFont = class extends HTMLElement { // attributes to observe static get observedAttributes() { return ["family", "weight", "style", "display"]; } // attribute change callback attributeChangedCallback(name, oldValue, newValue) { if (oldValue !== newValue) { this.insertLinkTag(); } } render() { const template = document.createElement("template"); template.innerHTML = ` <style> :host { font-family: ${this.getAttribute("family") ?? "Inter"}; } </style> <slot></slot> `; this.shadowRoot.innerHTML = ""; this.shadowRoot.appendChild(template.content.cloneNode(true)); } constructor() { super(); this.attachShadow({ mode: "open" }); this.render(); } get href() { const family = (this.getAttribute("family") ?? "Inter").replace(/ /g, "+"); const weight = this.getAttribute("weight") ?? "400"; const weights = weight.split(",").filter(Boolean).map((w) => w.trim()); const style = this.getAttribute("style") ?? "normal"; const display = this.getAttribute("display") ?? "fallback"; const styles = style.split(",").filter(Boolean).map((s) => s.trim()); const afterAtSymbol = weights.map( (w) => styles.map((style2) => { if (styles.length === 1 && style2 === "normal") { return w; } if (style2 === "normal") { return `0,${w}`; } if (style2 === "italic") { return `1,${w}`; } if (style2 === "oblique") { return `1,${w}`; } return `0,${w}`; }) ).join(";"); const beforeAtSymbol = `${family}:${[ styles.includes("italic") && "ital", "wght" ].filter(Boolean).join(",")}`; return `https://fonts.googleapis.com/css2?family=${beforeAtSymbol}@${afterAtSymbol}&display=${display}`; } insertLinkTag() { const link = document.createElement("link"); link.setAttribute("rel", "stylesheet"); link.setAttribute("href", this.href); document.head.appendChild(link); } }; // src/index.ts customElements.define("google-font", GoogleFont); //# sourceMappingURL=index.mjs.map