|
| 1 | +import { getAliasToken } from '../../utils'; |
| 2 | +import { RdTypographyTitleProps } from './types'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Calculates the visual height (in pixels) of a Typography Title component |
| 6 | + * based on its `level` prop, using the corresponding `fontSize` and `lineHeight` |
| 7 | + * token values from the theme (either component-specific or global). |
| 8 | + * |
| 9 | + * If an invalid level is provided (not from 1 to 5), it falls back to using |
| 10 | + * the level 1 (`fontSizeHeading1` and `lineHeightHeading1`) as default. |
| 11 | + * |
| 12 | + * @param level - The `level` prop of a `Typography.Title` component (typically from 1 to 5). |
| 13 | + * @returns The computed height in pixels (number), calculated as `fontSize * lineHeight`. |
| 14 | + * |
| 15 | + * @example |
| 16 | + * ```ts |
| 17 | + * const h1Height = detectHeightByLevel(1); |
| 18 | + * console.log(h1Height); // Example: 42 (depending on token values) |
| 19 | + * |
| 20 | + * const invalidHeight = detectHeightByLevel(); |
| 21 | + * console.log(invalidHeight); // Fallbacks to heading1 height |
| 22 | + * ``` |
| 23 | + */ |
| 24 | +export const detectHeightByLevel = (level: RdTypographyTitleProps['level']) => { |
| 25 | + // Detect fontSize and lineHeight based on `level` prop |
| 26 | + let detectedFontSize: number | null = null; |
| 27 | + let detectedLineHeight: number | null = null; |
| 28 | + |
| 29 | + switch (level) { |
| 30 | + case 1: |
| 31 | + detectedFontSize = getAliasToken('Typography', 'fontSizeHeading1') as number; |
| 32 | + detectedLineHeight = getAliasToken('Typography', 'lineHeightHeading1') as number; |
| 33 | + break; |
| 34 | + case 2: |
| 35 | + detectedFontSize = getAliasToken('Typography', 'fontSizeHeading2') as number; |
| 36 | + detectedLineHeight = getAliasToken('Typography', 'lineHeightHeading2') as number; |
| 37 | + break; |
| 38 | + case 3: |
| 39 | + detectedFontSize = getAliasToken('Typography', 'fontSizeHeading3') as number; |
| 40 | + detectedLineHeight = getAliasToken('Typography', 'lineHeightHeading3') as number; |
| 41 | + break; |
| 42 | + case 4: |
| 43 | + detectedFontSize = getAliasToken('Typography', 'fontSizeHeading4') as number; |
| 44 | + detectedLineHeight = getAliasToken('Typography', 'lineHeightHeading4') as number; |
| 45 | + break; |
| 46 | + case 5: |
| 47 | + detectedFontSize = getAliasToken('Typography', 'fontSizeHeading5') as number; |
| 48 | + detectedLineHeight = getAliasToken('Typography', 'lineHeightHeading5') as number; |
| 49 | + break; |
| 50 | + default: |
| 51 | + // fallback to level 1 if the level is invalid |
| 52 | + detectedFontSize = getAliasToken('Typography', 'fontSizeHeading1') as number; |
| 53 | + detectedLineHeight = getAliasToken('Typography', 'lineHeightHeading1') as number; |
| 54 | + } |
| 55 | + |
| 56 | + const detectedHeight = detectedFontSize * detectedLineHeight; |
| 57 | + |
| 58 | + return detectedHeight; |
| 59 | +}; |
0 commit comments