Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(PPDSC-1866): handle string line height #643

Merged
merged 3 commits into from
Feb 17, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/utils/__tests__/text-crop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,28 @@ describe('textCrop', () => {
expect(textCrop(cropData)).toEqual(expectedResult);
});

test(`handles lineHeight number as string to support legacy theme json`, () => {
const cropData: TextCropProps = {
fontSize: '12px',
lineHeight: '1.6',
fontMetrics: exampleFontMetrics,
};

const expectedResult: TextCropResults = {
'::after': {content: "''", display: 'block', marginTop: '-0.465em'},
'::before': {
content: "''",
display: 'block',
marginBottom: '-0.443em',
},
fontSize: '12px',
lineHeight: '19.2px',
padding: '0.5px 0px',
};

expect(textCrop(cropData)).toEqual(expectedResult);
});

test(`throws an error if invalid fontSize units passed`, () => {
const cropData: TextCropProps = {
fontSize: '12metres' as TextCropProps['fontSize'],
Expand Down
15 changes: 11 additions & 4 deletions src/utils/text-crop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ type FontUnit = 'px' | 'rem';

export type TextCropProps = {
fontSize: `${number}${FontUnit}`;
lineHeight: number;
lineHeight: number | string;
fontMetrics: {
capHeight: number;
ascent: number;
Expand Down Expand Up @@ -79,8 +79,15 @@ export const textCrop = ({
fontSize,
fontMetrics,
}: TextCropProps): TextCropResults => {
if (typeof lineHeight !== 'number') {
throw Error(`invalid lineHeight: ${lineHeight}`);
let parsedLineHeight: number;
if (typeof lineHeight === 'string') {
const match = lineHeight.match(/^\d+(\.\d+)*$/);
if (!match) {
throw Error(`invalid lineHeight: ${lineHeight}`);
}
parsedLineHeight = parseFloat(lineHeight);
} else {
parsedLineHeight = lineHeight;
}

const match = fontSize.match(/(\d+(?:\.\d+)?)(px|rem)/);
Expand All @@ -89,7 +96,7 @@ export const textCrop = ({
}
const fontSizeAsNumber = parseFloat(match[1]);
const fontSizeUnits = match[2] as FontUnit;
const leading = lineHeight * fontSizeAsNumber;
const leading = parsedLineHeight * fontSizeAsNumber;

const capsizeStyles = createStyleObject({
fontSize: fontSizeAsNumber,
Expand Down