forked from akveo/react-native-ui-kitten
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstyleConsumer.service.ts
267 lines (213 loc) · 8.78 KB
/
styleConsumer.service.ts
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import {
ControlMetaType,
ControlThemedStyleType,
ThemedStyleType,
} from '@eva-design/dss';
import { StyledComponentProps } from './styled';
import {
Interaction,
StyleService,
StyleType,
} from './style.service';
import { ThemeType } from '../theme/theme.service';
const SEPARATOR_MAPPING_ENTRY: string = '.';
interface StyleInfo {
appearance: string;
variants: string[];
states: string[];
}
export class StyleConsumerService {
private readonly name: string;
private readonly meta: ControlMetaType;
constructor(name: string, style: StyleType) {
this.name = name;
this.meta = this.safe(style[name], (generatedConfig): ControlMetaType => {
return generatedConfig.meta;
});
if (!this.meta) {
const docRoot: string = 'https://akveo.github.io/react-native-ui-kitten/docs';
const message: string = [
`\n${this.name}: unsupported configuration.`,
'Using UI Kitten components is only possible with configuring ApplicationProvider.',
`📖 Documentation: ${docRoot}/guides/getting-started#manual-installation`,
'\nIn case you have all in place, there might be an incorrect usage of a "styled" function.',
`📖 Documentation: ${docRoot}/design-system/custom-component-mapping`,
].join('\n');
console.error(message);
}
}
public createDefaultProps<P extends object>(): StyledComponentProps {
const appearance: string = this.getDefaultAppearance();
const variants: { [key: string]: string } = this.getDefaultVariants();
const states: { [key: string]: boolean } = this.getDefaultStates();
return { appearance, ...variants, ...states };
}
public withStyledProps<P extends object>(source: P,
style: StyleType,
theme: ThemeType,
interaction: Interaction[]): P & StyledComponentProps {
const styleInfo: StyleInfo = this.getStyleInfo(source, interaction);
const generatedMapping: StyleType = this.getGeneratedStyleMapping(style, styleInfo);
if (!generatedMapping) {
const docRoot: string = 'https://akveo.github.io/react-native-ui-kitten/docs';
const message: string = [
`${this.name}: unsupported configuration.`,
`Check one of the following prop values ${JSON.stringify(styleInfo, null, 2)}`,
`📖 Documentation: ${docRoot}/components/${this.name.toLowerCase()}/api`,
].join('\n');
console.warn(message);
return this.withStyledProps({ ...source, ...this.createDefaultProps() }, style, theme, interaction);
}
const mapping: StyleType = this.withValidParameters(generatedMapping);
const themedStyle: StyleType = StyleService.createThemedEntry(mapping, theme);
return { ...source, theme, themedStyle };
}
private getGeneratedStyleMapping<P extends StyledComponentProps>(style: StyleType, info: StyleInfo): StyleType {
return this.safe(style[this.name], (componentStyles: ControlThemedStyleType): ThemedStyleType => {
const styleKeys: string[] = Object.keys(componentStyles.styles);
const query: string = this.findGeneratedQuery(info, styleKeys);
return componentStyles.styles[query];
});
}
private withValidParameters(mapping: StyleType): StyleType {
const invalidParameters: string[] = [];
Object.keys(mapping).forEach((key: string) => {
if (!Object.keys(this.meta.parameters).includes(key)) {
invalidParameters.push(key);
delete mapping[key];
}
});
if (invalidParameters.length !== 0) {
const docRoot: string = 'https://akveo.github.io/react-native-ui-kitten/docs';
const message: string = [
`${this.name}: unsupported configuration.`,
`Unable to apply ${invalidParameters}`,
'There might be an incorrect usage of mapping',
`📖 Documentation: ${docRoot}/design-system/custom-component-mapping`,
].join('\n');
console.warn(message);
}
return mapping;
}
private getStyleInfo<P extends StyledComponentProps>(props: P,
interaction: Interaction[]): StyleInfo {
const variantProps: Partial<P> = this.getDerivedVariants(this.meta, props);
const stateProps: Partial<P> = this.getDerivedStates(this.meta, props);
const variants: string[] = Object.keys(variantProps).map((variant: string): string => {
return variantProps[variant];
});
const states: string[] = Object.keys(stateProps);
return {
appearance: props.appearance,
variants: variants,
states: [...states, ...interaction],
};
}
private getDefaultAppearance(): string {
const matches: string[] = Object.keys(this.meta.appearances).filter((appearance: string): boolean => {
return this.meta.appearances[appearance].default === true;
});
return matches[matches.length - 1];
}
private getDefaultVariants(): { [key: string]: any } {
return this.transformObject(this.meta.variantGroups, (variants, group: string): string | undefined => {
return Object.keys(variants[group]).find((variant: string): boolean => {
return variants[group][variant].default === true;
});
});
}
private getDefaultStates(): { [key: string]: any } {
return this.transformObject(this.meta.states, (states, state: string): boolean | undefined => {
const isDefault: boolean = states[state].default === true;
return isDefault ? isDefault : undefined;
});
}
private getDerivedVariants<P extends StyledComponentProps>(meta: ControlMetaType, props: P): Partial<P> {
return this.transformObject(props, (p: P, prop: string): string | undefined => {
const isVariant: boolean = Object.keys(meta.variantGroups).includes(prop);
return isVariant ? p[prop] : undefined;
});
}
private getDerivedStates<P extends StyledComponentProps>(meta: ControlMetaType, props: P): Partial<P> {
return this.transformObject(props, (p: P, prop: string): boolean => {
const isState: boolean = Object.keys(meta.states).includes(prop);
const isAssigned: boolean = p[prop] === true;
return isState && isAssigned;
});
}
/**
* Iterates throw `value` object keys and fills it values with values provided by `transform` callback
* If `transform` returns `undefined`, then appends nothing
*
* @param value (V extends object) - object to transform
* @param transform - object key transformation callback
*/
private transformObject<V extends object>(value: V, transform: (value: V, key: string) => any): Partial<V> {
return Object.keys(value).reduce((acc: Partial<V>, key: string): any => {
const nextValue: any = transform(value, key);
return nextValue ? {
...acc,
[key]: nextValue,
} : acc;
}, {});
}
/**
* Finds identical keys across `source` keys array
*
* Example:
*
* source = ['default.error.small.checked', ...]
* info = { appearance: 'default', variants: ['small', 'error'], states: ['checked'] }
*
* will return ['default', 'error', 'small', 'checked']
*
* @param info (StyleInfo) - component style info
* @param source (string[]) - array of style keys
*
* @return (string | undefined) - key identical to some of `source` keys if presents
*/
private findGeneratedQuery(info: StyleInfo, source: string[]): string | undefined {
const query: string[] = [
info.appearance,
...info.variants,
...info.states,
];
const matches: string[] = source.filter((key: string): boolean => {
const keyQuery: string[] = key.split(SEPARATOR_MAPPING_ENTRY);
return this.compareArrays(query, keyQuery);
});
return matches[0];
}
/**
* @param lhs (string[]) - comparable array
* @param rhs (string[]) - comparing array
*
* @return true if all of lhs keys are included in rhs
*/
private compareArrays(lhs: string[], rhs: string[]): boolean {
if (lhs.length !== rhs.length) {
return false;
}
return lhs.reduce((acc: boolean, current: string): boolean => acc && rhs.includes(current), true);
}
/**
* Safely retrieves R value of T object with reducer
*
* @param value (T | undefined) - unsafe object which should be processed
* @param reducer ((T) => R) - `value` processing lambda. Called if `value` is not `undefined`
* @param fallback (R) - fallback value to return. Optional
*
* @return (R | undefined) - object returned by `reducer` if `value` is not `undefined`, `fallback` otherwise
**/
private safe<T, R>(value: T | undefined, reducer: (value: T) => R, fallback?: R): R | undefined {
if (value) {
return reducer(value);
}
return fallback;
}
}