-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathuseNativeCss.ts
More file actions
204 lines (176 loc) · 5.44 KB
/
useNativeCss.ts
File metadata and controls
204 lines (176 loc) · 5.44 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
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
/* eslint-disable */
import {
createElement,
Fragment,
useContext,
useEffect,
useState,
type ComponentType,
} from "react";
import { Pressable, View } from "react-native";
import { VariableContext } from "react-native-css/style-collection";
import type { StyledConfiguration } from "../../runtime.types";
import { testGuards, type RenderGuard } from "../conditions/guards";
import {
cleanupEffect,
ContainerContext,
type ContainerContextValue,
type Effect,
type Getter,
type VariableContextValue,
} from "../reactivity";
import { animatedComponentFamily } from "../reanimated";
import { getStyledProps, stylesFamily } from "../styles";
import { updateRules } from "./rules";
export type Config = {
source: string;
target: string[] | string | false;
nativeStyleMapping?: Record<string, string>;
};
export type ComponentState = {
/** The source/target for classNames */
configs: Config[];
/** Reactive tracking */
ruleEffect: Effect;
ruleEffectGetter: Getter;
styleEffect: Effect;
/** The components props */
currentProps?: Record<string, any> | undefined | null;
/** An observable of the normal/important props */
stylesObs?: ReturnType<typeof stylesFamily>;
guards?: RenderGuard[];
variables?: VariableContextValue;
containers?: ContainerContextValue;
inheritedVariables: VariableContextValue;
inheritedContainers: ContainerContextValue;
animated?: boolean;
pressable?: undefined | boolean;
};
/**
* useNativeCss is the native implementation of the useCssElement hook.
*/
export function useNativeCss(
type: ComponentType<any>,
originalProps: Record<string, any> | undefined | null,
configs: Config[] = [{ source: "className", target: "style" }],
) {
const inheritedVariables = useContext(VariableContext);
const inheritedContainers = useContext(ContainerContext);
const [state, setState] = useState((): ComponentState => {
// Both effects share the same observers to improve memory usage
const observers = new Set<Effect>();
/**
* When fired, this effect will force the rules to be re-evaluated.
* This will cause a re-render if there are different rules
*
* Use this when a rule condition changes, e.g FastRefresh or media queries
*/
const ruleEffect: Effect = {
observers,
run: () => setState((state) => updateRules(state)),
};
/**
* When fired, this effect will force a re-render of the component.
* This will cause a re-fetch of the styles.
*
* Use this when a value changes, e.g vm units or light / dark mode
*/
const styleEffect: Effect = {
observers,
run: () => setState((state) => ({ ...state })),
};
return updateRules(
{
ruleEffect,
ruleEffectGetter: (observable) => observable.get(ruleEffect),
styleEffect,
configs,
inheritedContainers,
inheritedVariables,
pressable: type === View ? false : undefined,
},
originalProps,
inheritedVariables,
inheritedContainers,
false,
false,
);
});
// Both effects share the same observers, so we only need to cleanup one of them
useEffect(() => () => cleanupEffect(state.ruleEffect), [state.ruleEffect]);
// Check if our derived state has changed (e.g the className prop)
if (
testGuards(state, originalProps, inheritedVariables, inheritedContainers)
) {
/**
* Get the new state
* Note, this might result in the same styles, but the guards will now be different
*/
setState(
updateRules(
state,
originalProps,
inheritedVariables,
inheritedContainers,
true,
),
);
// We can bail on rendering as the result of this render will be discarded
return createElement(Fragment);
}
let props = getStyledProps(state, originalProps);
if (type === View && props?.onPress) {
type = Pressable;
}
if (state.animated) {
type = animatedComponentFamily(type);
}
if (state.variables) {
props = {
value: state.variables,
children: createElement(type, props),
};
type = VariableContext.Provider;
}
if (state.containers) {
props = {
value: state.containers,
children: createElement(type, props),
};
type = ContainerContext.Provider;
}
return createElement(type, props);
}
/**
* Convert the styled() mapping to a config array
*/
export function mappingToConfig(mapping: StyledConfiguration<any>) {
return Object.entries(mapping).flatMap(([key, value]): Config => {
if (value === true) {
return { source: key, target: key };
} else if (value === false) {
return { source: key, target: false };
} else if (typeof value === "string") {
return { source: key, target: value.split(".") };
} else if (typeof value === "object") {
if (Array.isArray(value)) {
return { source: key, target: value };
}
if ("target" in value) {
if (value.target === false) {
return { source: key, target: false };
} else if (typeof value.target === "string") {
const target = value.target.split(".");
if (target.length === 1) {
return { source: key, target: target[0]! };
} else {
return { source: key, target };
}
} else if (Array.isArray(value.target)) {
return { source: key, target: value.target };
}
}
}
throw new Error(`styled(): Invalid mapping for ${key}: ${value}`);
});
}