/
StyledNativeComponent.js
232 lines (190 loc) 路 7.67 KB
/
StyledNativeComponent.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// @flow
import hoist from 'hoist-non-react-statics';
import React, { createElement, useContext, type Ref } from 'react';
import type {
Attrs,
IInlineStyle,
IStyledNativeComponent,
IStyledNativeStatics,
RuleSet,
ShouldForwardProp,
Target,
} from '../types';
import determineTheme from '../utils/determineTheme';
import { EMPTY_ARRAY, EMPTY_OBJECT } from '../utils/empties';
import generateComponentId from '../utils/generateComponentId';
import generateDisplayName from '../utils/generateDisplayName';
import getComponentName from '../utils/getComponentName';
import isFunction from '../utils/isFunction';
import isStyledComponent from '../utils/isStyledComponent';
import merge from '../utils/mixinDeep';
import { ThemeContext } from './ThemeProvider';
const identifiers = {};
/* We depend on components having unique IDs */
function generateId(displayName?: string, parentComponentId?: string) {
const name = typeof displayName !== 'string' ? 'sc' : escape(displayName);
// Ensure that no displayName can lead to duplicate componentIds
identifiers[name] = (identifiers[name] || 0) + 1;
const componentId = `${name}-${generateComponentId(name + identifiers[name])}`;
return parentComponentId ? `${parentComponentId}-${componentId}` : componentId;
}
function useResolvedAttrs<Config>(theme: any = EMPTY_OBJECT, props: Config, attrs: Attrs) {
// NOTE: can't memoize this
// returns [context, resolvedAttrs]
// where resolvedAttrs is only the things injected by the attrs themselves
const context = { ...props, theme };
const resolvedAttrs = {};
attrs.forEach(attrDef => {
let resolvedAttrDef = attrDef;
let key;
if (isFunction(resolvedAttrDef)) {
resolvedAttrDef = resolvedAttrDef(context);
}
/* eslint-disable guard-for-in */
for (key in resolvedAttrDef) {
context[key] = resolvedAttrs[key] = resolvedAttrDef[key];
}
/* eslint-enable guard-for-in */
});
return [context, resolvedAttrs];
}
// Validator defaults to true if not in HTML/DOM env
const validAttr = () => true;
function useStyledComponentImpl(
forwardedComponent: IStyledNativeComponent,
props: Object,
forwardedRef: Ref<any>
) {
const {
attrs: componentAttrs,
inlineStyle,
defaultProps,
shouldForwardProp,
target,
} = forwardedComponent;
// NOTE: the non-hooks version only subscribes to this when !componentStyle.isStatic,
// but that'd be against the rules-of-hooks. We could be naughty and do it anyway as it
// should be an immutable value, but behave for now.
const theme = determineTheme(props, useContext(ThemeContext), defaultProps);
const [context, attrs] = useResolvedAttrs(theme || EMPTY_OBJECT, props, componentAttrs);
const generatedStyles = inlineStyle.generateStyleObject(context);
const refToForward = forwardedRef;
const elementToBeCreated: Target = attrs.$as || props.$as || attrs.as || props.as || target;
const computedProps = attrs !== props ? { ...props, ...attrs } : props;
const propsForElement = {};
// eslint-disable-next-line guard-for-in
for (const key in computedProps) {
if (key[0] === '$' || key === 'as') continue;
else if (key === 'forwardedAs') {
propsForElement.as = computedProps[key];
} else if (!shouldForwardProp || shouldForwardProp(key, validAttr)) {
propsForElement[key] = computedProps[key];
}
}
propsForElement.style = [generatedStyles].concat(props.style || []);
propsForElement.ref = refToForward;
return createElement(elementToBeCreated, propsForElement);
}
export default (InlineStyle: Class<IInlineStyle>) => {
const createStyledNativeComponent = (
target: $PropertyType<IStyledNativeComponent, 'target'>,
options: {
attrs?: Attrs,
componentId: string,
displayName?: string,
parentComponentId?: string,
shouldForwardProp?: ShouldForwardProp,
},
rules: RuleSet
) => {
const isTargetStyledComp = isStyledComponent(target);
const {
displayName = generateDisplayName(target),
componentId = generateId(options.displayName, options.parentComponentId),
attrs = EMPTY_ARRAY,
} = options;
const styledComponentId =
options.displayName && options.componentId
? `${escape(options.displayName)}-${options.componentId}`
: options.componentId || componentId;
// fold the underlying StyledComponent attrs up (implicit extend)
const finalAttrs =
isTargetStyledComp && ((target: any): IStyledNativeComponent).attrs
? ((target: any): IStyledNativeComponent).attrs.concat(attrs).filter(Boolean)
: attrs;
// eslint-disable-next-line prefer-destructuring
let shouldForwardProp = options.shouldForwardProp;
if (isTargetStyledComp && target.shouldForwardProp) {
if (options.shouldForwardProp) {
// compose nested shouldForwardProp calls
shouldForwardProp = (prop, filterFn) =>
((((target: any): IStyledNativeComponent).shouldForwardProp: any): ShouldForwardProp)(
prop,
filterFn
) && ((options.shouldForwardProp: any): ShouldForwardProp)(prop, filterFn);
} else {
// eslint-disable-next-line prefer-destructuring
shouldForwardProp = ((target: any): IStyledNativeComponent).shouldForwardProp;
}
}
/**
* forwardRef creates a new interim component, which we'll take advantage of
* instead of extending ParentComponent to create _another_ interim class
*/
let WrappedStyledComponent: IStyledNativeComponent;
// eslint-disable-next-line react-hooks/rules-of-hooks
const forwardRef = (props, ref) => useStyledComponentImpl(WrappedStyledComponent, props, ref);
forwardRef.displayName = displayName;
WrappedStyledComponent = ((React.forwardRef(forwardRef): any): IStyledNativeComponent);
WrappedStyledComponent.attrs = finalAttrs;
WrappedStyledComponent.inlineStyle = new InlineStyle(
isTargetStyledComp
? ((target: any): IStyledNativeComponent).inlineStyle.rules.concat(rules)
: rules
);
WrappedStyledComponent.displayName = displayName;
WrappedStyledComponent.shouldForwardProp = shouldForwardProp;
WrappedStyledComponent.styledComponentId = styledComponentId;
// fold the underlying StyledComponent target up since we folded the styles
WrappedStyledComponent.target = isTargetStyledComp
? ((target: any): IStyledNativeComponent).target
: target;
WrappedStyledComponent.withComponent = function withComponent(tag: Target) {
const { componentId: previousComponentId, ...optionsToCopy } = options;
const newComponentId =
previousComponentId && `${previousComponentId}-${escape(getComponentName(tag))}`;
const newOptions = {
...optionsToCopy,
attrs: finalAttrs,
componentId: newComponentId,
};
return createStyledNativeComponent(tag, newOptions, rules);
};
Object.defineProperty(WrappedStyledComponent, 'defaultProps', {
get() {
return this._foldedDefaultProps;
},
set(obj) {
this._foldedDefaultProps = isTargetStyledComp
? merge({}, ((target: any): IStyledNativeComponent).defaultProps, obj)
: obj;
},
});
hoist<
IStyledNativeStatics,
$PropertyType<IStyledNativeComponent, 'target'>,
{ [key: $Keys<IStyledNativeStatics>]: true }
>(WrappedStyledComponent, ((target: any): $PropertyType<IStyledNativeComponent, 'target'>), {
// all SC-specific things should not be hoisted
attrs: true,
inlineStyle: true,
displayName: true,
shouldForwardProp: true,
styledComponentId: true,
target: true,
withComponent: true,
});
return WrappedStyledComponent;
};
return createStyledNativeComponent;
};