UNPKG

@third774/google-font

Version:

A web component for loading fonts from Google Fonts

95 lines (94 loc) 3.17 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/google-font.ts var google_font_exports = {}; __export(google_font_exports, { GoogleFont: () => GoogleFont }); module.exports = __toCommonJS(google_font_exports); 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); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { GoogleFont }); //# sourceMappingURL=google-font.js.map