-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.jsx
97 lines (78 loc) · 2 KB
/
index.jsx
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
88
89
90
91
92
93
94
95
96
import React, { Component } from 'react';
var nargs = /\{([0-9a-zA-Z_]+)\}/g;
function getPositions(string, values) {
const postion = [];
string.replace(nargs, function replaceArg(match, capture, index) {
if (
!(
string[index - 1] === "{" &&
string[index + match.length] === "}"
)
) {
postion.push({
startIndex: index,
endIndex: index + match.length,
match: match,
capture: capture,
value: values[capture]
})
}
});
return postion
}
function parseEscape (str){
return str.replace(nargs, function replaceArg(match, capture, index) {
if (
str[index - 1] === "{" &&
str[index + match.length] === "}"
) {
return capture
}
return match
});
}
export function template (
str,
values,
renderNoMatch = ()=> "",
){
const arr = [];
const positions = getPositions(str, values);
if(positions.length < 1){
arr.push({ type: 'general', value: str });
}else {
let lastIndex = 0;
positions.forEach((p)=>{
const { startIndex, endIndex, value } = p;
const general = str.substring(lastIndex, startIndex);
arr.push({ type: 'general', value: general });
if(value){
arr.push({ type: 'var', value: value });
}else {
arr.push({ type: 'var', value: renderNoMatch(str, p), isNoMatch: true });
}
lastIndex = endIndex;
});
arr.push({ type:'general', value: str.substring(lastIndex) });
}
const parsedArr = arr.map((node)=>{
const { type, value } = node;
if(type === 'general' && typeof value === 'string'){
return parseEscape(value);
}
return value
});
return parsedArr;
}
export default class ReactStringTemplate extends Component {
render() {
const { str, values, renderNoMatch, children } = this.props;
return children(template(str, values, renderNoMatch));
}
}
ReactStringTemplate.defaultProps = {
str: '',
values: {},
renderNoMatch : () => '',
children: arr => arr,
}