Advertisement
jargon

Text Width.js

Mar 10th, 2025 (edited)
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. function TextWidth(text = "", font = "", containerWidth = 0)
  3. {
  4.     if (!text) return 0;
  5.    
  6.     if (!font) font = `${cellBase.FontSize}px ${cellBase.FontFamily1}`;
  7.    
  8.     if (!containerWidth) containerWidth = cellBase.SpanX;
  9.  
  10.     // Create a hidden div with a span inside it
  11.     let div = TextWidth.div || (TextWidth.div = document.createElement("div"));
  12.     div.style.position = "absolute";
  13.     div.style.visibility = "hidden";
  14.     div.style.whiteSpace = "nowrap";  // Prevent wrapping artificially
  15.     div.style.font = font;
  16.     div.style.display = "block"; // Prevent Chrome/Edge measurement issues
  17.     div.style.maxWidth = "none"; // Ensure accurate text width calculation
  18.  
  19.     // Ensure breakable text wrapping container
  20.     let span = document.createElement("span");
  21.     span.style.whiteSpace = "normal"; // Allow natural wrapping
  22.     span.textContent = text;
  23.     div.appendChild(span);
  24.  
  25.     // Append to the document to allow measurement
  26.     document.body.appendChild(div);
  27.  
  28.     // ✅ Use getBoundingClientRect() for more accurate width measurement
  29.     let width = div.getBoundingClientRect().width;
  30.  
  31.     document.body.removeChild(div); // Clean up
  32.  
  33.     return width;
  34. }
  35.  
  36. function FixTextWidth(text = "", font = "", containerWidth = 0)
  37. {
  38.     if (!text) return text;
  39.    
  40.     if (!font) font = `${cellBase.FontSize}px ${cellBase.FontFamily1}`;
  41.    
  42.     if (!containerWidth) containerWidth = cellBase.SpanX;
  43.  
  44.     // Measure original text width
  45.     let originalWidth = TextWidth(text, font);
  46.     if (originalWidth <= containerWidth) return text; // If it fits, return unchanged
  47.  
  48.     // 🔹 Introduce soft hyphen (`\u00AD`) and zero-width space (`\u200B`) to force breaks
  49.     let modifiedText = text.replace(/\//g, "/\u200B").replace(/-/g, "-\u200B");
  50.  
  51.     // Measure new width
  52.     let newWidth = TextWidth(modifiedText, font);
  53.  
  54.     // If still too wide, insert `&shy;` to force breaking at `/` and `-`
  55.     if (newWidth > containerWidth)
  56.     {
  57.         modifiedText = text.replace(/\//g, "/&shy;").replace(/-/g, "-&shy;");
  58.         newWidth = TextWidth(modifiedText, font);
  59.     }
  60.  
  61.     // Ensure Chrome and Edge recognize soft hyphens in HTML
  62.     return newWidth > containerWidth ? text : modifiedText;
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement