UNPKG

@zag-js/dom-query

Version:

The dom helper library for zag.js machines

69 lines (67 loc) 2.59 kB
"use strict"; 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/data-url.ts var data_url_exports = {}; __export(data_url_exports, { getDataUrl: () => getDataUrl }); module.exports = __toCommonJS(data_url_exports); var import_node = require("./node.js"); function getDataUrl(svg, opts) { const { type, quality = 0.92, background } = opts; if (!svg) throw new Error("[zag-js > getDataUrl]: Could not find the svg element"); const win = (0, import_node.getWindow)(svg); const doc = win.document; const svgBounds = svg.getBoundingClientRect(); const svgClone = svg.cloneNode(true); if (!svgClone.hasAttribute("viewBox")) { svgClone.setAttribute("viewBox", `0 0 ${svgBounds.width} ${svgBounds.height}`); } const serializer = new win.XMLSerializer(); const source = '<?xml version="1.0" standalone="no"?>\r\n' + serializer.serializeToString(svgClone); const svgString = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(source); if (type === "image/svg+xml") { return Promise.resolve(svgString).then((str) => { svgClone.remove(); return str; }); } const dpr = win.devicePixelRatio || 1; const canvas = doc.createElement("canvas"); const image = new win.Image(); image.src = svgString; canvas.width = svgBounds.width * dpr; canvas.height = svgBounds.height * dpr; const context = canvas.getContext("2d"); if (type === "image/jpeg" || background) { context.fillStyle = background || "white"; context.fillRect(0, 0, canvas.width, canvas.height); } return new Promise((resolve) => { image.onload = () => { context?.drawImage(image, 0, 0, canvas.width, canvas.height); resolve(canvas.toDataURL(type, quality)); svgClone.remove(); }; }); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { getDataUrl });