@veracity/vui
Version:
Veracity UI is a React component library crafted for use within Veracity applications and pages. Based on Styled Components and @xstyled.
87 lines (85 loc) • 2.48 kB
JavaScript
import { __DEV__ } from "../utils/consts.js";
//#region src/svg/helpers.ts
const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
/**
* SVG elements allowed in icon content. Notably excludes 'script' and
* 'foreignObject' (which switches parsing back to HTML and enables
* DOM clobbering / XSS). Comparison is case-sensitive per XML parsing.
*/
const ALLOWED_ELEMENTS = /* @__PURE__ */ new Set([
"svg",
"g",
"path",
"circle",
"ellipse",
"rect",
"line",
"polyline",
"polygon",
"defs",
"title",
"desc",
"symbol",
"use",
"linearGradient",
"radialGradient",
"stop",
"clipPath",
"mask",
"pattern",
"marker",
"text",
"tspan"
]);
function warnRemoval(kind, name) {
if (true) console.warn(`[Svg] Removed unsafe SVG ${kind} \`${name}\`.`);
}
/** Removes disallowed elements, event handler attributes and external references. */
function sanitizeElement(element) {
if (element.namespaceURI !== SVG_NAMESPACE || !ALLOWED_ELEMENTS.has(element.tagName)) {
warnRemoval("element", element.tagName);
element.remove();
return;
}
for (const attr of Array.from(element.attributes)) {
const name = attr.localName.toLowerCase();
const isEventHandler = name.startsWith("on");
const isExternalRef = name === "href" && !attr.value.trim().startsWith("#");
if (isEventHandler || isExternalRef) {
warnRemoval("attribute", attr.name);
element.removeAttribute(attr.name);
}
}
for (const child of Array.from(element.children)) sanitizeElement(child);
}
/** Parses an SVG string into an inert, sanitized svg element. Returns undefined for invalid content. */
function parseSvg(html) {
const root = new DOMParser().parseFromString(html, "image/svg+xml").documentElement;
if (root.namespaceURI !== SVG_NAMESPACE || root.tagName !== "svg") return void 0;
sanitizeElement(root);
return root;
}
/** Returns an object with given element's HTML attributes. */
function getAttributes(element) {
if (!element) return {};
return Array.from(element.attributes).reduce((props, attr) => {
const { name, value } = attr;
props[name] = value;
return props;
}, {});
}
/** Returns the inner content of a sanitized svg element. */
function getSvgContent(element) {
return element?.innerHTML ?? "";
}
/** Returns object with initial state values. */
function initState() {
return {
content: "",
svgAttributes: {}
};
}
//#endregion
export { getAttributes, getSvgContent, initState, parseSvg };
globalThis.__vuiVersion__ = "5.3.1"
//# sourceMappingURL=helpers.js.map