-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathformatTreeNode.js
More file actions
63 lines (50 loc) · 1.46 KB
/
formatTreeNode.js
File metadata and controls
63 lines (50 loc) · 1.46 KB
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
/* @flow */
import formatReactElementNode from './formatReactElementNode';
import formatReactFragmentNode from './formatReactFragmentNode';
import formatReactPortalNode from './formatReactPortalNode';
import type { Options } from './../options';
import type { TreeNode } from './../tree';
const jsxStopChars = ['<', '>', '{', '}'];
const shouldBeEscaped = (s: string) =>
jsxStopChars.some(jsxStopChar => s.includes(jsxStopChar));
const escape = (s: string) => {
if (!shouldBeEscaped(s)) {
return s;
}
return `{\`${s}\`}`;
};
const preserveTrailingSpace = (s: string) => {
let result = s;
if (result.endsWith(' ')) {
result = result.replace(/^(.*?)(\s+)$/, "$1{'$2'}");
}
if (result.startsWith(' ')) {
result = result.replace(/^(\s+)(.*)$/, "{'$1'}$2");
}
return result;
};
export default (
node: TreeNode,
inline: boolean,
lvl: number,
options: Options
): string => {
if (node.type === 'number') {
return String(node.value);
}
if (node.type === 'string') {
return node.value
? `${preserveTrailingSpace(escape(String(node.value)))}`
: '';
}
if (node.type === 'ReactElement') {
return formatReactElementNode(node, inline, lvl, options);
}
if (node.type === 'ReactFragment') {
return formatReactFragmentNode(node, inline, lvl, options);
}
if (node.type === 'ReactPortal') {
return formatReactPortalNode(node, inline, lvl, options);
}
throw new TypeError(`Unknow format type "${node.type}"`);
};