|
| 1 | +import React, {forwardRef, useEffect} from 'react' |
1 | 2 | import styled from 'styled-components' |
2 | 3 | import {get} from './constants' |
| 4 | +import {useRefObjectAsForwardedRef} from './hooks' |
3 | 5 | import sx, {SxProp} from './sx' |
4 | 6 | import {ComponentProps} from './utils/types' |
| 7 | +import {ForwardRefComponent as PolymorphicForwardRefComponent} from './utils/polymorphic' |
5 | 8 |
|
6 | | -const Heading = styled.h2<SxProp>` |
| 9 | +type StyledHeadingProps = { |
| 10 | + as?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' |
| 11 | +} & SxProp |
| 12 | + |
| 13 | +const StyledHeading = styled.h2<StyledHeadingProps>` |
7 | 14 | font-weight: ${get('fontWeights.bold')}; |
8 | 15 | font-size: ${get('fontSizes.5')}; |
9 | 16 | margin: 0; |
10 | 17 | ${sx}; |
11 | 18 | ` |
| 19 | +const Heading = forwardRef(({as: Component = 'h2', ...props}, forwardedRef) => { |
| 20 | + const innerRef = React.useRef<HTMLHeadingElement>(null) |
| 21 | + useRefObjectAsForwardedRef(forwardedRef, innerRef) |
| 22 | + |
| 23 | + if (__DEV__) { |
| 24 | + /** |
| 25 | + * The Linter yells because it thinks this conditionally calls an effect, |
| 26 | + * but since this is a compile-time flag and not a runtime conditional |
| 27 | + * this is safe, and ensures the entire effect is kept out of prod builds |
| 28 | + * shaving precious bytes from the output, and avoiding mounting a noop effect |
| 29 | + */ |
| 30 | + // eslint-disable-next-line react-hooks/rules-of-hooks |
| 31 | + useEffect(() => { |
| 32 | + if (innerRef.current && !(innerRef.current instanceof HTMLHeadingElement)) { |
| 33 | + // eslint-disable-next-line no-console |
| 34 | + console.warn('This Heading component should be an instanceof of h1-h6') |
| 35 | + } |
| 36 | + }, [innerRef]) |
| 37 | + } |
| 38 | + |
| 39 | + return ( |
| 40 | + <StyledHeading |
| 41 | + as={Component} |
| 42 | + {...props} |
| 43 | + // @ts-ignore shh |
| 44 | + ref={innerRef} |
| 45 | + /> |
| 46 | + ) |
| 47 | +}) as PolymorphicForwardRefComponent<'h2', StyledHeadingProps> |
| 48 | + |
| 49 | +Heading.displayName = 'Heading' |
12 | 50 |
|
13 | 51 | export type HeadingProps = ComponentProps<typeof Heading> |
14 | 52 | export default Heading |
0 commit comments