Untitled
raw download clone
TYPESCRIPT
views 14
,
size 2464 b
/** @jsx jsx */
import { jsx } from '@emotion/core';
import React from 'react';
import { Fonts, Palette, StyleGuide } from 'styleGuide';
import { getTypographyStyles } from './styles';
import { Assign, AsProps } from '../../typings';

export type TypographyProps<TAs extends React.ReactElement | React.ComponentType<any>> = Assign<
  {
    type?: Fonts;
    component?: TAs | string;
    bold?: boolean;
    upperCase?: boolean;
    color?: Palette;
    inheritColor?: boolean;
    hoverColor?: Palette;
    lineHeight?: number | string;
  } & React.HTMLAttributes<HTMLHeadingElement | HTMLSpanElement | HTMLDivElement | HTMLParagraphElement>,
  AsProps<TAs>
>;

const element = {
  [Fonts.TextH1]: 'h1',
  [Fonts.TextH2]: 'h2',
  [Fonts.TextH3]: 'h3',
  [Fonts.TextH4]: 'h4',
  [Fonts.TextH5]: 'h5',
  [Fonts.TextLink1]: 'span',
  [Fonts.TextLink2]: 'span',
  [Fonts.TextBody]: 'div',
  [Fonts.TextSecondary]: 'div',
  [Fonts.TextSupplementary]: 'span',
  [Fonts.Notification]: 'span',
};

export const Typography = <TAs extends React.ReactElement | React.ComponentType<any>>({
  type = Fonts.TextSecondary,
  component,
  children,
  bold,
  color,
  upperCase,
  hoverColor,
  inheritColor,
  lineHeight = StyleGuide.lineHeight[type],
  ...otherProps
}: TypographyProps<TAs>) => {
  const validProps = {
    ...(otherProps.onClick ? { onClick: otherProps.onClick } : {}),
    ...(otherProps.to ? { to: otherProps.to } : {}),
    ...(otherProps.href ? { href: otherProps.href } : {}),
    ...(otherProps.className ? { className: otherProps.className } : {}),
    ...(otherProps.styles ? { styles: otherProps.styles } : {}),
    ...(otherProps.dangerouslySetInnerHTML ? { dangerouslySetInnerHTML: otherProps.dangerouslySetInnerHTML } : {}),
    ...(otherProps.target ? { target: otherProps.target } : {}),
    ...(otherProps.rel ? { rel: otherProps.rel } : {}),
    ...(otherProps.isExternal ? { isExternal: otherProps.isExternal } : {}),
  };

  const Component = (cProps: any) =>
    component
      ? React.createElement(component as React.ComponentType, cProps)
      : React.createElement(element[type], cProps);

  return (
    <Component
      css={getTypographyStyles({
        type,
        bold,
        color,
        upperCase,
        hoverColor,
        lineHeight,
        inheritColor,
      })}
      {...validProps}
    >
      {children}
    </Component>
  );
};
close fullscreen
Login or Register to edit or fork this paste. It's free.