Created
December 18, 2019 19:18
-
-
Save likern/6e2da0bbe21fd0a7f7b4255d4537eb6e to your computer and use it in GitHub Desktop.
Text component which treats lineHeight as multiplier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react" | |
import { Text as ReactNativeText, StyleProp, TextStyle } from 'react-native' | |
import { NoExtraProperties, hasDefinedProperty, isArray, isObject } from "../types"; | |
interface TextProps { | |
style?: StyleProp<TextStyle>; | |
children: string; | |
} | |
/** In our application fontFamily is required */ | |
/** because we don't use default fonts */ | |
/** Our fonts are: Gilroy-* */ | |
function isTextStyle<T extends TextStyle>(style: unknown): style is NoExtraProperties<TextStyle, T> { | |
if (isObject(style)) { | |
return style.hasOwnProperty("fontFamily") | |
} | |
return false; | |
} | |
function isTextStyleArray<T extends TextStyle>(style: any): style is NoExtraProperties<TextStyle, T>[] { | |
return isArray<TextStyle>(style, param => isTextStyle(param)) | |
} | |
/** FIXME Make fontFamily a required property */ | |
const CustomText = ({ style, children, ...otherProps }: TextProps) => { | |
let styles: TextStyle[] = []; | |
let lineHeight: number | null = null; | |
let fontSize: number | null = null; | |
let absLineHeight: number | null = null; | |
if (isTextStyle(style)) { | |
styles.push(style) | |
} else if (isTextStyleArray(style)) { | |
styles = style; | |
} | |
for (const textStyle of styles) { | |
if (hasDefinedProperty(textStyle, "lineHeight")) lineHeight = textStyle.lineHeight; | |
if (hasDefinedProperty(textStyle, "fontSize")) fontSize = textStyle.fontSize; | |
} | |
// console.assert(fontSize !== null, `[${CustomText.name}] fontSize can't be null`) | |
if (lineHeight !== null && fontSize !== null) { | |
absLineHeight = fontSize * lineHeight; | |
} | |
if (absLineHeight != null) { | |
styles.push({ lineHeight: absLineHeight }); | |
} | |
console.debug(`[${CustomText.name}] newLineHeight: ${absLineHeight}, fontSize: ${fontSize}, lineHeight: ${lineHeight}`) | |
return ( | |
<ReactNativeText style={styles} {...otherProps}>{children}</ReactNativeText> | |
// <ReactNativeText style={{backgroundColor: "black"}} {...otherProps}>{children}</ReactNativeText> | |
// <Text>React Native Text</Text> | |
) | |
} | |
export default CustomText; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment