"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = measureTextWidth;

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

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

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

var _context;

var FONT_KEYS = ['fontWeight', 'fontStyle', // 'fontVariant',
'fontSize', 'fontFamily'];
var TEXT_STYLE_KEYS = ['letterSpacing', 'wordSpacing', 'textTransform', 'fontVariantCaps', 'fontKerning', 'fontStretch', 'textRendering'];

function getCanvasContext() {
  if (!_context) {
    _context = document.createElement('canvas').getContext('2d');
  }

  return _context;
}

function getCanvasTextStyle() {
  var style = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getComputedStyle(document.body);
  var font = '';
  var textStyle = {};
  FONT_KEYS.forEach(function (k) {
    font += " ".concat(style[k]);
  });
  TEXT_STYLE_KEYS.forEach(function (k) {
    textStyle[k] = style[k];
  });
  return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, textStyle), {}, {
    font: font.trim()
  });
}

function measureTextWidth(text, style) {
  var width = 0;

  if ((typeof window === "undefined" ? "undefined" : (0, _typeof2["default"])(window)) !== undefined) {
    var _ref = style || getComputedStyle(document.body),
        _ref$tabSize = _ref.tabSize,
        tabSize = _ref$tabSize === void 0 ? 8 : _ref$tabSize;

    var tabSpace = ' '.repeat(Number(tabSize));
    var ctx = getCanvasContext();
    (0, _extends2["default"])(ctx, getCanvasTextStyle(style));
    width = ctx.measureText(text.replace(/\t/g, tabSpace)).width;
  }

  return width;
}
//# sourceMappingURL=measureTextWidth.js.map
