-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathformatProp.js
More file actions
78 lines (69 loc) · 2.36 KB
/
Copy pathformatProp.js
File metadata and controls
78 lines (69 loc) · 2.36 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 spacer from './spacer';
import formatPropValue from './formatPropValue';
import formatComplexDataStructure from './formatComplexDataStructure';
import type { Options } from './../options';
const isValidJSXPropName = (propName: string): boolean =>
/^[$A-Z_a-z][$\w-]*$/.test(propName);
export default (
name: string,
hasValue: boolean,
value: any,
hasDefaultValue: boolean,
defaultValue: any,
inline: boolean,
lvl: number,
options: Options
): {
attributeFormattedInline: string,
attributeFormattedMultiline: string,
isMultilineAttribute: boolean,
} => {
if (!hasValue && !hasDefaultValue) {
throw new Error(
`The prop "${name}" has no value and no default: could not be formatted`
);
}
const usedValue = hasValue ? value : defaultValue;
const { useBooleanShorthandSyntax, tabStop } = options;
const hasValidJSXPropName = isValidJSXPropName(name);
const formattedPropValue = hasValidJSXPropName
? formatPropValue(usedValue, inline, lvl, options)
: null;
let attributeFormattedInline = ' ';
let attributeFormattedMultiline = `\n${spacer(lvl + 1, tabStop)}`;
let attributePayload = '';
if (
useBooleanShorthandSyntax &&
formattedPropValue === '{false}' &&
!hasDefaultValue
) {
// If a boolean is false and not different from it's default, we do not render the attribute
attributeFormattedInline = '';
attributeFormattedMultiline = '';
} else if (!hasValidJSXPropName) {
const formattedObjectSpreadValue = `{...${formatComplexDataStructure(
{ [name]: usedValue },
true,
lvl,
options
)}}`;
attributePayload = formattedObjectSpreadValue;
attributeFormattedInline += formattedObjectSpreadValue;
attributeFormattedMultiline += formattedObjectSpreadValue;
} else if (useBooleanShorthandSyntax && formattedPropValue === '{true}') {
attributePayload = `${name}`;
attributeFormattedInline += `${name}`;
attributeFormattedMultiline += `${name}`;
} else {
attributePayload = `${name}=${String(formattedPropValue)}`;
attributeFormattedInline += `${name}=${String(formattedPropValue)}`;
attributeFormattedMultiline += `${name}=${String(formattedPropValue)}`;
}
const isMultilineAttribute = attributePayload.includes('\n');
return {
attributeFormattedInline,
attributeFormattedMultiline,
isMultilineAttribute,
};
};