(text: string, font: string, maxWidth: number)
| 428 | })(); |
| 429 | |
| 430 | export function wrapText(text: string, font: string, maxWidth: number): string { |
| 431 | // if maxWidth is not finite or NaN which can happen in case of bugs in |
| 432 | // computation, we need to make sure we don't continue as we'll end up |
| 433 | // in an infinite loop |
| 434 | if (!Number.isFinite(maxWidth) || maxWidth < 0) { |
| 435 | return text; |
| 436 | } |
| 437 | |
| 438 | const lines: Array<string> = []; |
| 439 | const originalLines = text.split('\n'); |
| 440 | const spaceWidth = getLineWidth(' ', font); |
| 441 | |
| 442 | let currentLine = ''; |
| 443 | let currentLineWidthTillNow = 0; |
| 444 | |
| 445 | const push = (str: string) => { |
| 446 | if (str.trim()) { |
| 447 | lines.push(str); |
| 448 | } |
| 449 | }; |
| 450 | |
| 451 | const resetParams = () => { |
| 452 | currentLine = ''; |
| 453 | currentLineWidthTillNow = 0; |
| 454 | }; |
| 455 | originalLines.forEach(originalLine => { |
| 456 | const currentLineWidth = getTextWidth(originalLine, font); |
| 457 | |
| 458 | // Push the line if its <= maxWidth |
| 459 | if (currentLineWidth <= maxWidth) { |
| 460 | lines.push(originalLine); |
| 461 | return; // continue |
| 462 | } |
| 463 | |
| 464 | const words = parseTokens(originalLine); |
| 465 | resetParams(); |
| 466 | |
| 467 | let index = 0; |
| 468 | |
| 469 | while (index < words.length) { |
| 470 | const currentWordWidth = getLineWidth(words[index], font); |
| 471 | |
| 472 | // This will only happen when single word takes entire width |
| 473 | if (currentWordWidth === maxWidth) { |
| 474 | push(words[index]); |
| 475 | index++; |
| 476 | } |
| 477 | |
| 478 | // Start breaking longer words exceeding max width |
| 479 | else if (currentWordWidth > maxWidth) { |
| 480 | // push current line since the current word exceeds the max width |
| 481 | // so will be appended in next line |
| 482 | |
| 483 | push(currentLine); |
| 484 | |
| 485 | resetParams(); |
| 486 | |
| 487 | while (words[index].length > 0) { |
no test coverage detected