From e0336328040129c3342dfcccee5a385cf620e070 Mon Sep 17 00:00:00 2001 From: Aaron Dodson Date: Wed, 11 Sep 2024 14:25:23 -0700 Subject: [PATCH 1/2] fix: size text with computed styles even when hidden --- core/utils/dom.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/core/utils/dom.ts b/core/utils/dom.ts index e318e7e915e..6cbb05dd9d3 100644 --- a/core/utils/dom.ts +++ b/core/utils/dom.ts @@ -210,7 +210,13 @@ export function getTextWidth(textElement: SVGTextElement): number { // Attempt to compute fetch the width of the SVG text element. try { - width = textElement.getComputedTextLength(); + const style = window.getComputedStyle(textElement); + width = getFastTextWidthWithSizeString( + textElement, + style.fontSize, + style.fontWeight, + style.fontFamily, + ); } catch (e) { // In other cases where we fail to get the computed text. Instead, use an // approximation and do not cache the result. At some later point in time From 65d8528c78457434ad7f7dd2299065df45f226e0 Mon Sep 17 00:00:00 2001 From: Aaron Dodson Date: Wed, 11 Sep 2024 14:37:37 -0700 Subject: [PATCH 2/2] refactor: remove unneeded try/catch. --- core/utils/dom.ts | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/core/utils/dom.ts b/core/utils/dom.ts index 6cbb05dd9d3..87019dbb2de 100644 --- a/core/utils/dom.ts +++ b/core/utils/dom.ts @@ -208,22 +208,14 @@ export function getTextWidth(textElement: SVGTextElement): number { } } - // Attempt to compute fetch the width of the SVG text element. - try { - const style = window.getComputedStyle(textElement); - width = getFastTextWidthWithSizeString( - textElement, - style.fontSize, - style.fontWeight, - style.fontFamily, - ); - } catch (e) { - // In other cases where we fail to get the computed text. Instead, use an - // approximation and do not cache the result. At some later point in time - // when the block is inserted into the visible DOM, this method will be - // called again and, at that point in time, will not throw an exception. - return textElement.textContent!.length * 8; - } + // Compute the width of the SVG text element. + const style = window.getComputedStyle(textElement); + width = getFastTextWidthWithSizeString( + textElement, + style.fontSize, + style.fontWeight, + style.fontFamily, + ); // Cache the computed width and return. if (cacheWidths) {