1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
| export class AdvancedTextProcessor { constructor() { this.textMeasurer = new TextMeasurer(); }
const { minFontSize = 12, maxFontSize = 24, fontFamily = 'inherit', fontWeight = 'inherit', lineHeight = 1.2 } = options;
let high = maxFontSize; let optimalSize = minFontSize;
while (low <= high) { const mid = Math.floor((low + high) / 2); const fits = this.checkTextFits(text, containerWidth, containerHeight, mid, { fontFamily, fontWeight, lineHeight });
if (fits) { optimalSize = mid; low = mid + 1; } else { high = mid - 1; } }
return optimalSize; }
const { fontFamily, fontWeight, lineHeight } = options; const measured = this.textMeasurer.measureTextWithLineBreaks( text, fontSize, containerWidth, fontFamily, fontWeight );
return measured.width <= containerWidth && measured.height <= containerHeight; }
const { suffix = '...', fontFamily, fontWeight, lineHeight } = options;
fontFamily, fontWeight, lineHeight })) { return text; }
let right = text.length; let result = '';
while (left <= right) { const mid = Math.floor((left + right) / 2); const truncated = text.substring(0, mid) + suffix;
if (this.checkTextFits(truncated, containerWidth, containerHeight, fontSize, { fontFamily, fontWeight, lineHeight })) { result = truncated; left = mid + 1; } else { right = mid - 1; } }
return result; }
const { fontSize = 16, fontFamily = 'inherit', fontWeight = 'inherit', lineHeight = 1.2, maxLines = Infinity } = options;
fontFamily, fontWeight, lineHeight });
if (singleLineFits) { return { text, lines: 1, fits: true }; }
let lines = []; let currentLine = '';
for (const word of words) { const testLine = currentLine ? `${currentLine} ${word}` : word; const testLineFits = this.checkTextFits(testLine, containerWidth, containerHeight, fontSize, { fontFamily, fontWeight, lineHeight });
if (testLineFits && lines.length + 1 <= maxLines) { currentLine = testLine; } else { if (currentLine) { lines.push(currentLine); }
break; }
currentLine = word; } }
if (currentLine) { lines.push(currentLine); }
const resultText = lines.join('\n'); const totalHeight = lines.length * fontSize * lineHeight;
return { text: resultText, lines: lines.length, fits: totalHeight <= containerHeight }; }
destroy() { this.textMeasurer.cleanup(); } }
|