|
| 1 | +/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 2 | +import clsx from 'clsx'; |
| 3 | +import React, { forwardRef, HTMLAttributes, ReactNode } from 'react'; |
| 4 | + |
| 5 | +export enum TypographyVariant { |
| 6 | + H1, |
| 7 | + H2, |
| 8 | + H3, |
| 9 | + H4, |
| 10 | + H5, |
| 11 | + H6, |
| 12 | + P1, |
| 13 | + P2, |
| 14 | + P3, |
| 15 | + P4, |
| 16 | + P5, |
| 17 | + P6, |
| 18 | +} |
| 19 | + |
| 20 | +const tagByVariant: Record<TypographyVariant, 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p'> = { |
| 21 | + [TypographyVariant.H1]: 'h1', |
| 22 | + [TypographyVariant.H2]: 'h2', |
| 23 | + [TypographyVariant.H3]: 'h3', |
| 24 | + [TypographyVariant.H4]: 'h4', |
| 25 | + [TypographyVariant.H5]: 'h5', |
| 26 | + [TypographyVariant.H6]: 'h6', |
| 27 | + [TypographyVariant.P1]: 'p', |
| 28 | + [TypographyVariant.P2]: 'p', |
| 29 | + [TypographyVariant.P3]: 'p', |
| 30 | + [TypographyVariant.P4]: 'p', |
| 31 | + [TypographyVariant.P5]: 'p', |
| 32 | + [TypographyVariant.P6]: 'p', |
| 33 | +}; |
| 34 | + |
| 35 | +const variantClasses: Record<TypographyVariant, string> = { |
| 36 | + [TypographyVariant.H1]: 'text-h1', |
| 37 | + [TypographyVariant.H2]: 'text-h2', |
| 38 | + [TypographyVariant.H3]: 'text-h3', |
| 39 | + [TypographyVariant.H4]: 'text-h4', |
| 40 | + [TypographyVariant.H5]: 'text-h5', |
| 41 | + [TypographyVariant.H6]: 'text-h6', |
| 42 | + [TypographyVariant.P1]: 'text-p1', |
| 43 | + [TypographyVariant.P2]: 'text-p2', |
| 44 | + [TypographyVariant.P3]: 'text-p3', |
| 45 | + [TypographyVariant.P4]: 'text-p4', |
| 46 | + [TypographyVariant.P5]: 'text-p5', |
| 47 | + [TypographyVariant.P6]: 'text-p6', |
| 48 | +}; |
| 49 | + |
| 50 | +interface BaseProps { |
| 51 | + children?: ReactNode; |
| 52 | + text?: ReactNode; |
| 53 | + variant?: TypographyVariant; |
| 54 | + className?: string; |
| 55 | + truncate?: boolean; |
| 56 | + noWrap?: boolean; |
| 57 | +} |
| 58 | + |
| 59 | +export interface TypographyProps extends BaseProps, HTMLAttributes<HTMLElement> {} |
| 60 | + |
| 61 | +export const Typography = forwardRef<HTMLElement, TypographyProps>( |
| 62 | + ( |
| 63 | + { variant = TypographyVariant.P1, className, children, text, truncate, noWrap, ...rest }, |
| 64 | + ref, |
| 65 | + ) => { |
| 66 | + const Tag = tagByVariant[variant]; |
| 67 | + const classes = clsx( |
| 68 | + variantClasses[variant], |
| 69 | + truncate && 'truncate', |
| 70 | + noWrap && !truncate && 'whitespace-nowrap', |
| 71 | + className, |
| 72 | + ); |
| 73 | + |
| 74 | + return ( |
| 75 | + <Tag className={classes} data-variant={TypographyVariant[variant]} ref={ref as any} {...rest}> |
| 76 | + {children ?? text} |
| 77 | + </Tag> |
| 78 | + ); |
| 79 | + }, |
| 80 | +); |
0 commit comments