-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
WrappedText.js
82 lines (72 loc) · 2.52 KB
/
WrappedText.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import _ from 'underscore';
import React, {Fragment} from 'react';
import {View} from 'react-native';
import PropTypes from 'prop-types';
import styles from '../../styles/styles';
import Text from '../Text';
/**
* Breaks the text into matrix
* for eg: My Name is Rajat
* [
* [My,' ',Name,' ',' ',is,' ',Rajat],
* ]
*
* @param {String} text
* @returns {Array<String[]>}
*/
function getTextMatrix(text) {
return _.map(text.split('\n'), row => _.without(row.split(/(\s)/), ''));
}
const propTypes = {
/** Required text */
children: PropTypes.string.isRequired,
/** Style to be applied to Text */
// eslint-disable-next-line react/forbid-prop-types
textStyles: PropTypes.arrayOf(PropTypes.object),
/** Style for each word(Token) in the text, remember that token also includes whitespaces among words */
// eslint-disable-next-line react/forbid-prop-types
wordStyles: PropTypes.arrayOf(PropTypes.object),
};
const defaultProps = {
textStyles: [],
wordStyles: [],
};
const WrappedText = (props) => {
if (!_.isString(props.children)) {
return null;
}
const textMatrix = getTextMatrix(props.children);
return (
<>
{_.map(textMatrix, (rowText, rowIndex) => (
<Fragment
// eslint-disable-next-line react/no-array-index-key
key={`${rowText}-${rowIndex}`}
>
{_.map(rowText, (colText, colIndex) => (
// Outer View is important to vertically center the Text
<View
// eslint-disable-next-line react/no-array-index-key
key={`${colText}-${colIndex}`}
style={styles.codeWordWrapper}
>
<View
style={[
props.wordStyles,
colIndex === 0 && styles.codeFirstWordStyle,
colIndex === rowText.length - 1 && styles.codeLastWordStyle,
]}
>
<Text style={props.textStyles}>{colText}</Text>
</View>
</View>
))}
</Fragment>
))}
</>
);
};
WrappedText.propTypes = propTypes;
WrappedText.defaultProps = defaultProps;
WrappedText.displayName = 'WrappedText';
export default WrappedText;