Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function TextWidth(text = "", font = "", containerWidth = 0)
- {
- if (!text) return 0;
- if (!font) font = `${cellBase.FontSize}px ${cellBase.FontFamily1}`;
- if (!containerWidth) containerWidth = cellBase.SpanX;
- // Create a hidden div with a span inside it
- let div = TextWidth.div || (TextWidth.div = document.createElement("div"));
- div.style.position = "absolute";
- div.style.visibility = "hidden";
- div.style.whiteSpace = "nowrap"; // Prevent wrapping artificially
- div.style.font = font;
- div.style.display = "block"; // Prevent Chrome/Edge measurement issues
- div.style.maxWidth = "none"; // Ensure accurate text width calculation
- // Ensure breakable text wrapping container
- let span = document.createElement("span");
- span.style.whiteSpace = "normal"; // Allow natural wrapping
- span.textContent = text;
- div.appendChild(span);
- // Append to the document to allow measurement
- document.body.appendChild(div);
- // ✅ Use getBoundingClientRect() for more accurate width measurement
- let width = div.getBoundingClientRect().width;
- document.body.removeChild(div); // Clean up
- return width;
- }
- function FixTextWidth(text = "", font = "", containerWidth = 0)
- {
- if (!text) return text;
- if (!font) font = `${cellBase.FontSize}px ${cellBase.FontFamily1}`;
- if (!containerWidth) containerWidth = cellBase.SpanX;
- // Measure original text width
- let originalWidth = TextWidth(text, font);
- if (originalWidth <= containerWidth) return text; // If it fits, return unchanged
- // 🔹 Introduce soft hyphen (`\u00AD`) and zero-width space (`\u200B`) to force breaks
- let modifiedText = text.replace(/\//g, "/\u200B").replace(/-/g, "-\u200B");
- // Measure new width
- let newWidth = TextWidth(modifiedText, font);
- // If still too wide, insert `­` to force breaking at `/` and `-`
- if (newWidth > containerWidth)
- {
- modifiedText = text.replace(/\//g, "/­").replace(/-/g, "-­");
- newWidth = TextWidth(modifiedText, font);
- }
- // Ensure Chrome and Edge recognize soft hyphens in HTML
- return newWidth > containerWidth ? text : modifiedText;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement