"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.btoa = btoa;
exports.parse = parse;
exports.png = png;
exports.purge = purge;
exports.render = render;
exports.sanitize = sanitize;
exports.stringify = stringify;

var _btoa = _interopRequireDefault(require("btoa"));

var _react = require("react");

var _components = require("@patternplate/components");

var _xmldom = require("xmldom");

var _lodash = require("lodash");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }

const parser = new _xmldom.DOMParser();
const serializer = new _xmldom.XMLSerializer();
const TAG_NAMES = ["circle", "g", "path", "polygon", "rect", "svg"];
/**
 * These attributes are valid on all SVG elements and accepted by this
 * renderer.
 * All attributes will be converted to their camelCase version.
 * This allows using valid SVG strings. 
 * Extend this list to allow additional default SVG attributes.
 * 
 * @type {Array}
 */

const SHARED_ATTRIBUTES = ["fill", "stroke", "stroke-width"];
const ATTRIBUTES = {
  circle: [...SHARED_ATTRIBUTES, "cx", "cy", "r", "style"],
  g: [...SHARED_ATTRIBUTES, "x", "y"],
  path: [...SHARED_ATTRIBUTES, "d", "style"],
  polygon: [...SHARED_ATTRIBUTES, "points"],
  rect: [...SHARED_ATTRIBUTES, "x", "y", "width", "height", "style"],
  svg: ["width", "height", "viewBox", "x", "y", "style", "xmlns"]
};

function attributes(node, key) {
  return (ATTRIBUTES[node.tagName] || []).reduce((props, name) => {
    const attribute = node.attributes.getNamedItem(name);
    const reactProp = (0, _lodash.camelCase)(name);

    if (attribute && attribute.specified) {
      props[reactProp] = attribute.value;
    }

    return props;
  }, {
    key
  });
}

function btoa(source) {
  return `data:image/svg+xml;base64,${(0, _btoa.default)(source)}`;
}

function parse(source) {
  const doc = parser.parseFromString(source, "image/svg+xml");
  const parsed = Array.prototype.slice.call(doc.childNodes).find(node => node.tagName === "svg");
  parsed.setAttribute("xmlns", "http://www.w3.org/2000/svg");
  return parsed;
}

function png(source) {
  return new Promise((resolve, reject) => {
    const img = new global.Image();
    const canvas = global.document.createElement("canvas");
    const ratio = global.devicePixelRatio || 1;
    canvas.width = 16 * ratio;
    canvas.height = 16 * ratio;
    const context = canvas.getContext("2d");

    img.onload = () => {
      context.drawImage(img, 0, 0);
      resolve(canvas.toDataURL("image/png"));
    };

    img.onerror = err => reject(err);

    img.src = btoa(source);
  });
}

function purge(parsed) {
  return Array.prototype.slice.call(parsed).filter(node => TAG_NAMES.includes(node.tagName)).map(node => {
    node.childNodes = purge(node.childNodes);
    const attributes = ATTRIBUTES[node.tagName] || [];

    for (let i = 0; i < node.attributes.length; i++) {
      const attribute = node.attributes[i];

      if (!attributes.includes(attribute.name)) {
        node.removeAttribute(attribute.name);
      }
    }

    return node;
  });
}

function render(element) {
  const _element = _slicedToArray(element, 3),
        tagName = _element[0],
        props = _element[1],
        _element$ = _element[2],
        children = _element$ === void 0 ? [] : _element$;

  const style = props.style,
        rest = _objectWithoutProperties(props, ["style"]);

  const tag = (0, _components.styled)(tagName).withConfig({
    displayName: "svg__tag"
  })(["", ";"], style);
  return (0, _react.createElement)(tag, rest, children.map(c => render(c)));
}

function sanitize(parsed) {
  return [...parsed].map((node, i) => [node.tagName, attributes(node, i), sanitize(node.childNodes)]);
}

function stringify(tree) {
  return serializer.serializeToString(tree);
}
//# sourceMappingURL=svg.js.map