From 4baab3378099f9c1d5f2e2f9a3ae790cd5923d84 Mon Sep 17 00:00:00 2001 From: Alber EE <122263897+Alber-Writer@users.noreply.github.com> Date: Tue, 12 Nov 2024 14:18:38 +0100 Subject: [PATCH] switch method to canvas context approach --- .../tabsbar/business/calc-text-width.ts | 34 ++++++------------- 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/src/common/components/mock-components/front-rich-components/tabsbar/business/calc-text-width.ts b/src/common/components/mock-components/front-rich-components/tabsbar/business/calc-text-width.ts index 91535f05..f83a5fbe 100644 --- a/src/common/components/mock-components/front-rich-components/tabsbar/business/calc-text-width.ts +++ b/src/common/components/mock-components/front-rich-components/tabsbar/business/calc-text-width.ts @@ -1,30 +1,16 @@ export const calcTextWidth = ( inputText: string, fontSize: number, - _fontfamily: string + fontfamily: string ) => { - const REGX_DEFS = { - LOWERCASE_BIG: /[mwoq]/, - LOWERCASE: /[a-z0-9]/, - UPPERCASE_BIG: /[MWOQ]/, - UPPERCASE: /[A-Z]/, - MARKS: /[.,;:!?'"(){}\[\]\-]/, - SPACE: /\s/, - DEFAULT: 'default', - }; + // Creates an invisible canvas to perform the measurement + let canvas = document.createElement('canvas'); + const context = canvas.getContext('2d'); - const calcLength = [...inputText].reduce((sum, current) => { - const testChar = (regx: RegExp) => regx.test(current); - const addLength = (value: number) => sum + fontSize * value; - - if (testChar(REGX_DEFS.LOWERCASE_BIG)) return addLength(0.85); - if (testChar(REGX_DEFS.LOWERCASE)) return addLength(0.5); - if (testChar(REGX_DEFS.SPACE)) return addLength(0.2); - if (testChar(REGX_DEFS.UPPERCASE_BIG)) return addLength(0.95); - if (testChar(REGX_DEFS.UPPERCASE)) return addLength(0.7); - if (testChar(REGX_DEFS.MARKS)) return addLength(0.3); - return addLength(0.5); - }, 0); - - return calcLength; + if (context) { + context.font = `${fontSize}px ${fontfamily}`; + return context.measureText(inputText).width; + } + const charAverageWidth = fontSize * 0.7; + return inputText.length * charAverageWidth + charAverageWidth * 0.8; };