UNPKG

choerodon-ui

Version:

An enterprise-class UI design language and React-based implementation

53 lines (41 loc) 1.57 kB
import _extends from "@babel/runtime/helpers/extends"; import _typeof from "@babel/runtime/helpers/typeof"; import _objectSpread from "@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 _objectSpread(_objectSpread({}, textStyle), {}, { font: font.trim() }); } export default function measureTextWidth(text, style) { var width = 0; if ((typeof window === "undefined" ? "undefined" : _typeof(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(); _extends(ctx, getCanvasTextStyle(style)); width = ctx.measureText(text.replace(/\t/g, tabSpace)).width; } return width; } //# sourceMappingURL=measureTextWidth.js.map