Skip to content

Commit

Permalink
fix(component): add AspectText component
Browse files Browse the repository at this point in the history
  • Loading branch information
tanmen committed May 2, 2021
1 parent 898f910 commit e279f10
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/aspects/AspectText.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import styled from "@emotion/styled";
import {Story} from "@storybook/react";
import React from "react";
import {AspectText, AspectTextProps} from "./AspectText";

export default {
title: 'AspectText',
component: AspectText
};

export const Default: Story<AspectTextProps & {children?: string}> = (args) => <div style={{height: '50vh'}}>
<AspectText {...args}/>
</div>;
Default.args = {
children: 'Text'
}

export const Styled: Story<AspectTextProps & {children?: string}> = (args) => <div style={{height: '50vh'}}>
<StyledAspectText {...args}/>
</div>;
Styled.args = {
ratio: 70,
children: 'Text'
}

const StyledAspectText = styled(AspectText)`
border: 1em solid #000066;
padding: 5em 0;
`
44 changes: 44 additions & 0 deletions src/aspects/AspectText.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {css} from "@emotion/react";
import styled from "@emotion/styled";
import React, {FC, useEffect, useRef, useState} from "react";

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

/**
* Change fontSize from height
* @param {number | undefined} ratio
* @param {string | undefined} className
* @param {React.ReactElement<any, string | React.JSXElementConstructor<any>> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined} children
* @returns {JSX.Element}
* @constructor
*/
export const AspectText: FC<AspectTextProps> = ({ratio = 100, className, children}) => {
const ref = useRef<HTMLParagraphElement>(null);
const [fontSize, setFontSize] = useState<number | null>(null);
const _ratio = ratio > 100 ? 100 : ratio < 0 ? 0 : ratio;

useEffect(() => {
if (ref.current) {
setFontSize(ref.current.clientHeight * (_ratio / 100));
}
}, [ref.current?.clientHeight, _ratio]);

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

const Box = styled.div`
height: 100%;
`;

const Text = styled.p<{ fontSize: number | null }>`
box-sizing: content-box;
height: 100%;
${({fontSize}) => fontSize && css`font-size: ${fontSize}px`};
`;
1 change: 1 addition & 0 deletions src/aspects/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './Aspect';
export * from './AspectText';

0 comments on commit e279f10

Please sign in to comment.