MCPcopy
hub / github.com/toeverything/AFFiNE / wrapText

Function wrapText

blocksuite/affine/gfx/text/src/element-renderer/utils.ts:430–559  ·  view source on GitHub ↗
(text: string, font: string, maxWidth: number)

Source from the content-addressed store, hash-verified

428})();
429
430export 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) {

Callers 3

normalizeShapeBoundFunction · 0.85
wrapTextDeltasFunction · 0.85
normalizeTextBoundFunction · 0.85

Calls 9

getLineWidthFunction · 0.85
getTextWidthFunction · 0.85
parseTokensFunction · 0.85
resetParamsFunction · 0.85
splitMethod · 0.80
pushFunction · 0.70
pushMethod · 0.65
forEachMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected