UNPKG

@tag0/use-text-width

Version:
49 lines (44 loc) 2.45 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.useTextWidth = {}, global.React)); }(this, (function (exports, react) { 'use strict'; 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; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=index.js.map