Skip to content

Commit

Permalink
fix(AspectText): changed the target of css to outer to take padding i…
Browse files Browse the repository at this point in the history
…nto account
  • Loading branch information
tanmen committed May 7, 2021
1 parent 7f8c070 commit f0f0b1d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
6 changes: 5 additions & 1 deletion src/aspects/AspectText.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Default.args = {
}

export const Styled: Story<AspectTextProps & {children?: string}> = (args) => <div style={{height: '50vh'}}>
<StyledAspectText {...args}/>
<StyledAspectText {...args} textStyle={{backgroundColor: '#fff'}}/>
</div>;
Styled.args = {
ratio: 50,
Expand All @@ -26,4 +26,8 @@ Styled.args = {
const StyledAspectText = styled(AspectText)`
border: 10px solid #000066;
padding: 50px 0;
display: flex;
justify-content: center;
align-items: center;
background-color: #7f7f7f;
`
18 changes: 11 additions & 7 deletions src/aspects/AspectText.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import {css} from "@emotion/react";
import styled from "@emotion/styled";
import React, {FC, useEffect, useRef, useState} from "react";
import React, {CSSProperties, FC, useEffect, useRef, useState} from "react";
import {useResizeObserver} from "../hooks/useResizeObserver";

export type AspectTextProps = {
ratio?: number
className?: string;
textStyle?: CSSProperties
}

/**
Expand All @@ -16,33 +17,36 @@ export type AspectTextProps = {
* @returns {JSX.Element}
* @constructor
*/
export const AspectText: FC<AspectTextProps> = ({ratio = 100, className, children}) => {
export const AspectText: FC<AspectTextProps> = ({ratio = 100, className, textStyle,children}) => {
const ref = useRef<HTMLParagraphElement>(null);
const [height, setHeight] = useState<number | null>();
const [fontSize, setFontSize] = useState<number | null>(null);
const _ratio = ratio > 100 ? 100 : ratio < 0 ? 0 : ratio;

useResizeObserver((elm) => setHeight(elm.clientHeight), ref);
useResizeObserver((elm) => {
const {paddingTop, paddingBottom} = getComputedStyle(elm);
setHeight(elm.clientHeight - Number(paddingTop.replace('px', '')) - Number(paddingBottom.replace('px', '')));
}, ref);

useEffect(() => {
if (height) {
console.log(height);
setFontSize(height * (_ratio / 100));
}
}, [height, _ratio]);

return <Box>
<Text ref={ref} className={className} fontSize={fontSize}>
return <Box ref={ref} className={className}>
<Text fontSize={fontSize} style={textStyle}>
{children}
</Text>
</Box>;
};

const Box = styled.div`
box-sizing: content-box;
height: 100%;
`;

const Text = styled.p<{ fontSize: number | null }>`
box-sizing: content-box;
height: 100%;
${({fontSize}) => fontSize && css`font-size: ${fontSize}px`};
`;

0 comments on commit f0f0b1d

Please sign in to comment.