From 2cebe96ca26482706d1ce40ae71bf8cf479b9692 Mon Sep 17 00:00:00 2001 From: Sean Lynch Date: Mon, 9 Jun 2025 22:58:31 -0400 Subject: [PATCH] fix(Text): Performance improvement by only determining word width if `width` prop defined (for word wrapping) --- .changeset/warm-women-glow.md | 5 ++ .../layerchart/src/lib/components/Text.svelte | 49 +++++++++++-------- 2 files changed, 33 insertions(+), 21 deletions(-) create mode 100644 .changeset/warm-women-glow.md diff --git a/.changeset/warm-women-glow.md b/.changeset/warm-women-glow.md new file mode 100644 index 000000000..c7edca8e3 --- /dev/null +++ b/.changeset/warm-women-glow.md @@ -0,0 +1,5 @@ +--- +'layerchart': patch +--- + +fix(Text): Performance improvement by only determining word width if `width` prop defined (for word wrapping) diff --git a/packages/layerchart/src/lib/components/Text.svelte b/packages/layerchart/src/lib/components/Text.svelte index 9a5aa1da8..4a87c76ee 100644 --- a/packages/layerchart/src/lib/components/Text.svelte +++ b/packages/layerchart/src/lib/components/Text.svelte @@ -281,27 +281,34 @@ // Split each line into words const words = line.split(/(?:(?!\u00A0+)\s+)/); - // Handle word wrapping within each line - return words.reduce((result: { words: string[]; width?: number }[], item) => { - const currentLine = result[result.length - 1]; - const itemWidth = getStringWidth(item, style) || 0; - - if ( - currentLine && - (width == null || scaleToFit || (currentLine.width || 0) + itemWidth + spaceWidth < width) - ) { - // Word can be added to an existing line - currentLine.words.push(item); - currentLine.width = currentLine.width || 0; - currentLine.width += itemWidth + spaceWidth; - } else { - // Add first word to line or word is too long to scaleToFit on existing line - const newLine = { words: [item], width: itemWidth }; - result.push(newLine); - } - - return result; - }, []); + if (width == null) { + // No width specified, only use explicit line breaks (if used) + return [{ words }]; + } else { + // Handle word wrapping within each line + return words.reduce((result: { words: string[]; width?: number }[], item) => { + const currentLine = result[result.length - 1]; + const itemWidth = getStringWidth(item, style) || 0; + + if ( + currentLine && + (width == null || + scaleToFit || + (currentLine.width || 0) + itemWidth + spaceWidth < width) + ) { + // Word can be added to an existing line + currentLine.words.push(item); + currentLine.width = currentLine.width || 0; + currentLine.width += itemWidth + spaceWidth; + } else { + // Add first word to line or word is too long to scaleToFit on existing line + const newLine = { words: [item], width: itemWidth }; + result.push(newLine); + } + + return result; + }, []); + } }); });