@tag0/use-text-width
Version:
React hook to measure text width
45 lines (40 loc) • 2.02 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var react = require('react');
var getContext = function () {
var fragment = document.createDocumentFragment();
var canvas = document.createElement('canvas');
fragment.appendChild(canvas);
return canvas.getContext('2d');
};
var getTextWidth = function (currentText, font) {
var context = getContext();
context.font = font;
if (Array.isArray(currentText)) {
return Math.max.apply(Math, currentText.map(function (t) { return context.measureText(t).width; }));
}
else {
var metrics = context.measureText(currentText);
return metrics.width;
}
};
var useTextWidth = function (options) {
var textOptions = react.useMemo(function () { return ('text' in options ? options : undefined); }, [options]);
var refOptions = react.useMemo(function () { return ('ref' in options ? options : undefined); }, [options]);
return react.useMemo(function () {
var _a, _b;
if ((_a = refOptions === null || refOptions === void 0 ? void 0 : refOptions.ref.current) === null || _a === void 0 ? void 0 : _a.textContent) {
var context = getContext();
var computedStyles = window.getComputedStyle(refOptions.ref.current);
context.font = computedStyles.font;
var metrics = context.measureText(refOptions.ref.current.textContent);
return metrics.width;
}
else if (textOptions === null || textOptions === void 0 ? void 0 : textOptions.text) {
return getTextWidth(textOptions.text, (_b = textOptions.font) !== null && _b !== void 0 ? _b : '16px times');
}
return NaN;
}, [textOptions === null || textOptions === void 0 ? void 0 : textOptions.text, textOptions === null || textOptions === void 0 ? void 0 : textOptions.font, refOptions === null || refOptions === void 0 ? void 0 : refOptions.ref]);
};
exports.useTextWidth = useTextWidth;
//# sourceMappingURL=index.js.map