|
@@ -0,0 +1,73 @@
|
|
1
|
+/* @flow */
|
|
2
|
+
|
|
3
|
+declare type StyleSheet = Object;
|
|
4
|
+
|
|
5
|
+/**
|
|
6
|
+ * The list of the well-known style properties which may not be numbers on Web
|
|
7
|
+ * but must be numbers on React Native.
|
|
8
|
+ *
|
|
9
|
+ * @private
|
|
10
|
+ */
|
|
11
|
+const _WELL_KNOWN_NUMBER_PROPERTIES = [ 'height', 'width' ];
|
|
12
|
+
|
|
13
|
+/* eslint-disable flowtype/space-before-type-colon */
|
|
14
|
+
|
|
15
|
+/**
|
|
16
|
+ * Create a style sheet using the provided style definitions.
|
|
17
|
+ *
|
|
18
|
+ * @param {StyleSheet} styles - A dictionary of named style definitions.
|
|
19
|
+ * @param {StyleSheet} [overrides={}] - Optional set of additional (often
|
|
20
|
+ * platform-dependent/specific) style definitions that will override the base
|
|
21
|
+ * (often platform-independent) styles.
|
|
22
|
+ * @returns {StyleSheet}
|
|
23
|
+ */
|
|
24
|
+export function createStyleSheet(styles: StyleSheet, overrides: StyleSheet = {})
|
|
25
|
+ : StyleSheet {
|
|
26
|
+
|
|
27
|
+/* eslint-enable flowtype/space-before-type-colon */
|
|
28
|
+
|
|
29
|
+ const combinedStyles = {};
|
|
30
|
+
|
|
31
|
+ for (const k of Object.keys(styles)) {
|
|
32
|
+ combinedStyles[k]
|
|
33
|
+ = _shimStyles({
|
|
34
|
+ ...styles[k],
|
|
35
|
+ ...overrides[k]
|
|
36
|
+ });
|
|
37
|
+ }
|
|
38
|
+
|
|
39
|
+ return combinedStyles;
|
|
40
|
+}
|
|
41
|
+
|
|
42
|
+/**
|
|
43
|
+ * Shims style properties to work correctly on native. Allows us to minimize the
|
|
44
|
+ * number of style declarations that need to be set or overridden for specific
|
|
45
|
+ * platforms.
|
|
46
|
+ *
|
|
47
|
+ * @param {StyleSheet} styles - An object which represents a stylesheet.
|
|
48
|
+ * @private
|
|
49
|
+ * @returns {StyleSheet}
|
|
50
|
+ */
|
|
51
|
+function _shimStyles<T: StyleSheet>(styles: T): T {
|
|
52
|
+ // Certain style properties may not be numbers on Web but must be numbers on
|
|
53
|
+ // React Native. For example, height and width may be expressed in percent
|
|
54
|
+ // on Web but React Native will not understand them and we will get errors
|
|
55
|
+ // (at least during development). Convert such well-known properties to
|
|
56
|
+ // numbers if possible; otherwise, remove them to avoid runtime errors.
|
|
57
|
+ for (const k of _WELL_KNOWN_NUMBER_PROPERTIES) {
|
|
58
|
+ const v = styles[k];
|
|
59
|
+ const typeofV = typeof v;
|
|
60
|
+
|
|
61
|
+ if (typeofV !== 'undefined' && typeofV !== 'number') {
|
|
62
|
+ const numberV = Number(v);
|
|
63
|
+
|
|
64
|
+ if (Number.isNaN(numberV)) {
|
|
65
|
+ delete styles[k];
|
|
66
|
+ } else {
|
|
67
|
+ styles[k] = numberV;
|
|
68
|
+ }
|
|
69
|
+ }
|
|
70
|
+ }
|
|
71
|
+
|
|
72
|
+ return styles;
|
|
73
|
+}
|