All files / components/icon validate.ts

94.74% Statements 36/38
78.57% Branches 22/28
100% Functions 2/2
93.94% Lines 31/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 631x   1x 1x 1x 1x     1x 1x           1x 1x 1x 1x 1x     1x 1x 1x           1x 1x             1x 11x 10x 2x     8x 3x 3x 3x 3x 2x         6x 3x 1x       6x    
import { isStr } from "../../utils/utils";
 
export const validateContent = (svgContent: string | null) => {
    Eif (svgContent && typeof document !== "undefined") {
        const div = document.createElement("div");
        div.innerHTML = svgContent;
 
        // setup this way to ensure it works on IE
        for (let i = div.childNodes.length - 1; i >= 0; i--) {
            Iif (div.childNodes[i].nodeName.toLowerCase() !== "svg") {
                div.removeChild(div.childNodes[i]);
            }
        }
 
        // must only have 1 root element
        const svgElm = div.firstElementChild;
        Eif (svgElm && svgElm.nodeName.toLowerCase() === "svg") {
            const svgClass = svgElm.getAttribute("class") || "";
            svgElm.setAttribute("class", (svgClass + " ux-icon__svg").trim());
            svgElm.removeAttribute("id");
 
            // remove title element to prevent a bug where the svg title was treated as the page title
            const title = svgElm.querySelector("title");
            Eif (title !== null) {
                title.remove();
            }
 
            // root element must be an svg
            // lets double check we've got valid elements
            // do not allow scripts
            Eif (isValid(svgElm as any)) {
                return div.innerHTML;
            }
        }
    }
    return "";
};
 
export const isValid = (elm: HTMLElement) => {
    if (elm.nodeType === 1) {
        if (elm.nodeName.toLowerCase() === "script") {
            return false;
        }
 
        for (let i = 0; i < elm.attributes.length; i++) {
            const attr = elm.attributes[i];
            Eif (typeof attr !== "undefined") {
                const val = elm.attributes[i].name;
                if (isStr(val) && val.toLowerCase().indexOf("on") === 0) {
                    return false;
                }
            }
        }
 
        for (let i = 0; i < elm.childNodes.length; i++) {
            if (!isValid(elm.childNodes[i] as any)) {
                return false;
            }
        }
    }
    return true;
};