UNPKG

@tag0/use-text-width

Version:
41 lines (38 loc) 1.91 kB
import { useMemo } from '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 = useMemo(function () { return ('text' in options ? options : undefined); }, [options]); var refOptions = useMemo(function () { return ('ref' in options ? options : undefined); }, [options]); return 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]); }; export { useTextWidth }; //# sourceMappingURL=index.js.map