-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathParsedText.js
87 lines (70 loc) · 2.18 KB
/
ParsedText.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
83
84
85
86
87
import React from 'react';
import ReactNative from 'react-native';
import TextExtraction from './lib/TextExtraction';
const PATTERNS = {
url: /(https?:\/\/|www\.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/i,
phone: /[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}/,
email: /\S+@\S+\.\S+/,
};
const defaultParseShape = React.PropTypes.shape({
...ReactNative.Text.propTypes,
type: React.PropTypes.oneOf(Object.keys(PATTERNS)).isRequired,
});
const customParseShape = React.PropTypes.shape({
...ReactNative.Text.propTypes,
pattern: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.instanceOf(RegExp)]).isRequired,
});
class ParsedText extends React.Component {
static displayName = 'ParsedText';
static propTypes = {
...ReactNative.Text.propTypes,
parse: React.PropTypes.arrayOf(
React.PropTypes.oneOfType([defaultParseShape, customParseShape]),
),
childrenProps: React.PropTypes.shape(ReactNative.Text.propTypes),
};
static defaultProps = {
parse: null,
childrenProps: {},
};
setNativeProps(nativeProps) {
this._root.setNativeProps(nativeProps);
}
getPatterns() {
return this.props.parse.map((option) => {
const {type, ...patternOption} = option;
if (type) {
if (!PATTERNS[type]) {
throw new Error(`${option.type} is not a supported type`);
}
patternOption.pattern = PATTERNS[type];
}
return patternOption;
});
}
getParsedText() {
if (!this.props.parse) { return this.props.children; }
if (typeof this.props.children !== 'string') { return this.props.children; }
const textExtraction = new TextExtraction(this.props.children, this.getPatterns());
return textExtraction.parse().map((props, index) => {
return (
<ReactNative.Text
key={`parsedText-${index}`}
{...this.props.childrenProps}
{...props}
/>
);
});
}
render() {
return (
<ReactNative.Text
ref={ref => this._root = ref}
{...this.props}
>
{this.getParsedText()}
</ReactNative.Text>
);
}
}
export default ParsedText;