UNPKG

@razorpay/blade

Version:

The Design System that powers Razorpay

61 lines (53 loc) 1.88 kB
import { MAX_WIDTH, PADDING_HORIZONTAL, MIN_WIDTH } from './tokens.js'; var calculateTextWidth = function calculateTextWidth(text, theme) { // Create a temporary canvas to measure text var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); if (!context) return { width: 80, displayText: text }; // fallback // Set font properties to match the text styling var fontSize = theme.typography.fonts.size[50]; var fontFamily = theme.typography.fonts.family.text; var fontWeight = theme.typography.fonts.weight.medium; context.font = "".concat(fontWeight, " ").concat(fontSize, "px ").concat(fontFamily); // Measure the full text first var fullTextWidth = context.measureText(text).width; var availableWidth = MAX_WIDTH - PADDING_HORIZONTAL; // If text fits within max width, use it as is if (fullTextWidth <= availableWidth) { var _finalWidth = Math.max(MIN_WIDTH, fullTextWidth + PADDING_HORIZONTAL); return { width: _finalWidth, displayText: text }; } // Text is too long, need to truncate var ELLIPSIS = '...'; var ellipsisWidth = context.measureText(ELLIPSIS).width; var maxTextWidth = availableWidth - ellipsisWidth; // Binary search to find the optimal truncation point var left = 0; var right = text.length; var bestFit = ''; while (left <= right) { var mid = Math.floor((left + right) / 2); var testText = text.substring(0, mid); var testWidth = context.measureText(testText).width; if (testWidth <= maxTextWidth) { bestFit = testText; left = mid + 1; } else { right = mid - 1; } } var truncatedText = bestFit + ELLIPSIS; var finalWidth = Math.max(MIN_WIDTH, MAX_WIDTH); return { width: finalWidth, displayText: truncatedText }; }; export { calculateTextWidth }; //# sourceMappingURL=utils.js.map