From 04da2e68fd5263dd6795e4ba6a6dba5046fd0926 Mon Sep 17 00:00:00 2001 From: Cee Chen Date: Fri, 23 Feb 2024 09:44:52 -0800 Subject: [PATCH] [mixins] Memoize typography hooks --- src/global_styling/mixins/_typography.ts | 34 +++++++++++++++++++----- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/src/global_styling/mixins/_typography.ts b/src/global_styling/mixins/_typography.ts index 668f3593ff4..e7268f607e2 100644 --- a/src/global_styling/mixins/_typography.ts +++ b/src/global_styling/mixins/_typography.ts @@ -12,8 +12,15 @@ import { euiFontSizeFromScale, _FontScaleOptions, } from '../functions/typography'; -import { useEuiTheme, UseEuiTheme } from '../../services/theme/hooks'; -import { _EuiThemeFontScale } from '../variables/typography'; +import { + useEuiMemoizedStyles, + useEuiTheme, + UseEuiTheme, +} from '../../services/theme'; +import { + _EuiThemeFontScale, + EuiThemeFontScales, +} from '../variables/typography'; import { logicalCSS } from '../functions'; export type EuiThemeFontSize = { @@ -39,7 +46,22 @@ export const useEuiFontSize = ( options?: _FontScaleOptions ): EuiThemeFontSize => { const euiTheme = useEuiTheme(); - return euiFontSize(euiTheme, scale, options); + const memoizedFontSizes = useEuiMemoizedStyles(euiFontSizes); + + return !options + ? memoizedFontSizes[scale] + : euiFontSize(euiTheme, scale, options); +}; +// Memomize a basic set of font sizes. We unfortunately can't +// memoize all possible options, there's too many permutations +const euiFontSizes = (euiThemeContext: UseEuiTheme) => { + return EuiThemeFontScales.reduce( + (map, scale) => ({ + ...map, + [scale]: euiFontSize(euiThemeContext, scale), + }), + {} as Record<_EuiThemeFontScale, EuiThemeFontSize> + ); }; /** @@ -71,7 +93,5 @@ export const euiTextTruncate = ( export const euiNumberFormat = ({ euiTheme }: UseEuiTheme) => ` font-feature-settings: ${euiTheme.font.featureSettings}, 'tnum' 1; `; -export const useEuiNumberFormat = (): string => { - const euiTheme = useEuiTheme(); - return euiNumberFormat(euiTheme); -}; +export const useEuiNumberFormat = (): string => + useEuiMemoizedStyles(euiNumberFormat);