diff --git a/src/shared/lib/helpers/createCharacterComparison/createCharacterComparison.svelte.ts b/src/shared/lib/helpers/createCharacterComparison/createCharacterComparison.svelte.ts index 2867dda..8abb64c 100644 --- a/src/shared/lib/helpers/createCharacterComparison/createCharacterComparison.svelte.ts +++ b/src/shared/lib/helpers/createCharacterComparison/createCharacterComparison.svelte.ts @@ -150,42 +150,63 @@ export function createCharacterComparison< currentLineWords = []; } - let remainingWord = word; - while (remainingWord.length > 0) { - let low = 1; - let high = remainingWord.length; - let bestBreak = 1; + const wordWidthA = measureText( + ctx, + word, + Math.min(fontSize, controlledFontSize), + currentWeight, + fontA()?.name, + ); + const wordWidthB = measureText( + ctx, + word, + Math.min(fontSize, controlledFontSize), + currentWeight, + fontB()?.name, + ); + const wordAloneWidth = Math.max(wordWidthA, wordWidthB); - // Binary Search to find the maximum characters that fit - while (low <= high) { - const mid = Math.floor((low + high) / 2); - const testFragment = remainingWord.slice(0, mid); + if (wordAloneWidth <= availableWidth) { + // If word fits start new line with it + currentLineWords = [word]; + } else { + let remainingWord = word; + while (remainingWord.length > 0) { + let low = 1; + let high = remainingWord.length; + let bestBreak = 1; - const wA = measureText( - ctx, - testFragment, - fontSize, - currentWeight, - fontA()?.name, - ); - const wB = measureText( - ctx, - testFragment, - fontSize, - currentWeight, - fontB()?.name, - ); + // Binary Search to find the maximum characters that fit + while (low <= high) { + const mid = Math.floor((low + high) / 2); + const testFragment = remainingWord.slice(0, mid); - if (Math.max(wA, wB) <= availableWidth) { - bestBreak = mid; - low = mid + 1; - } else { - high = mid - 1; + const wA = measureText( + ctx, + testFragment, + fontSize, + currentWeight, + fontA()?.name, + ); + const wB = measureText( + ctx, + testFragment, + fontSize, + currentWeight, + fontB()?.name, + ); + + if (Math.max(wA, wB) <= availableWidth) { + bestBreak = mid; + low = mid + 1; + } else { + high = mid - 1; + } } - } - pushLine([remainingWord.slice(0, bestBreak)]); - remainingWord = remainingWord.slice(bestBreak); + pushLine([remainingWord.slice(0, bestBreak)]); + remainingWord = remainingWord.slice(bestBreak); + } } } else if (maxWidth > availableWidth && currentLineWords.length > 0) { pushLine(currentLineWords);