"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.reactAttributes = exports.parseStyleString = exports.deserialize = exports.MARK_TAGS = void 0;

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slateHtmlSerializer = _interopRequireDefault(require("slate-html-serializer"));

var _toStyle = require("to-style");

var _debug = _interopRequireDefault(require("debug"));

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

var log = (0, _debug["default"])('@pie-lib:mask-markup:serialization');
var INLINE = ['span'];
var MARK = ['em', 'strong', 'u'];
var TEXT_NODE = 3;
var COMMENT_NODE = 8;

var attr = function attr(el) {
  if (!el.attributes || el.attributes.length <= 0) {
    return undefined;
  }

  var out = {};
  var i;

  for (i = 0; i < el.attributes.length; i++) {
    var a = el.attributes[i];
    out[a.name] = a.value;
  }

  return out;
};

var getObject = function getObject(type) {
  if (INLINE.includes(type)) {
    return 'inline';
  } else if (MARK.includes(type)) {
    return 'mark';
  }

  return 'block';
};

var parseStyleString = function parseStyleString(s) {
  var regex = /([\w-]*)\s*:\s*([^;]*)/g;
  var match;
  var result = {};

  while (match = regex.exec(s)) {
    result[match[1]] = match[2].trim();
  }

  return result;
};

exports.parseStyleString = parseStyleString;

var reactAttributes = function reactAttributes(o) {
  return (0, _toStyle.object)(o, {
    camelize: true,
    addUnits: false
  });
};

exports.reactAttributes = reactAttributes;

var handleStyles = function handleStyles(el, attribute) {
  var styleString = el.getAttribute(attribute);
  return reactAttributes(parseStyleString(styleString));
};

var handleClass = function handleClass(el, acc, attribute) {
  var classNames = el.getAttribute(attribute);
  delete acc["class"];
  return classNames;
};

var attributesToMap = function attributesToMap(el) {
  return function (acc, attribute) {
    if (!el.getAttribute) {
      return acc;
    }

    var value = el.getAttribute(attribute);

    if (value) {
      switch (attribute) {
        case 'style':
          acc.style = handleStyles(el, attribute);
          break;

        case 'class':
          acc.className = handleClass(el, acc, attribute);
          break;

        default:
          acc[attribute] = el.getAttribute(attribute);
          break;
      }
    }

    return acc;
  };
};

var attributes = ['border', 'class', 'style'];
/**
 * Tags to marks.
 *
 * @type {Object}
 */

var MARK_TAGS = {
  b: 'bold',
  em: 'italic',
  u: 'underline',
  s: 'strikethrough',
  code: 'code',
  strong: 'strong'
};
exports.MARK_TAGS = MARK_TAGS;
var marks = {
  deserialize: function deserialize(el, next) {
    var mark = MARK_TAGS[el.tagName.toLowerCase()];
    if (!mark) return;
    log('[deserialize] mark: ', mark);
    return {
      object: 'mark',
      type: mark,
      nodes: next(el.childNodes)
    };
  }
};
var rules = [marks, {
  /**
   * deserialize everything, we're not fussy about the dom structure for now.
   */
  deserialize: function deserialize(el, next) {
    if (el.nodeType === COMMENT_NODE) {
      return undefined;
    }

    if (el.nodeType === TEXT_NODE) {
      return {
        object: 'text',
        leaves: [{
          text: el.textContent
        }]
      };
    }

    var type = el.tagName.toLowerCase();
    var normalAttrs = attr(el) || {};

    if (type == 'audio' && normalAttrs.controls == '') {
      normalAttrs.controls = true;
    }

    var allAttrs = attributes.reduce(attributesToMap(el), _objectSpread({}, normalAttrs));
    var object = getObject(type);

    if (el.tagName.toLowerCase() === 'math') {
      return {
        isMath: true,
        nodes: [el]
      };
    }

    return {
      object: object,
      type: type,
      data: {
        dataset: _objectSpread({}, el.dataset),
        attributes: _objectSpread({}, allAttrs)
      },
      nodes: next(el.childNodes)
    };
  }
}];
/**
 * Create a new serializer instance with our `rules` from above.
 * Having a default div block will just put every div on it's own line, which is not ideal.
 */

var html = new _slateHtmlSerializer["default"]({
  rules: rules,
  defaultBlock: 'span'
});

var deserialize = function deserialize(s) {
  return html.deserialize(s, {
    toJSON: true
  });
};

exports.deserialize = deserialize;
//# sourceMappingURL=serialization.js.map