-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathformatPropValue.js
More file actions
78 lines (64 loc) · 1.98 KB
/
formatPropValue.js
File metadata and controls
78 lines (64 loc) · 1.98 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* @flow */
import { isPlainObject } from 'is-plain-object';
import { isValidElement } from 'react';
import type { Options } from './../options';
import parseReactElement from './../parser/parseReactElement';
import formatComplexDataStructure from './formatComplexDataStructure';
import formatFunction from './formatFunction';
import formatTreeNode from './formatTreeNode';
const escape = (s: string): string => s.replace(/"/g, '"');
const formatPropValue = (
propValue: any,
inline: boolean,
lvl: number,
options: Options
): string => {
if (typeof propValue === 'number') {
return `{${String(propValue)}}`;
}
if (typeof propValue === 'string') {
return `"${escape(propValue)}"`;
}
// > "Symbols (new in ECMAScript 2015, not yet supported in Flow)"
// @see: https://flow.org/en/docs/types/primitives/
// $FlowFixMe: Flow does not support Symbol
if (typeof propValue === 'symbol') {
const symbolDescription = propValue
.valueOf()
.toString()
.replace(/Symbol\((.*)\)/, '$1');
if (!symbolDescription) {
return `{Symbol()}`;
}
return `{Symbol('${symbolDescription}')}`;
}
if (typeof propValue === 'function') {
return `{${formatFunction(propValue, options)}}`;
}
if (isValidElement(propValue)) {
return `{${formatTreeNode(
parseReactElement(propValue, options),
true,
lvl,
options
)}}`;
}
// handle forwardRef and memo
if (isPlainObject(propValue) && propValue.$$typeof) {
return `{${propValue.displayName ||
propValue.type?.name ||
propValue.render?.name ||
'Component'}}`;
}
if (propValue instanceof Date) {
if (isNaN(propValue.valueOf())) {
return `{new Date(NaN)}`;
}
return `{new Date("${propValue.toISOString()}")}`;
}
if (isPlainObject(propValue) || Array.isArray(propValue)) {
return `{${formatComplexDataStructure(propValue, inline, lvl, options)}}`;
}
return `{${String(propValue)}}`;
};
export default formatPropValue;