-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathrules.ts
More file actions
326 lines (279 loc) · 10.1 KB
/
rules.ts
File metadata and controls
326 lines (279 loc) · 10.1 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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/* eslint-disable */
import type { InlineVariable, StyleRule } from "../../../compiler";
import { getDeepPath } from "../../utils";
import { testRule } from "../conditions";
import { DEFAULT_CONTAINER_NAME } from "../conditions/container-query";
import type { RenderGuard } from "../conditions/guards";
import { StyleCollection } from "../injection";
import {
activeFamily,
containerLayoutFamily,
focusFamily,
hoverFamily,
VAR_SYMBOL,
weakFamily,
type VariableContextValue,
} from "../reactivity";
import { stylesFamily } from "../styles";
import type { ComponentState, Config } from "./useNativeCss";
export const INLINE_RULE_SYMBOL = Symbol("react-native-css.inlineRule");
export function updateRules(
state: ComponentState,
// Either update the state with new props or use the current props
currentProps = state.currentProps,
inheritedVariables = state.inheritedVariables,
inheritedContainers = state.inheritedContainers,
forceUpdate = false,
isRerender = true,
): ComponentState {
const guards: RenderGuard[] = [];
const rules = new Set<StyleRule | InlineVariable | VariableContextValue>();
if (forceUpdate) {
state = { ...state, guards, currentProps };
}
let usesVariables = false;
let variables = state.variables ? inheritedVariables : undefined;
let containers = state.containers ? inheritedContainers : undefined;
const inlineVariables = new Set<InlineVariable>();
let animated = false;
for (const config of state.configs) {
const source = currentProps?.[config.source];
const shallowTarget = Array.isArray(config.target)
? config.target[0]
: config.target;
guards.push(["a", config.source, source]);
if (shallowTarget) {
guards.push(["a", shallowTarget, currentProps?.[shallowTarget]]);
}
const styleRuleSet = [];
if (typeof source === "string") {
const classNames = source.split(/\s+/);
for (const className of classNames) {
styleRuleSet.push(
...StyleCollection.styles(className).get(state.ruleEffect),
);
}
}
const target = getDeepPath(currentProps, config.target);
if (target) {
if (Array.isArray(target)) {
for (const item of target) {
if (VAR_SYMBOL in item) {
inlineVariables.add(item);
} else if (
INLINE_RULE_SYMBOL in item &&
typeof item[INLINE_RULE_SYMBOL] === "string"
) {
pushInlineRule(state, item, styleRuleSet);
}
}
} else if (
config.target &&
typeof target === "object" &&
target &&
VAR_SYMBOL in target
) {
inlineVariables.add(target);
} else if (
INLINE_RULE_SYMBOL in target &&
typeof target[INLINE_RULE_SYMBOL] === "string"
) {
pushInlineRule(state, target, styleRuleSet);
}
}
for (let rule of styleRuleSet) {
// Even if a rule does not match, make sure we register that it could set
// a variable or container or be animated.
if (rule.v) usesVariables = true;
if (rule.c) containers ??= inheritedContainers;
if (rule.a) animated = true;
usesVariables ||= Boolean(rule.dv);
if (
!testRule(
rule,
state.ruleEffect,
currentProps,
guards,
inheritedContainers,
)
) {
continue;
}
if (rule.v) {
// We're going to set a value, so we need to create a new object
if (variables === inheritedVariables) {
variables = { ...inheritedVariables };
} else {
variables ??= { ...inheritedVariables };
}
for (const v of rule.v) {
variables![v[0]] = v[1];
}
}
if (rule.c) {
// We're going to set a value, so we need to create a new object
if (containers === inheritedContainers) {
containers = {
...inheritedContainers,
// This container becomes the default container
[DEFAULT_CONTAINER_NAME]: state.ruleEffect,
};
}
// This this component as the named container
for (const name of rule.c) {
containers![name] = state.ruleEffect;
}
// Enable hover/active/focus/layout handlers
hoverFamily(state.ruleEffect);
activeFamily(state.ruleEffect);
focusFamily(state.ruleEffect);
containerLayoutFamily(state.ruleEffect);
}
if (rule.a) {
animated = true;
}
// Rules normally target style. If the target is not style, we need to create a new rule.
if (config.target !== "style") {
rule = getRuleVariation(rule)(config);
}
// Add the rule to the set and update the hash
rules.add(rule);
}
if (process.env.NODE_ENV !== "production") {
if (isRerender) {
let pressable = activeFamily.has(state.ruleEffect);
if (Boolean(variables) !== Boolean(state.variables)) {
console.log(
`ReactNativeCss: className '${source}' added or removed a variable after the initial render. This causes the components state to be reset and all children be re-mounted. Use the className 'will-change-variable' to avoid this warning. If this was caused by sibling components being added/removed, use a 'key' prop so React can track the component correctly.`,
);
} else if (Boolean(containers) !== Boolean(state.containers)) {
console.log(
`ReactNativeCss: className '${source}' added or removed a container after the initial render. This causes the components state to be reset and all children be re-mounted. This will cause unexpected behavior. Use the className 'will-change-container' to avoid this warning. If this was caused by sibling components being added/removed, use a 'key' prop so React can track the component correctly.`,
);
} else if (animated !== state.animated) {
console.log(
`ReactNativeCss: className '${source}' added or removed an animation after the initial render. This causes the components state to be reset and all children be re-mounted. This will cause unexpected behavior. Use the className 'will-change-animation' to avoid this warning. If this was caused by sibling components being added/removed, use a 'key' prop so React can track the component correctly.`,
);
} else if (pressable !== state.pressable) {
console.log(
`ReactNativeCss: className '${source}' added or removed a pressable state after the initial render. This causes the components state to be reset and all children be re-mounted. This will cause unexpected behavior. Use the className 'will-change-pressable' to avoid this warning. If this was caused by sibling components being added/removed, use a 'key' prop so React can track the component correctly.`,
);
}
}
}
}
// We only track this in development
let pressable =
process.env.NODE_ENV === "production"
? undefined
: activeFamily.has(state.ruleEffect);
if (!rules.size && !state.stylesObs && !inlineVariables.size) {
return {
...state,
currentProps,
guards,
animated,
pressable,
};
}
if (usesVariables || variables) {
rules.add(inheritedVariables);
if (inlineVariables.size) {
variables = Object.assign(
{},
variables,
inheritedVariables,
...Array.from(inlineVariables),
{ [VAR_SYMBOL]: true },
);
}
for (const variable of inlineVariables) {
rules.add(variable);
}
}
// Generate a StyleObservable for this unique set of rules / variables
const stylesObs = stylesFamily(generateStateHash(state, rules), rules);
// Get the guards without subscribing to the observable
// We will subscribe within the render using the StyleEffect
guards.push(...stylesObs.get().guards);
// If these are the same styles with no inline variables, we can skip the update
if (state.stylesObs === stylesObs && !inlineVariables.size) {
return state;
}
// Remove this component from the old observer
state.stylesObs?.cleanup(state.ruleEffect);
return {
...state,
currentProps,
stylesObs,
variables,
containers,
guards,
animated,
pressable,
};
}
/**
* Create variations of a style rule based on the config.
* Cache for reference equality.
*/
const getRuleVariation = weakFamily((rule: StyleRule) => {
return weakFamily((config: Config): StyleRule => {
return { ...rule, target: config.target };
});
});
function pushInlineRule(
state: ComponentState,
item: any,
styleRuleSet: StyleRule[],
) {
for (const className of item[INLINE_RULE_SYMBOL].split(/\s+/)) {
let inlineRuleSet = StyleCollection.styles(className).get(state.ruleEffect);
for (let rule of inlineRuleSet) {
styleRuleSet.push(rule);
}
}
}
/**
* Get a unique number for a weak key.
*/
let hashKeyCount = 0;
const hashKeyFamily = weakFamily(() => hashKeyCount++);
export function generateStateHash(
state: ComponentState,
iterableKeys?: Iterable<WeakKey>,
variables?: WeakKey,
inlineVars?: Set<WeakKey>,
): string {
if (!iterableKeys) {
return "";
}
const keys = [state.configs, ...iterableKeys];
if (variables) {
keys.push(variables);
}
if (inlineVars) {
keys.push(...inlineVars);
}
return generateHash(keys);
}
/**
* Quickly generate a unique hash for a set of numbers.
* This is not a cryptographic hash, but it is fast and has a low chance of collision.
*/
const MOD = 9007199254740871; // Largest prime within safe integer range 2^53
const PRIME = 31; // A smaller prime for mixing
export function generateHash(keys: WeakKey[]): string {
let hash = 0;
let product = 1; // Used for mixing to enhance uniqueness
for (const key of keys) {
if (!key) continue; // Skip if key is undefined
const num = hashKeyFamily(key);
hash = (hash ^ num) % MOD; // XOR and modular arithmetic
product = (product * (num + PRIME)) % MOD; // Mix with multiplication
}
// Combine hash and product to form the final hash
hash = (hash + product) % MOD;
// Return the hash as a string
return hash.toString(36);
}