vitest-native 0.14.0-rc.9 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +76 -60
  2. package/dist/cli.d.mts +1 -3
  3. package/dist/cli.mjs +175 -63
  4. package/dist/context.d.mts +45 -0
  5. package/dist/context.mjs +243 -0
  6. package/dist/errors.d.mts +3 -0
  7. package/dist/helpers.cjs +53 -4
  8. package/dist/helpers.d.cts +1 -3
  9. package/dist/helpers.d.mts +1 -3
  10. package/dist/helpers.mjs +2 -3
  11. package/dist/host-5o48Ujzs.mjs +939 -0
  12. package/dist/{index-CzQazgp9.d.cts → index-DqU4YO3D.d.mts} +27 -49
  13. package/dist/index.d.mts +1 -3
  14. package/dist/index.mjs +463 -595
  15. package/dist/jest-compat/error-equality.mjs +127 -0
  16. package/dist/jest-compat/jest-object.mjs +149 -4
  17. package/dist/jest-compat/node-registry.mjs +233 -58
  18. package/dist/jest-compat/setup.mjs +28 -4
  19. package/dist/jest-compat.cjs +227 -52
  20. package/dist/jest-compat.d.cts +5 -6
  21. package/dist/jest-compat.d.mts +5 -6
  22. package/dist/jest-compat.mjs +204 -52
  23. package/dist/matchers.cjs +1 -2
  24. package/dist/matchers.d.cts +0 -2
  25. package/dist/matchers.d.mts +0 -2
  26. package/dist/matchers.mjs +1 -2
  27. package/dist/{memory-FYbP0_gg.mjs → memory-Couw0Esx.mjs} +31 -6
  28. package/dist/native/assets.d.mts +2 -0
  29. package/dist/native/assets.mjs +34 -0
  30. package/dist/native/babel-toolchain.mjs +190 -0
  31. package/dist/native/babel-worker.mjs +47 -0
  32. package/dist/native/boundary.mjs +23 -8
  33. package/dist/native/compile-cache.mjs +21 -9
  34. package/dist/native/coverage-v8.mjs +287 -0
  35. package/dist/native/esm-interop.mjs +216 -0
  36. package/dist/native/expo-native-modules.mjs +7 -1
  37. package/dist/native/globals.mjs +104 -6
  38. package/dist/native/hooks.mjs +271 -60
  39. package/dist/native/loader.mjs +378 -20
  40. package/dist/native/match.d.mts +24 -2
  41. package/dist/native/match.mjs +117 -12
  42. package/dist/native/metro-profile-compiler.mjs +2 -31
  43. package/dist/native/module-reset.mjs +37 -5
  44. package/dist/native/native-modules.d.mts +2 -3
  45. package/dist/native/native-modules.mjs +22 -21
  46. package/dist/native/ownership.d.mts +10 -0
  47. package/dist/native/ownership.mjs +96 -9
  48. package/dist/native/registry-compiler.mjs +6 -0
  49. package/dist/native/registry.mjs +138 -119
  50. package/dist/native/resident-health.mjs +133 -0
  51. package/dist/native/resolve.d.mts +6 -0
  52. package/dist/native/resolve.mjs +100 -9
  53. package/dist/native/rntl-hooks.mjs +157 -6
  54. package/dist/native/rntl-text-host.mjs +64 -0
  55. package/dist/native/runner.mjs +73 -0
  56. package/dist/native/setup.mjs +96 -70
  57. package/dist/native/state-manifest.mjs +14 -8
  58. package/dist/native/transform.d.mts +2 -0
  59. package/dist/native/transform.mjs +476 -59
  60. package/dist/native/worker.mjs +65 -36
  61. package/dist/{pool-DjpOjOf3.mjs → pool-CFSpNfyw.mjs} +37 -11
  62. package/dist/{preset-map-BlBriTA0.mjs → preset-map-CogjYmSw.mjs} +4 -19
  63. package/dist/preset-modules.mjs +2 -11
  64. package/dist/{presets--zrEWQC2.mjs → presets-CXDyg51l.mjs} +65 -82
  65. package/dist/presets.d.mts +1 -1
  66. package/dist/presets.mjs +1 -1
  67. package/dist/report-error.d.mts +20 -0
  68. package/dist/report-error.mjs +145 -0
  69. package/dist/rntl-support.d.mts +12 -0
  70. package/dist/rntl-support.mjs +189 -0
  71. package/dist/{rolldown-runtime-BhDjJH2R.mjs → rolldown-runtime-D70C1uOS.mjs} +1 -2
  72. package/dist/serializer.cjs +1 -2
  73. package/dist/serializer.d.cts +1 -3
  74. package/dist/serializer.d.mts +1 -3
  75. package/dist/serializer.mjs +1 -2
  76. package/dist/setup.mjs +95 -156
  77. package/dist/{worker-vitest-BGPo0ek6.mjs → worker-vitest-CILPFeRX.mjs} +2 -3
  78. package/docs/migrating-from-jest.md +76 -12
  79. package/docs/release-readiness.md +1 -1
  80. package/package.json +119 -102
  81. package/CHANGELOG.md +0 -2491
  82. package/dist/cli.cjs +0 -1951
  83. package/dist/cli.d.cts +0 -3
  84. package/dist/ecosystem-D6e1OVOg.mjs +0 -1019
  85. package/dist/ecosystem-MFwkbnaC.cjs +0 -1099
  86. package/dist/errors-B3lJK46O.cjs +0 -75
  87. package/dist/errors-CxoBUfVJ.mjs +0 -64
  88. package/dist/index-xw43lBlv.d.mts +0 -481
  89. package/dist/memory-6EPHrJA1.cjs +0 -144
  90. package/dist/pool-B4yesGhI.cjs +0 -121
  91. package/dist/preset-map-jSFsNy1Q.cjs +0 -241
  92. package/dist/preset-modules-BoLkaeEN.cjs +0 -53
  93. package/dist/preset-modules-CG8-G82P.mjs +0 -36
  94. package/dist/presets-9f83H0WW.cjs +0 -3939
  95. package/dist/rolldown-runtime-C0BPl7ul.cjs +0 -43
  96. package/dist/worker-vitest-BfiQB8ND.cjs +0 -62
  97. package/docs/hot-default-design.md +0 -216
@@ -1,3939 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
- const require_errors = require("./errors-B3lJK46O.cjs");
3
- let node_fs = require("node:fs");
4
- node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
5
- let node_path = require("node:path");
6
- node_path = require_rolldown_runtime.__toESM(node_path, 1);
7
- let node_module = require("node:module");
8
- let vitest = require("vitest");
9
- let react = require("react");
10
- react = require_rolldown_runtime.__toESM(react, 1);
11
- //#region src/presets/built-in.ts
12
- /**
13
- * Marks the presets vitest-native's own factories return. A test worker rebuilds a
14
- * built-in preset from its name, so an object that only shares the name, such as a
15
- * copy extended with modules of its own, would get the built-in's modules there; the
16
- * plugin refuses one without the mark. The mark is non-enumerable, so a spread copy
17
- * does not carry it, and its symbol is registered, so it holds across copies of this
18
- * module (an ESM and a CommonJS build loaded side by side).
19
- */
20
- const BUILT_IN_PRESET = Symbol.for("vitest-native.built-in-preset");
21
- function builtInPreset(preset) {
22
- Object.defineProperty(preset, BUILT_IN_PRESET, { value: preset.name });
23
- return preset;
24
- }
25
- //#endregion
26
- //#region src/presets/reanimated.ts
27
- /**
28
- * Resolve the *active* React Native module — the mock under `engine: 'mock'`
29
- * (intercepted by the CJS bridge) or real RN under `engine: 'native'` (served by
30
- * the Node loader hooks). Cached. Lets the reanimated mock's `Animated.View`
31
- * &co. wrap whichever RN component set is live, so the preset is engine-agnostic.
32
- */
33
- let _rnCache = null;
34
- function getRN$1() {
35
- if (_rnCache) return _rnCache;
36
- try {
37
- const base = node_path.default.join(process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd(), "package.json");
38
- _rnCache = (0, node_module.createRequire)(base)("react-native");
39
- } catch {
40
- _rnCache = {};
41
- }
42
- return _rnCache;
43
- }
44
- function reanimated() {
45
- return builtInPreset({
46
- name: "reanimated",
47
- modules: { "react-native-reanimated": {
48
- exports: [
49
- "useSharedValue",
50
- "useAnimatedStyle",
51
- "useAnimatedProps",
52
- "useDerivedValue",
53
- "useAnimatedScrollHandler",
54
- "useAnimatedGestureHandler",
55
- "useAnimatedReaction",
56
- "useAnimatedKeyboard",
57
- "useReducedMotion",
58
- "useFrameCallback",
59
- "withTiming",
60
- "withSpring",
61
- "withDecay",
62
- "withSequence",
63
- "withDelay",
64
- "withRepeat",
65
- "runOnJS",
66
- "runOnUI",
67
- "createAnimatedComponent",
68
- "addWhitelistedUIProps",
69
- "addWhitelistedNativeProps",
70
- "configureProps",
71
- "Easing",
72
- "FadeIn",
73
- "FadeOut",
74
- "FadeInDown",
75
- "FadeInUp",
76
- "FadeInLeft",
77
- "FadeInRight",
78
- "FadeOutDown",
79
- "FadeOutUp",
80
- "FadeOutLeft",
81
- "FadeOutRight",
82
- "SlideInRight",
83
- "SlideInLeft",
84
- "SlideInUp",
85
- "SlideInDown",
86
- "SlideOutRight",
87
- "SlideOutLeft",
88
- "SlideOutUp",
89
- "SlideOutDown",
90
- "ZoomIn",
91
- "ZoomOut",
92
- "BounceIn",
93
- "BounceOut",
94
- "BounceInDown",
95
- "BounceInUp",
96
- "BounceInLeft",
97
- "BounceInRight",
98
- "FlipInEasyX",
99
- "FlipInEasyY",
100
- "FlipOutEasyX",
101
- "FlipOutEasyY",
102
- "LightSpeedInLeft",
103
- "LightSpeedInRight",
104
- "LightSpeedOutLeft",
105
- "LightSpeedOutRight",
106
- "PinwheelIn",
107
- "PinwheelOut",
108
- "StretchInX",
109
- "StretchInY",
110
- "StretchOutX",
111
- "StretchOutY",
112
- "RotateInDownLeft",
113
- "RotateInDownRight",
114
- "RotateInUpLeft",
115
- "RotateInUpRight",
116
- "RotateOutDownLeft",
117
- "RotateOutDownRight",
118
- "RotateOutUpLeft",
119
- "RotateOutUpRight",
120
- "Layout",
121
- "LinearTransition",
122
- "SequencedTransition",
123
- "FadingTransition",
124
- "JumpingTransition",
125
- "CurvedTransition",
126
- "EntryExitTransition",
127
- "interpolate",
128
- "Extrapolation",
129
- "useAnimatedRef",
130
- "measure",
131
- "scrollTo",
132
- "cancelAnimation",
133
- "makeMutable",
134
- "SharedTransition",
135
- "ReduceMotion",
136
- "KeyboardState"
137
- ],
138
- factory: () => {
139
- function createSharedValue(init) {
140
- const listeners = /* @__PURE__ */ new Map();
141
- const sv = {
142
- value: init,
143
- get() {
144
- return sv.value;
145
- },
146
- set(value) {
147
- sv.value = typeof value === "function" ? value(sv.value) : value;
148
- listeners.forEach((fn) => fn(sv.value));
149
- },
150
- addListener(id, listener) {
151
- listeners.set(id, listener);
152
- },
153
- removeListener(id) {
154
- listeners.delete(id);
155
- },
156
- modify(modifier, forceUpdate) {
157
- if (modifier) modifier(sv.value);
158
- if (forceUpdate !== false) listeners.forEach((fn) => fn(sv.value));
159
- }
160
- };
161
- return sv;
162
- }
163
- function useSharedValue(init) {
164
- return react.default.useRef(createSharedValue(init)).current;
165
- }
166
- function useAnimatedStyle(updater) {
167
- return updater();
168
- }
169
- function useAnimatedProps(updater) {
170
- return updater();
171
- }
172
- function useDerivedValue(updater) {
173
- return createSharedValue(updater());
174
- }
175
- function useAnimatedScrollHandler(_handler) {
176
- return vitest.vi.fn();
177
- }
178
- function useAnimatedGestureHandler(_handler) {
179
- return vitest.vi.fn();
180
- }
181
- function useAnimatedReaction(_prepare, _react, _deps) {}
182
- function useAnimatedKeyboard() {
183
- return {
184
- state: createSharedValue(0),
185
- height: createSharedValue(0)
186
- };
187
- }
188
- function useReducedMotion() {
189
- return false;
190
- }
191
- function useFrameCallback(_callback, _autostart) {
192
- return {
193
- setActive: vitest.vi.fn(),
194
- isActive: false,
195
- callbackId: 0
196
- };
197
- }
198
- function withTiming(toValue, _config, callback) {
199
- callback?.({
200
- finished: true,
201
- current: toValue
202
- });
203
- return toValue;
204
- }
205
- function withSpring(toValue, _config, callback) {
206
- callback?.({
207
- finished: true,
208
- current: toValue
209
- });
210
- return toValue;
211
- }
212
- function withDecay(_config, callback) {
213
- callback?.({
214
- finished: true,
215
- current: 0
216
- });
217
- return 0;
218
- }
219
- function withSequence(...values) {
220
- return values[values.length - 1];
221
- }
222
- function withDelay(_delay, value) {
223
- return value;
224
- }
225
- function withRepeat(value) {
226
- return value;
227
- }
228
- function runOnJS(fn) {
229
- return fn;
230
- }
231
- function runOnUI(fn) {
232
- return fn;
233
- }
234
- function addWhitelistedUIProps(_props) {}
235
- function addWhitelistedNativeProps(_props) {}
236
- function configureProps() {}
237
- function createAnimatedComponent(component) {
238
- const Animated = react.default.forwardRef((props, ref) => {
239
- return react.default.createElement(component, {
240
- ...props,
241
- ref
242
- });
243
- });
244
- Animated.displayName = `Animated(${component.displayName || component.name || "Component"})`;
245
- return Animated;
246
- }
247
- function makeAnimatedHost(name) {
248
- const Comp = react.default.forwardRef((props, ref) => {
249
- const Base = getRN$1()[name];
250
- if (!Base) throw new require_errors.VitestNativeError("PRESET_UNAVAILABLE", `The reanimated preset needs React Native's '${name}' component to build Animated.${name}, and react-native did not provide it.\nThis usually means react-native resolved to something unexpected — a partially installed copy, or a mock replacing the whole module. Check that 'react-native' resolves in your project and that no vi.mock replaces it wholesale.`);
251
- return react.default.createElement(Base, {
252
- ...props,
253
- ref
254
- });
255
- });
256
- Comp.displayName = `Animated.${name}`;
257
- return Comp;
258
- }
259
- const View = makeAnimatedHost("View");
260
- const Text = makeAnimatedHost("Text");
261
- const Image = makeAnimatedHost("Image");
262
- const ScrollView = makeAnimatedHost("ScrollView");
263
- const FlatList = makeAnimatedHost("FlatList");
264
- function createLayoutAnim() {
265
- const obj = {};
266
- obj.duration = vitest.vi.fn(() => obj);
267
- obj.delay = vitest.vi.fn(() => obj);
268
- obj.easing = vitest.vi.fn(() => obj);
269
- obj.damping = vitest.vi.fn(() => obj);
270
- obj.stiffness = vitest.vi.fn(() => obj);
271
- obj.mass = vitest.vi.fn(() => obj);
272
- obj.overshootClamping = vitest.vi.fn(() => obj);
273
- obj.restDisplacementThreshold = vitest.vi.fn(() => obj);
274
- obj.restSpeedThreshold = vitest.vi.fn(() => obj);
275
- obj.springify = vitest.vi.fn(() => obj);
276
- obj.withCallback = vitest.vi.fn(() => obj);
277
- obj.withInitialValues = vitest.vi.fn(() => obj);
278
- obj.randomDelay = vitest.vi.fn(() => obj);
279
- obj.build = vitest.vi.fn();
280
- return obj;
281
- }
282
- function returnThis() {
283
- return this;
284
- }
285
- return {
286
- default: {
287
- createAnimatedComponent,
288
- View,
289
- Text,
290
- Image,
291
- ScrollView,
292
- FlatList,
293
- addWhitelistedUIProps,
294
- addWhitelistedNativeProps,
295
- configureProps
296
- },
297
- addWhitelistedUIProps,
298
- addWhitelistedNativeProps,
299
- configureProps,
300
- useSharedValue,
301
- useAnimatedStyle,
302
- useAnimatedProps,
303
- useDerivedValue,
304
- useAnimatedScrollHandler,
305
- useAnimatedGestureHandler,
306
- useAnimatedReaction,
307
- useAnimatedKeyboard,
308
- useReducedMotion,
309
- useFrameCallback,
310
- withTiming,
311
- withSpring,
312
- withDecay,
313
- withSequence,
314
- withDelay,
315
- withRepeat,
316
- runOnJS,
317
- runOnUI,
318
- createAnimatedComponent,
319
- Easing: {
320
- linear: vitest.vi.fn((t) => t),
321
- ease: vitest.vi.fn((t) => t),
322
- quad: vitest.vi.fn((t) => t * t),
323
- cubic: vitest.vi.fn((t) => t * t * t),
324
- bezier: vitest.vi.fn(() => (t) => t),
325
- in: vitest.vi.fn((fn) => fn),
326
- out: vitest.vi.fn((fn) => fn),
327
- inOut: vitest.vi.fn((fn) => fn)
328
- },
329
- FadeIn: createLayoutAnim(),
330
- FadeOut: createLayoutAnim(),
331
- FadeInDown: createLayoutAnim(),
332
- FadeInUp: createLayoutAnim(),
333
- FadeInLeft: createLayoutAnim(),
334
- FadeInRight: createLayoutAnim(),
335
- FadeOutDown: createLayoutAnim(),
336
- FadeOutUp: createLayoutAnim(),
337
- FadeOutLeft: createLayoutAnim(),
338
- FadeOutRight: createLayoutAnim(),
339
- SlideInRight: createLayoutAnim(),
340
- SlideInLeft: createLayoutAnim(),
341
- SlideInUp: createLayoutAnim(),
342
- SlideInDown: createLayoutAnim(),
343
- SlideOutRight: createLayoutAnim(),
344
- SlideOutLeft: createLayoutAnim(),
345
- SlideOutUp: createLayoutAnim(),
346
- SlideOutDown: createLayoutAnim(),
347
- ZoomIn: createLayoutAnim(),
348
- ZoomOut: createLayoutAnim(),
349
- BounceIn: createLayoutAnim(),
350
- BounceOut: createLayoutAnim(),
351
- BounceInDown: createLayoutAnim(),
352
- BounceInUp: createLayoutAnim(),
353
- BounceInLeft: createLayoutAnim(),
354
- BounceInRight: createLayoutAnim(),
355
- FlipInEasyX: createLayoutAnim(),
356
- FlipInEasyY: createLayoutAnim(),
357
- FlipOutEasyX: createLayoutAnim(),
358
- FlipOutEasyY: createLayoutAnim(),
359
- LightSpeedInLeft: createLayoutAnim(),
360
- LightSpeedInRight: createLayoutAnim(),
361
- LightSpeedOutLeft: createLayoutAnim(),
362
- LightSpeedOutRight: createLayoutAnim(),
363
- PinwheelIn: createLayoutAnim(),
364
- PinwheelOut: createLayoutAnim(),
365
- StretchInX: createLayoutAnim(),
366
- StretchInY: createLayoutAnim(),
367
- StretchOutX: createLayoutAnim(),
368
- StretchOutY: createLayoutAnim(),
369
- RotateInDownLeft: createLayoutAnim(),
370
- RotateInDownRight: createLayoutAnim(),
371
- RotateInUpLeft: createLayoutAnim(),
372
- RotateInUpRight: createLayoutAnim(),
373
- RotateOutDownLeft: createLayoutAnim(),
374
- RotateOutDownRight: createLayoutAnim(),
375
- RotateOutUpLeft: createLayoutAnim(),
376
- RotateOutUpRight: createLayoutAnim(),
377
- Layout: createLayoutAnim(),
378
- LinearTransition: createLayoutAnim(),
379
- SequencedTransition: createLayoutAnim(),
380
- FadingTransition: createLayoutAnim(),
381
- JumpingTransition: createLayoutAnim(),
382
- CurvedTransition: createLayoutAnim(),
383
- EntryExitTransition: createLayoutAnim(),
384
- interpolate: vitest.vi.fn((_value, input, output) => output[0]),
385
- Extrapolation: {
386
- CLAMP: "clamp",
387
- EXTEND: "extend",
388
- IDENTITY: "identity"
389
- },
390
- useAnimatedRef: () => react.default.useRef(null),
391
- measure: vitest.vi.fn(() => ({
392
- x: 0,
393
- y: 0,
394
- width: 0,
395
- height: 0,
396
- pageX: 0,
397
- pageY: 0
398
- })),
399
- scrollTo: vitest.vi.fn(),
400
- cancelAnimation: vitest.vi.fn(),
401
- makeMutable: vitest.vi.fn((init) => createSharedValue(init)),
402
- SharedTransition: {
403
- duration: vitest.vi.fn(returnThis),
404
- custom: vitest.vi.fn(returnThis),
405
- progressAnimation: vitest.vi.fn(returnThis),
406
- defaultTransitionType: vitest.vi.fn(returnThis)
407
- },
408
- ReduceMotion: {
409
- System: "system",
410
- Always: "always",
411
- Never: "never"
412
- },
413
- KeyboardState: {
414
- UNKNOWN: 0,
415
- OPENING: 1,
416
- OPEN: 2,
417
- CLOSING: 3,
418
- CLOSED: 4
419
- }
420
- };
421
- }
422
- } }
423
- });
424
- }
425
- //#endregion
426
- //#region src/mocks/components/pressableHost.ts
427
- function buildPressableHostProps(props, ref) {
428
- const { disabled, accessibilityState, onPress, onPressIn, onPressOut, onLongPress, ...rest } = props;
429
- const mergedA11yState = disabled || accessibilityState ? {
430
- ...accessibilityState,
431
- ...disabled ? { disabled: true } : {}
432
- } : void 0;
433
- const pressProps = disabled ? {} : {
434
- onStartShouldSetResponder: () => true,
435
- onResponderGrant: (e) => onPressIn?.(e),
436
- onResponderRelease: (e) => {
437
- onPress?.(e);
438
- onPressOut?.(e);
439
- },
440
- onPress,
441
- onPressIn,
442
- onPressOut,
443
- onLongPress
444
- };
445
- return {
446
- accessible: true,
447
- ...disabled ? { pointerEvents: "none" } : {},
448
- ...pressProps,
449
- ...rest,
450
- ...mergedA11yState ? { accessibilityState: mergedA11yState } : {},
451
- ref
452
- };
453
- }
454
- //#endregion
455
- //#region src/mocks/components/Pressable.ts
456
- function createPressableMock() {
457
- const Pressable = react.default.forwardRef((props, ref) => {
458
- const { style, children, onPressIn, onPressOut, ...rest } = props;
459
- const [pressed, setPressed] = react.default.useState(false);
460
- const state = { pressed };
461
- const resolvedStyle = typeof style === "function" ? style(state) : style;
462
- const resolvedChildren = typeof children === "function" ? children(state) : children;
463
- const hostProps = buildPressableHostProps({
464
- ...rest,
465
- style: resolvedStyle,
466
- onPressIn: (e) => {
467
- setPressed(true);
468
- onPressIn?.(e);
469
- },
470
- onPressOut: (e) => {
471
- setPressed(false);
472
- onPressOut?.(e);
473
- }
474
- }, ref);
475
- return react.default.createElement("Pressable", hostProps, resolvedChildren);
476
- });
477
- Pressable.displayName = "Pressable";
478
- return Pressable;
479
- }
480
- //#endregion
481
- //#region src/presets/gesture-handler.ts
482
- function gestureHandler() {
483
- return builtInPreset({
484
- name: "gestureHandler",
485
- modules: { "react-native-gesture-handler": {
486
- exports: [
487
- "State",
488
- "Directions",
489
- "Gesture",
490
- "GestureDetector",
491
- "GestureHandlerRootView",
492
- "Swipeable",
493
- "DrawerLayout",
494
- "gestureHandlerRootHOC",
495
- "PanGestureHandler",
496
- "TapGestureHandler",
497
- "LongPressGestureHandler",
498
- "PinchGestureHandler",
499
- "RotationGestureHandler",
500
- "FlingGestureHandler",
501
- "ForceTouchGestureHandler",
502
- "NativeViewGestureHandler",
503
- "ScrollView",
504
- "FlatList",
505
- "TouchableOpacity",
506
- "TouchableHighlight",
507
- "TouchableWithoutFeedback",
508
- "TouchableNativeFeedback",
509
- "Pressable",
510
- "RectButton",
511
- "BaseButton",
512
- "BorderlessButton",
513
- "RawButton",
514
- "PureNativeButton"
515
- ],
516
- factory: () => {
517
- const State = {
518
- UNDETERMINED: 0,
519
- FAILED: 1,
520
- BEGAN: 2,
521
- CANCELLED: 3,
522
- ACTIVE: 4,
523
- END: 5
524
- };
525
- const Directions = {
526
- RIGHT: 1,
527
- LEFT: 2,
528
- UP: 4,
529
- DOWN: 8
530
- };
531
- function createGestureHandler(name) {
532
- const Handler = react.default.forwardRef((props, ref) => react.default.createElement(name, {
533
- ...props,
534
- ref
535
- }, props.children));
536
- Handler.displayName = name;
537
- return Handler;
538
- }
539
- const GestureHandlerRootView = react.default.forwardRef((props, ref) => react.default.createElement("GestureHandlerRootView", {
540
- ...props,
541
- ref
542
- }, props.children));
543
- GestureHandlerRootView.displayName = "GestureHandlerRootView";
544
- const Swipeable = react.default.forwardRef((props, ref) => react.default.createElement("Swipeable", {
545
- ...props,
546
- ref
547
- }, props.children));
548
- Swipeable.displayName = "Swipeable";
549
- const DrawerLayout = react.default.forwardRef((props, ref) => react.default.createElement("DrawerLayout", {
550
- ...props,
551
- ref
552
- }, props.children));
553
- DrawerLayout.displayName = "DrawerLayout";
554
- function gestureHandlerRootHOC(component) {
555
- return component;
556
- }
557
- function returnThis() {
558
- return this;
559
- }
560
- const Gesture = {
561
- Pan: vitest.vi.fn(() => ({
562
- onStart: vitest.vi.fn(returnThis),
563
- onUpdate: vitest.vi.fn(returnThis),
564
- onEnd: vitest.vi.fn(returnThis),
565
- onFinalize: vitest.vi.fn(returnThis),
566
- enabled: vitest.vi.fn(returnThis),
567
- minDistance: vitest.vi.fn(returnThis)
568
- })),
569
- Tap: vitest.vi.fn(() => ({
570
- onStart: vitest.vi.fn(returnThis),
571
- onEnd: vitest.vi.fn(returnThis),
572
- numberOfTaps: vitest.vi.fn(returnThis),
573
- enabled: vitest.vi.fn(returnThis)
574
- })),
575
- LongPress: vitest.vi.fn(() => ({
576
- onStart: vitest.vi.fn(returnThis),
577
- onEnd: vitest.vi.fn(returnThis),
578
- minDuration: vitest.vi.fn(returnThis),
579
- enabled: vitest.vi.fn(returnThis)
580
- })),
581
- Pinch: vitest.vi.fn(() => ({
582
- onStart: vitest.vi.fn(returnThis),
583
- onUpdate: vitest.vi.fn(returnThis),
584
- onEnd: vitest.vi.fn(returnThis),
585
- enabled: vitest.vi.fn(returnThis)
586
- })),
587
- Rotation: vitest.vi.fn(() => ({
588
- onStart: vitest.vi.fn(returnThis),
589
- onUpdate: vitest.vi.fn(returnThis),
590
- onEnd: vitest.vi.fn(returnThis),
591
- enabled: vitest.vi.fn(returnThis)
592
- })),
593
- Fling: vitest.vi.fn(() => ({
594
- direction: vitest.vi.fn(returnThis),
595
- onStart: vitest.vi.fn(returnThis),
596
- onEnd: vitest.vi.fn(returnThis),
597
- enabled: vitest.vi.fn(returnThis)
598
- })),
599
- Simultaneous: vitest.vi.fn((..._gestures) => ({})),
600
- Exclusive: vitest.vi.fn((..._gestures) => ({})),
601
- Race: vitest.vi.fn((..._gestures) => ({}))
602
- };
603
- const GestureDetector = react.default.forwardRef((props, ref) => react.default.createElement("GestureDetector", {
604
- ...props,
605
- ref
606
- }, props.children));
607
- GestureDetector.displayName = "GestureDetector";
608
- return {
609
- default: {
610
- GestureHandlerRootView,
611
- State,
612
- Directions
613
- },
614
- State,
615
- Directions,
616
- Gesture,
617
- GestureDetector,
618
- GestureHandlerRootView,
619
- Swipeable,
620
- DrawerLayout,
621
- gestureHandlerRootHOC,
622
- PanGestureHandler: createGestureHandler("PanGestureHandler"),
623
- TapGestureHandler: createGestureHandler("TapGestureHandler"),
624
- LongPressGestureHandler: createGestureHandler("LongPressGestureHandler"),
625
- PinchGestureHandler: createGestureHandler("PinchGestureHandler"),
626
- RotationGestureHandler: createGestureHandler("RotationGestureHandler"),
627
- FlingGestureHandler: createGestureHandler("FlingGestureHandler"),
628
- ForceTouchGestureHandler: createGestureHandler("ForceTouchGestureHandler"),
629
- NativeViewGestureHandler: createGestureHandler("NativeViewGestureHandler"),
630
- ScrollView: createGestureHandler("GH-ScrollView"),
631
- FlatList: createGestureHandler("GH-FlatList"),
632
- TouchableOpacity: createGestureHandler("GH-TouchableOpacity"),
633
- TouchableHighlight: createGestureHandler("GH-TouchableHighlight"),
634
- TouchableWithoutFeedback: createGestureHandler("GH-TouchableWithoutFeedback"),
635
- TouchableNativeFeedback: createGestureHandler("GH-TouchableNativeFeedback"),
636
- Pressable: createPressableMock(),
637
- RectButton: createGestureHandler("RectButton"),
638
- BaseButton: createGestureHandler("BaseButton"),
639
- BorderlessButton: createGestureHandler("BorderlessButton"),
640
- RawButton: createGestureHandler("RawButton"),
641
- PureNativeButton: createGestureHandler("PureNativeButton")
642
- };
643
- }
644
- } }
645
- });
646
- }
647
- //#endregion
648
- //#region src/presets/safe-area.ts
649
- function safeAreaContext() {
650
- return builtInPreset({
651
- name: "safeAreaContext",
652
- modules: { "react-native-safe-area-context": {
653
- exports: [
654
- "SafeAreaProvider",
655
- "SafeAreaView",
656
- "SafeAreaInsetsContext",
657
- "SafeAreaFrameContext",
658
- "useSafeAreaInsets",
659
- "useSafeAreaFrame",
660
- "withSafeAreaInsets",
661
- "initialWindowMetrics",
662
- "initialWindowSafeAreaInsets"
663
- ],
664
- factory: () => {
665
- const defaultInsets = {
666
- top: 47,
667
- right: 0,
668
- bottom: 34,
669
- left: 0
670
- };
671
- const defaultFrame = {
672
- x: 0,
673
- y: 0,
674
- width: 390,
675
- height: 844
676
- };
677
- const state = {
678
- insets: { ...defaultInsets },
679
- frame: { ...defaultFrame }
680
- };
681
- const initialMetrics = {
682
- frame: state.frame,
683
- insets: state.insets
684
- };
685
- const SafeAreaProvider = react.default.forwardRef((props, ref) => react.default.createElement("SafeAreaProvider", {
686
- ...props,
687
- ref
688
- }, props.children));
689
- SafeAreaProvider.displayName = "SafeAreaProvider";
690
- const SafeAreaView = react.default.forwardRef((props, ref) => react.default.createElement("SafeAreaView", {
691
- ...props,
692
- ref
693
- }, props.children));
694
- SafeAreaView.displayName = "SafeAreaView";
695
- const SafeAreaInsetsContext = react.default.createContext(state.insets);
696
- const SafeAreaFrameContext = react.default.createContext(state.frame);
697
- function useSafeAreaInsets() {
698
- return state.insets;
699
- }
700
- function useSafeAreaFrame() {
701
- return state.frame;
702
- }
703
- function withSafeAreaInsets(WrappedComponent) {
704
- const WithSafeAreaInsets = react.default.forwardRef((props, ref) => react.default.createElement(WrappedComponent, {
705
- ...props,
706
- ref,
707
- insets: state.insets
708
- }));
709
- WithSafeAreaInsets.displayName = `withSafeAreaInsets(${WrappedComponent.displayName || WrappedComponent.name || "Component"})`;
710
- return WithSafeAreaInsets;
711
- }
712
- return {
713
- default: {
714
- SafeAreaProvider,
715
- SafeAreaView
716
- },
717
- SafeAreaProvider,
718
- SafeAreaView,
719
- SafeAreaInsetsContext,
720
- SafeAreaFrameContext,
721
- useSafeAreaInsets,
722
- useSafeAreaFrame,
723
- withSafeAreaInsets,
724
- initialWindowMetrics: initialMetrics,
725
- initialWindowSafeAreaInsets: state.insets,
726
- EdgeInsets: vitest.vi.fn(),
727
- Rect: vitest.vi.fn(),
728
- Metrics: vitest.vi.fn(),
729
- /** Internal: update insets. Called by setInsets() helper. */
730
- _setInsets: (insets) => {
731
- Object.assign(state.insets, insets);
732
- },
733
- /** Internal: reset insets to defaults. Called by resetAllMocks(). */
734
- _reset: () => {
735
- Object.assign(state.insets, defaultInsets);
736
- Object.assign(state.frame, defaultFrame);
737
- }
738
- };
739
- }
740
- } }
741
- });
742
- }
743
- //#endregion
744
- //#region src/presets/navigation.ts
745
- /** Builds a minimal navigation prop matching useNavigation()'s shape. */
746
- function createMockNavigation() {
747
- return {
748
- navigate: vitest.vi.fn(),
749
- goBack: vitest.vi.fn(),
750
- reset: vitest.vi.fn(),
751
- setParams: vitest.vi.fn(),
752
- setOptions: vitest.vi.fn(),
753
- dispatch: vitest.vi.fn(),
754
- canGoBack: vitest.vi.fn(() => false),
755
- getParent: vitest.vi.fn(() => void 0),
756
- getState: vitest.vi.fn(() => ({
757
- index: 0,
758
- key: "root",
759
- routeNames: [],
760
- routes: [],
761
- type: "stack",
762
- stale: false
763
- })),
764
- isFocused: vitest.vi.fn(() => true),
765
- addListener: vitest.vi.fn(() => vitest.vi.fn()),
766
- removeListener: vitest.vi.fn(),
767
- getId: vitest.vi.fn(() => void 0)
768
- };
769
- }
770
- /**
771
- * Creates a Screen component mock that handles all three React Navigation patterns:
772
- * 1. <Screen component={Comp} /> — renders Comp with route & navigation props
773
- * 2. <Screen>{(props) => <Comp />}</Screen> — calls render function
774
- * 3. <Screen><Something /></Screen> — passes children through
775
- *
776
- * Accepts NavigationContext and NavigationRouteContext so that hooks like
777
- * useNavigation() and useRoute() inside the screen component return values
778
- * consistent with the route/navigation props passed to the component.
779
- */
780
- function createMockScreen(NavContext, RouteContext, defaultRouteParams) {
781
- const Screen = react.default.forwardRef(({ component: Component, children, ...rest }, ref) => {
782
- const route = {
783
- key: rest.name ?? "",
784
- name: rest.name ?? "",
785
- params: rest.initialParams ?? defaultRouteParams
786
- };
787
- const nav = createMockNavigation();
788
- const content = Component ? react.default.createElement(Component, {
789
- route,
790
- navigation: nav
791
- }) : typeof children === "function" ? children({
792
- route,
793
- navigation: nav
794
- }) : children;
795
- return react.default.createElement("Screen", {
796
- ...rest,
797
- ref
798
- }, react.default.createElement(NavContext.Provider, { value: nav }, react.default.createElement(RouteContext.Provider, { value: route }, content)));
799
- });
800
- Screen.displayName = "Screen";
801
- return Screen;
802
- }
803
- function navigation(presetOptions = {}) {
804
- const defaultRouteParams = presetOptions.defaultRouteParams ?? {};
805
- const NavigationContext = react.default.createContext(null);
806
- const NavigationRouteContext = react.default.createContext(null);
807
- const NavigationContainerRefContext = react.default.createContext(null);
808
- const NavigationHelpersContext = react.default.createContext(null);
809
- const CurrentRenderContext = react.default.createContext(void 0);
810
- const PreventRemoveContext = react.default.createContext(null);
811
- const LinkingContext = react.default.createContext({ options: void 0 });
812
- const LocaleDirContext = react.default.createContext("ltr");
813
- const UNSTABLE_UnhandledLinkingContext = react.default.createContext({
814
- lastUnhandledLink: void 0,
815
- setLastUnhandledLink: () => {}
816
- });
817
- const themeFonts = (() => {
818
- return process.env.VITEST_NATIVE_PLATFORM !== "android" ? {
819
- regular: {
820
- fontFamily: "System",
821
- fontWeight: "400"
822
- },
823
- medium: {
824
- fontFamily: "System",
825
- fontWeight: "500"
826
- },
827
- bold: {
828
- fontFamily: "System",
829
- fontWeight: "600"
830
- },
831
- heavy: {
832
- fontFamily: "System",
833
- fontWeight: "700"
834
- }
835
- } : {
836
- regular: {
837
- fontFamily: "sans-serif",
838
- fontWeight: "normal"
839
- },
840
- medium: {
841
- fontFamily: "sans-serif-medium",
842
- fontWeight: "normal"
843
- },
844
- bold: {
845
- fontFamily: "sans-serif",
846
- fontWeight: "600"
847
- },
848
- heavy: {
849
- fontFamily: "sans-serif",
850
- fontWeight: "700"
851
- }
852
- };
853
- })();
854
- const DefaultTheme = {
855
- dark: false,
856
- colors: {
857
- primary: "rgb(0, 122, 255)",
858
- background: "rgb(242, 242, 242)",
859
- card: "rgb(255, 255, 255)",
860
- text: "rgb(28, 28, 30)",
861
- border: "rgb(216, 216, 216)",
862
- notification: "rgb(255, 59, 48)"
863
- },
864
- fonts: themeFonts
865
- };
866
- const DarkTheme = {
867
- dark: true,
868
- colors: {
869
- primary: "rgb(10, 132, 255)",
870
- background: "rgb(1, 1, 1)",
871
- card: "rgb(18, 18, 18)",
872
- text: "rgb(229, 229, 231)",
873
- border: "rgb(39, 39, 41)",
874
- notification: "rgb(255, 69, 58)"
875
- },
876
- fonts: themeFonts
877
- };
878
- const ThemeContext = react.default.createContext(DefaultTheme);
879
- const Screen = createMockScreen(NavigationContext, NavigationRouteContext, defaultRouteParams);
880
- return builtInPreset({
881
- name: "navigation",
882
- config: { defaultRouteParams },
883
- modules: {
884
- "@react-navigation/native": {
885
- exports: [
886
- "NavigationContainer",
887
- "useLinkTo",
888
- "Link",
889
- "useNavigation",
890
- "useRoute",
891
- "useFocusEffect",
892
- "useIsFocused",
893
- "useNavigationState",
894
- "useScrollToTop",
895
- "useNavigationContainerRef",
896
- "createNavigationContainerRef",
897
- "createNavigatorFactory",
898
- "useNavigationBuilder",
899
- "NavigationContext",
900
- "NavigationRouteContext",
901
- "NavigationContainerRefContext",
902
- "NavigationHelpersContext",
903
- "CurrentRenderContext",
904
- "ThemeContext",
905
- "ThemeProvider",
906
- "useTheme",
907
- "NavigationIndependentTree",
908
- "useNavigationIndependentTree",
909
- "PreventRemoveContext",
910
- "PreventRemoveProvider",
911
- "usePreventRemove",
912
- "usePreventRemoveContext",
913
- "CommonActions",
914
- "StackActions",
915
- "TabActions",
916
- "DrawerActions",
917
- "findFocusedRoute",
918
- "getFocusedRouteNameFromRoute",
919
- "getActionFromState",
920
- "getPathFromState",
921
- "getStateFromPath",
922
- "useStateForPath",
923
- "validatePathConfig",
924
- "BaseNavigationContainer",
925
- "LinkingContext",
926
- "LocaleDirContext",
927
- "UNSTABLE_UnhandledLinkingContext",
928
- "DefaultTheme",
929
- "DarkTheme",
930
- "createStaticNavigation",
931
- "ServerContainer",
932
- "useLinkBuilder",
933
- "useLinkProps",
934
- "useLocale",
935
- "useRoutePath",
936
- "createComponentForStaticNavigation",
937
- "createPathConfigForStaticNavigation",
938
- "BaseRouter"
939
- ],
940
- factory: () => {
941
- const NavigationContainer = react.default.forwardRef((props, ref) => react.default.createElement("NavigationContainer", {
942
- ...props,
943
- ref
944
- }, props.children));
945
- NavigationContainer.displayName = "NavigationContainer";
946
- const navigate = vitest.vi.fn();
947
- const goBack = vitest.vi.fn();
948
- const reset = vitest.vi.fn();
949
- const setParams = vitest.vi.fn();
950
- const setOptions = vitest.vi.fn();
951
- const dispatch = vitest.vi.fn();
952
- const canGoBack = vitest.vi.fn(() => false);
953
- const getParent = vitest.vi.fn(() => void 0);
954
- const getState = vitest.vi.fn(() => ({
955
- index: 0,
956
- key: "root",
957
- routeNames: [],
958
- routes: [],
959
- type: "stack",
960
- stale: false
961
- }));
962
- const defaultNavigation = {
963
- navigate,
964
- goBack,
965
- reset,
966
- setParams,
967
- setOptions,
968
- dispatch,
969
- canGoBack,
970
- getParent,
971
- getState,
972
- isFocused: vitest.vi.fn(() => true),
973
- addListener: vitest.vi.fn(() => vitest.vi.fn()),
974
- removeListener: vitest.vi.fn(),
975
- getId: vitest.vi.fn(() => void 0)
976
- };
977
- const defaultRoute = {
978
- key: "test-route-key",
979
- name: "TestScreen",
980
- params: defaultRouteParams
981
- };
982
- function useNavigation() {
983
- try {
984
- const ctx = react.default.useContext(NavigationContext);
985
- if (ctx) return ctx;
986
- } catch {}
987
- return defaultNavigation;
988
- }
989
- function useRoute() {
990
- try {
991
- const ctx = react.default.useContext(NavigationRouteContext);
992
- if (ctx) return ctx;
993
- } catch {}
994
- return defaultRoute;
995
- }
996
- function useFocusEffect(callback) {
997
- react.default.useEffect(callback, []);
998
- }
999
- function useIsFocused() {
1000
- return true;
1001
- }
1002
- function useNavigationState(selector) {
1003
- return selector(getState());
1004
- }
1005
- function createNavigationContainerRef() {
1006
- return {
1007
- current: null,
1008
- isReady: vitest.vi.fn(() => true),
1009
- navigate,
1010
- goBack,
1011
- reset,
1012
- dispatch,
1013
- canGoBack,
1014
- getState,
1015
- getRootState: getState,
1016
- getCurrentRoute: vitest.vi.fn(() => ({
1017
- key: "test",
1018
- name: "TestScreen"
1019
- })),
1020
- getCurrentOptions: vitest.vi.fn(() => ({})),
1021
- addListener: vitest.vi.fn(() => vitest.vi.fn())
1022
- };
1023
- }
1024
- function useNavigationContainerRef() {
1025
- return createNavigationContainerRef();
1026
- }
1027
- function ThemeProvider({ value, children }) {
1028
- return react.default.createElement(ThemeContext.Provider, { value: value ?? DefaultTheme }, children);
1029
- }
1030
- function useTheme() {
1031
- try {
1032
- return react.default.useContext(ThemeContext) ?? DefaultTheme;
1033
- } catch {
1034
- return DefaultTheme;
1035
- }
1036
- }
1037
- function NavigationIndependentTree({ children }) {
1038
- return children;
1039
- }
1040
- function useNavigationIndependentTree() {
1041
- return true;
1042
- }
1043
- function PreventRemoveProvider({ children }) {
1044
- return children;
1045
- }
1046
- const BaseNavigationContainer = react.default.forwardRef((props, ref) => react.default.createElement("BaseNavigationContainer", {
1047
- ...props,
1048
- ref
1049
- }, props.children));
1050
- BaseNavigationContainer.displayName = "BaseNavigationContainer";
1051
- return {
1052
- default: { NavigationContainer },
1053
- NavigationContainer,
1054
- useNavigation,
1055
- useRoute,
1056
- useFocusEffect,
1057
- useIsFocused,
1058
- useNavigationState,
1059
- useNavigationContainerRef,
1060
- createNavigationContainerRef,
1061
- createNavigatorFactory: vitest.vi.fn((Navigator) => () => ({
1062
- Navigator: Navigator ?? react.default.forwardRef((props, ref) => react.default.createElement("Navigator", {
1063
- ...props,
1064
- ref
1065
- }, props.children)),
1066
- Screen,
1067
- Group: react.default.forwardRef((props, ref) => react.default.createElement("Group", {
1068
- ...props,
1069
- ref
1070
- }, props.children))
1071
- })),
1072
- useNavigationBuilder: vitest.vi.fn(() => ({
1073
- state: getState(),
1074
- navigation: useNavigation(),
1075
- descriptors: {},
1076
- NavigationContent: ({ children }) => children
1077
- })),
1078
- NavigationContext,
1079
- NavigationRouteContext,
1080
- NavigationContainerRefContext,
1081
- NavigationHelpersContext,
1082
- CurrentRenderContext,
1083
- ThemeContext,
1084
- ThemeProvider,
1085
- useTheme,
1086
- NavigationIndependentTree,
1087
- useNavigationIndependentTree,
1088
- PreventRemoveContext,
1089
- PreventRemoveProvider,
1090
- usePreventRemove: vitest.vi.fn(),
1091
- usePreventRemoveContext: vitest.vi.fn(() => null),
1092
- CommonActions: {
1093
- navigate: vitest.vi.fn(),
1094
- reset: vitest.vi.fn(),
1095
- goBack: vitest.vi.fn(),
1096
- setParams: vitest.vi.fn()
1097
- },
1098
- StackActions: {
1099
- push: vitest.vi.fn(),
1100
- pop: vitest.vi.fn(),
1101
- popToTop: vitest.vi.fn(),
1102
- replace: vitest.vi.fn()
1103
- },
1104
- TabActions: { jumpTo: vitest.vi.fn() },
1105
- DrawerActions: {
1106
- openDrawer: vitest.vi.fn(),
1107
- closeDrawer: vitest.vi.fn(),
1108
- toggleDrawer: vitest.vi.fn(),
1109
- jumpTo: vitest.vi.fn()
1110
- },
1111
- findFocusedRoute: vitest.vi.fn((state) => state?.routes?.[state?.index ?? 0]),
1112
- getFocusedRouteNameFromRoute: vitest.vi.fn((route) => route?.state?.routes?.[route?.state?.index ?? 0]?.name),
1113
- getActionFromState: vitest.vi.fn(() => void 0),
1114
- getPathFromState: vitest.vi.fn(() => "/"),
1115
- getStateFromPath: vitest.vi.fn(() => void 0),
1116
- useStateForPath: vitest.vi.fn(() => void 0),
1117
- validatePathConfig: vitest.vi.fn(),
1118
- BaseNavigationContainer,
1119
- createComponentForStaticNavigation: vitest.vi.fn(() => () => null),
1120
- createPathConfigForStaticNavigation: vitest.vi.fn(() => ({})),
1121
- LinkingContext,
1122
- LocaleDirContext,
1123
- UNSTABLE_UnhandledLinkingContext,
1124
- DefaultTheme,
1125
- DarkTheme,
1126
- createStaticNavigation: vitest.vi.fn(() => NavigationContainer),
1127
- ServerContainer: react.default.forwardRef((props, _ref) => react.default.createElement(react.default.Fragment, null, props.children)),
1128
- useLinkBuilder: vitest.vi.fn(() => ({
1129
- buildHref: (name) => `/${name}`,
1130
- buildAction: (href) => ({
1131
- type: "NAVIGATE",
1132
- payload: { name: href }
1133
- })
1134
- })),
1135
- useLinkProps: vitest.vi.fn(({ href, action }) => ({
1136
- href,
1137
- accessibilityRole: "link",
1138
- onPress: () => action
1139
- })),
1140
- useLocale: vitest.vi.fn(() => ({ direction: "ltr" })),
1141
- useRoutePath: vitest.vi.fn(() => void 0),
1142
- BaseRouter: {
1143
- getInitialState: vitest.vi.fn(() => getState()),
1144
- getRehydratedState: vitest.vi.fn((state) => state),
1145
- getStateForRouteNamesChange: vitest.vi.fn((state) => state),
1146
- getStateForRouteFocus: vitest.vi.fn((state) => state),
1147
- getStateForAction: vitest.vi.fn((state) => state),
1148
- shouldActionChangeFocus: vitest.vi.fn(() => false)
1149
- },
1150
- useScrollToTop: vitest.vi.fn(),
1151
- useLinkTo: vitest.vi.fn(() => vitest.vi.fn()),
1152
- Link: react.default.forwardRef((props, ref) => react.default.createElement("Link", {
1153
- ...props,
1154
- ref
1155
- }, props.children))
1156
- };
1157
- }
1158
- },
1159
- "@react-navigation/native-stack": {
1160
- exports: ["createNativeStackNavigator"],
1161
- factory: () => {
1162
- function createNativeStackNavigator() {
1163
- return {
1164
- Navigator: react.default.forwardRef((props, ref) => react.default.createElement("NativeStackNavigator", {
1165
- ...props,
1166
- ref
1167
- }, props.children)),
1168
- Screen,
1169
- Group: react.default.forwardRef((props, ref) => react.default.createElement("Group", {
1170
- ...props,
1171
- ref
1172
- }, props.children))
1173
- };
1174
- }
1175
- return {
1176
- default: { createNativeStackNavigator },
1177
- createNativeStackNavigator
1178
- };
1179
- }
1180
- },
1181
- "@react-navigation/bottom-tabs": {
1182
- exports: ["createBottomTabNavigator"],
1183
- factory: () => {
1184
- function createBottomTabNavigator() {
1185
- return {
1186
- Navigator: react.default.forwardRef((props, ref) => react.default.createElement("BottomTabNavigator", {
1187
- ...props,
1188
- ref
1189
- }, props.children)),
1190
- Screen,
1191
- Group: react.default.forwardRef((props, ref) => react.default.createElement("Group", {
1192
- ...props,
1193
- ref
1194
- }, props.children))
1195
- };
1196
- }
1197
- return {
1198
- default: { createBottomTabNavigator },
1199
- createBottomTabNavigator
1200
- };
1201
- }
1202
- },
1203
- "@react-navigation/drawer": {
1204
- exports: ["createDrawerNavigator"],
1205
- factory: () => {
1206
- function createDrawerNavigator() {
1207
- return {
1208
- Navigator: react.default.forwardRef((props, ref) => react.default.createElement("DrawerNavigator", {
1209
- ...props,
1210
- ref
1211
- }, props.children)),
1212
- Screen,
1213
- Group: react.default.forwardRef((props, ref) => react.default.createElement("Group", {
1214
- ...props,
1215
- ref
1216
- }, props.children))
1217
- };
1218
- }
1219
- return {
1220
- default: { createDrawerNavigator },
1221
- createDrawerNavigator
1222
- };
1223
- }
1224
- },
1225
- "@react-navigation/elements": {
1226
- exports: [
1227
- "Header",
1228
- "HeaderBackground",
1229
- "HeaderBackButton",
1230
- "HeaderTitle",
1231
- "HeaderBackContext",
1232
- "HeaderShownContext",
1233
- "HeaderHeightContext",
1234
- "useHeaderHeight",
1235
- "getDefaultHeaderHeight",
1236
- "getHeaderTitle"
1237
- ],
1238
- factory: () => {
1239
- const Header = react.default.forwardRef((props, ref) => react.default.createElement("Header", {
1240
- ...props,
1241
- ref
1242
- }, props.children));
1243
- Header.displayName = "Header";
1244
- const HeaderBackground = react.default.forwardRef((props, ref) => react.default.createElement("HeaderBackground", {
1245
- ...props,
1246
- ref
1247
- }, props.children));
1248
- HeaderBackground.displayName = "HeaderBackground";
1249
- const HeaderBackButton = react.default.forwardRef((props, ref) => react.default.createElement("HeaderBackButton", {
1250
- ...props,
1251
- ref
1252
- }));
1253
- HeaderBackButton.displayName = "HeaderBackButton";
1254
- const HeaderTitle = react.default.forwardRef((props, ref) => react.default.createElement("HeaderTitle", {
1255
- ...props,
1256
- ref
1257
- }, props.children));
1258
- HeaderTitle.displayName = "HeaderTitle";
1259
- return {
1260
- default: {
1261
- Header,
1262
- HeaderBackground,
1263
- HeaderBackButton,
1264
- HeaderTitle
1265
- },
1266
- Header,
1267
- HeaderBackground,
1268
- HeaderBackButton,
1269
- HeaderTitle,
1270
- HeaderBackContext: react.default.createContext(void 0),
1271
- HeaderShownContext: react.default.createContext(true),
1272
- HeaderHeightContext: react.default.createContext(64),
1273
- useHeaderHeight: () => 64,
1274
- getDefaultHeaderHeight: vitest.vi.fn(() => 64),
1275
- getHeaderTitle: vitest.vi.fn((options, fallback) => options?.headerTitle ?? options?.title ?? fallback)
1276
- };
1277
- }
1278
- }
1279
- }
1280
- });
1281
- }
1282
- //#endregion
1283
- //#region src/presets/async-storage.ts
1284
- function asyncStorage() {
1285
- return builtInPreset({
1286
- name: "asyncStorage",
1287
- modules: { "@react-native-async-storage/async-storage": {
1288
- exports: [
1289
- "getItem",
1290
- "setItem",
1291
- "removeItem",
1292
- "mergeItem",
1293
- "clear",
1294
- "getAllKeys",
1295
- "multiGet",
1296
- "multiSet",
1297
- "multiRemove",
1298
- "multiMerge",
1299
- "flushGetRequests"
1300
- ],
1301
- factory: () => {
1302
- const store = /* @__PURE__ */ new Map();
1303
- const exports = {
1304
- getItem: vitest.vi.fn(async (key) => {
1305
- return store.get(key) ?? null;
1306
- }),
1307
- setItem: vitest.vi.fn(async (key, value) => {
1308
- store.set(key, value);
1309
- }),
1310
- removeItem: vitest.vi.fn(async (key) => {
1311
- store.delete(key);
1312
- }),
1313
- mergeItem: vitest.vi.fn(async (key, value) => {
1314
- const existing = store.get(key);
1315
- if (existing) try {
1316
- const merged = {
1317
- ...JSON.parse(existing),
1318
- ...JSON.parse(value)
1319
- };
1320
- store.set(key, JSON.stringify(merged));
1321
- } catch {
1322
- store.set(key, value);
1323
- }
1324
- else store.set(key, value);
1325
- }),
1326
- clear: vitest.vi.fn(async () => {
1327
- store.clear();
1328
- }),
1329
- getAllKeys: vitest.vi.fn(async () => {
1330
- return Array.from(store.keys());
1331
- }),
1332
- multiGet: vitest.vi.fn(async (keys) => {
1333
- return keys.map((key) => [key, store.get(key) ?? null]);
1334
- }),
1335
- multiSet: vitest.vi.fn(async (keyValuePairs) => {
1336
- keyValuePairs.forEach(([key, value]) => store.set(key, value));
1337
- }),
1338
- multiRemove: vitest.vi.fn(async (keys) => {
1339
- keys.forEach((key) => store.delete(key));
1340
- }),
1341
- multiMerge: vitest.vi.fn(async (keyValuePairs) => {
1342
- keyValuePairs.forEach(([key, value]) => {
1343
- const existing = store.get(key);
1344
- if (existing) try {
1345
- const merged = {
1346
- ...JSON.parse(existing),
1347
- ...JSON.parse(value)
1348
- };
1349
- store.set(key, JSON.stringify(merged));
1350
- } catch {
1351
- store.set(key, value);
1352
- }
1353
- else store.set(key, value);
1354
- });
1355
- }),
1356
- flushGetRequests: vitest.vi.fn(() => {}),
1357
- /** Internal: reset store between tests. Called by resetAllMocks(). */
1358
- _resetStore: () => store.clear()
1359
- };
1360
- return {
1361
- ...exports,
1362
- default: exports
1363
- };
1364
- }
1365
- } }
1366
- });
1367
- }
1368
- //#endregion
1369
- //#region src/presets/screens.ts
1370
- function screens() {
1371
- return builtInPreset({
1372
- name: "screens",
1373
- modules: { "react-native-screens": {
1374
- exports: [
1375
- "enableScreens",
1376
- "screensEnabled",
1377
- "enableFreeze",
1378
- "freezeEnabled",
1379
- "featureFlags",
1380
- "compatibilityFlags",
1381
- "executeNativeBackPress",
1382
- "isSearchBarAvailableForCurrentPlatform",
1383
- "useTransitionProgress",
1384
- "Screen",
1385
- "InnerScreen",
1386
- "ScreenContainer",
1387
- "ScreenContentWrapper",
1388
- "ScreenContext",
1389
- "ScreenFooter",
1390
- "ScreenStack",
1391
- "ScreenStackItem",
1392
- "ScreenStackHeaderConfig",
1393
- "ScreenStackHeaderBackButtonImage",
1394
- "ScreenStackHeaderCenterView",
1395
- "ScreenStackHeaderLeftView",
1396
- "ScreenStackHeaderRightView",
1397
- "ScreenStackHeaderSearchBarView",
1398
- "ScreenStackHeaderSubview",
1399
- "SearchBar",
1400
- "FullWindowOverlay",
1401
- "Tabs",
1402
- "NativeScreen",
1403
- "NativeScreenContainer"
1404
- ],
1405
- factory: () => {
1406
- let screensEnabledFlag = true;
1407
- let freezeEnabledFlag = false;
1408
- const enableScreens = vitest.vi.fn((shouldEnableScreens) => {
1409
- screensEnabledFlag = shouldEnableScreens !== false;
1410
- });
1411
- const screensEnabled = vitest.vi.fn(() => screensEnabledFlag);
1412
- const enableFreeze = vitest.vi.fn((shouldEnableFreeze) => {
1413
- freezeEnabledFlag = shouldEnableFreeze !== false;
1414
- });
1415
- const freezeEnabled = vitest.vi.fn(() => freezeEnabledFlag);
1416
- function createScreenComponent(name) {
1417
- const Component = react.default.forwardRef((props, ref) => react.default.createElement(name, {
1418
- ...props,
1419
- ref
1420
- }, props.children));
1421
- Component.displayName = name;
1422
- return Component;
1423
- }
1424
- const Screen = createScreenComponent("Screen");
1425
- const ScreenContainer = createScreenComponent("ScreenContainer");
1426
- const ScreenStack = createScreenComponent("ScreenStack");
1427
- const ScreenStackHeaderConfig = createScreenComponent("ScreenStackHeaderConfig");
1428
- const SearchBar = createScreenComponent("SearchBar");
1429
- const FullWindowOverlay = createScreenComponent("FullWindowOverlay");
1430
- const NativeScreen = createScreenComponent("NativeScreen");
1431
- const NativeScreenContainer = createScreenComponent("NativeScreenContainer");
1432
- const InnerScreen = createScreenComponent("InnerScreen");
1433
- const ScreenContentWrapper = createScreenComponent("ScreenContentWrapper");
1434
- const ScreenFooter = createScreenComponent("ScreenFooter");
1435
- const ScreenStackItem = createScreenComponent("ScreenStackItem");
1436
- const ScreenStackHeaderBackButtonImage = createScreenComponent("ScreenStackHeaderBackButtonImage");
1437
- const ScreenStackHeaderCenterView = createScreenComponent("ScreenStackHeaderCenterView");
1438
- const ScreenStackHeaderLeftView = createScreenComponent("ScreenStackHeaderLeftView");
1439
- const ScreenStackHeaderRightView = createScreenComponent("ScreenStackHeaderRightView");
1440
- const ScreenStackHeaderSearchBarView = createScreenComponent("ScreenStackHeaderSearchBarView");
1441
- const ScreenStackHeaderSubview = createScreenComponent("ScreenStackHeaderSubview");
1442
- const Tabs = createScreenComponent("Tabs");
1443
- const ScreenContext = react.default.createContext(Screen);
1444
- const useTransitionProgress = vitest.vi.fn(() => ({
1445
- progress: 1,
1446
- closing: 0,
1447
- goingForward: 0
1448
- }));
1449
- const executeNativeBackPress = vitest.vi.fn(() => true);
1450
- return {
1451
- default: {
1452
- Screen,
1453
- ScreenContainer,
1454
- enableScreens,
1455
- screensEnabled
1456
- },
1457
- enableScreens,
1458
- screensEnabled,
1459
- enableFreeze,
1460
- freezeEnabled,
1461
- Screen,
1462
- ScreenContainer,
1463
- ScreenStack,
1464
- ScreenStackHeaderConfig,
1465
- SearchBar,
1466
- FullWindowOverlay,
1467
- NativeScreen,
1468
- NativeScreenContainer,
1469
- InnerScreen,
1470
- ScreenContentWrapper,
1471
- ScreenContext,
1472
- ScreenFooter,
1473
- ScreenStackItem,
1474
- ScreenStackHeaderBackButtonImage,
1475
- ScreenStackHeaderCenterView,
1476
- ScreenStackHeaderLeftView,
1477
- ScreenStackHeaderRightView,
1478
- ScreenStackHeaderSearchBarView,
1479
- ScreenStackHeaderSubview,
1480
- Tabs,
1481
- useTransitionProgress,
1482
- executeNativeBackPress,
1483
- isSearchBarAvailableForCurrentPlatform: true,
1484
- featureFlags: {
1485
- experiment: {},
1486
- flags: {}
1487
- },
1488
- compatibilityFlags: {}
1489
- };
1490
- }
1491
- } }
1492
- });
1493
- }
1494
- //#endregion
1495
- //#region src/presets/expo.ts
1496
- function expo() {
1497
- return builtInPreset({
1498
- name: "expo",
1499
- modules: {
1500
- "expo-constants": {
1501
- exports: [
1502
- "AppOwnership",
1503
- "ExecutionEnvironment",
1504
- "UserInterfaceIdiom"
1505
- ],
1506
- factory: () => {
1507
- return {
1508
- default: {
1509
- expoConfig: {
1510
- name: "test-app",
1511
- slug: "test-app",
1512
- version: "1.0.0",
1513
- extra: {}
1514
- },
1515
- executionEnvironment: "storeClient",
1516
- appOwnership: "standalone",
1517
- isDevice: true,
1518
- platform: {},
1519
- manifest: null,
1520
- manifest2: null,
1521
- expoGoConfig: null,
1522
- easConfig: null,
1523
- experienceUrl: "",
1524
- linkingUri: "",
1525
- getWebViewUserAgentAsync: vitest.vi.fn(async () => "test-user-agent")
1526
- },
1527
- AppOwnership: { Expo: "expo" },
1528
- ExecutionEnvironment: {
1529
- Bare: "bare",
1530
- Standalone: "standalone",
1531
- StoreClient: "storeClient"
1532
- },
1533
- UserInterfaceIdiom: {
1534
- Handset: "handset",
1535
- Tablet: "tablet",
1536
- Desktop: "desktop",
1537
- TV: "tv",
1538
- Unsupported: "unsupported"
1539
- }
1540
- };
1541
- }
1542
- },
1543
- "expo-font": {
1544
- exports: [
1545
- "useFonts",
1546
- "loadAsync",
1547
- "isLoaded"
1548
- ],
1549
- factory: () => {
1550
- const exports = {
1551
- useFonts: vitest.vi.fn(() => [true, null]),
1552
- loadAsync: vitest.vi.fn(async () => {}),
1553
- isLoaded: vitest.vi.fn(() => true)
1554
- };
1555
- return {
1556
- ...exports,
1557
- default: exports
1558
- };
1559
- }
1560
- },
1561
- "expo-asset": {
1562
- exports: ["Asset"],
1563
- factory: () => {
1564
- const Asset = {
1565
- fromModule: vitest.vi.fn((moduleId) => ({
1566
- uri: `asset://${moduleId}`,
1567
- localUri: `asset://${moduleId}`,
1568
- width: 100,
1569
- height: 100,
1570
- name: "mock-asset",
1571
- type: "png",
1572
- downloadAsync: vitest.vi.fn(async () => {})
1573
- })),
1574
- loadAsync: vitest.vi.fn(async () => {})
1575
- };
1576
- return {
1577
- default: { Asset },
1578
- Asset
1579
- };
1580
- }
1581
- },
1582
- "expo-splash-screen": {
1583
- exports: [
1584
- "preventAutoHideAsync",
1585
- "hideAsync",
1586
- "hide",
1587
- "setOptions"
1588
- ],
1589
- factory: () => {
1590
- const exports = {
1591
- preventAutoHideAsync: vitest.vi.fn(async () => true),
1592
- hideAsync: vitest.vi.fn(async () => true),
1593
- hide: vitest.vi.fn(() => {}),
1594
- setOptions: vitest.vi.fn((_options) => {})
1595
- };
1596
- return {
1597
- ...exports,
1598
- default: exports
1599
- };
1600
- }
1601
- },
1602
- "expo-linking": {
1603
- exports: [
1604
- "createURL",
1605
- "parse",
1606
- "useURL",
1607
- "resolveScheme",
1608
- "addEventListener",
1609
- "getInitialURL",
1610
- "getLinkingURL",
1611
- "openURL",
1612
- "unwrapDevLaunchURL"
1613
- ],
1614
- factory: () => {
1615
- const exports = {
1616
- createURL: vitest.vi.fn((path) => `exp://localhost:19000/${path}`),
1617
- parse: vitest.vi.fn((url) => ({
1618
- scheme: "exp",
1619
- hostname: "localhost",
1620
- path: url,
1621
- queryParams: {}
1622
- })),
1623
- useURL: vitest.vi.fn(() => null),
1624
- resolveScheme: vitest.vi.fn(() => "exp"),
1625
- addEventListener: vitest.vi.fn(() => ({ remove: () => {} })),
1626
- getInitialURL: vitest.vi.fn(async () => null),
1627
- getLinkingURL: vitest.vi.fn(() => null),
1628
- openURL: vitest.vi.fn(async (_url) => true),
1629
- unwrapDevLaunchURL: vitest.vi.fn((url) => {
1630
- let parsed;
1631
- try {
1632
- parsed = new URL(url);
1633
- } catch {
1634
- return url;
1635
- }
1636
- const isLegacyHost = parsed.hostname === "expo-development-client";
1637
- const target = parsed.searchParams.get("__expo_url") ?? (isLegacyHost ? parsed.searchParams.get("url") : null);
1638
- if (target != null) return target;
1639
- if (isLegacyHost) return "";
1640
- const reserved = [...parsed.searchParams.keys()].filter((key) => key.startsWith("__expo_"));
1641
- if (!reserved.length) return url;
1642
- for (const key of reserved) parsed.searchParams.delete(key);
1643
- return parsed.toString();
1644
- })
1645
- };
1646
- return {
1647
- ...exports,
1648
- default: exports
1649
- };
1650
- }
1651
- },
1652
- "expo-status-bar": {
1653
- exports: [
1654
- "StatusBar",
1655
- "setStatusBarStyle",
1656
- "setStatusBarHidden",
1657
- "setStatusBarBackgroundColor",
1658
- "setStatusBarTranslucent",
1659
- "setStatusBarNetworkActivityIndicatorVisible"
1660
- ],
1661
- factory: () => {
1662
- const StatusBar = react.default.forwardRef((props, ref) => react.default.createElement("StatusBar", {
1663
- ...props,
1664
- ref
1665
- }, props.children));
1666
- StatusBar.displayName = "StatusBar";
1667
- const setStatusBarStyle = vitest.vi.fn();
1668
- const setStatusBarHidden = vitest.vi.fn();
1669
- const setStatusBarBackgroundColor = vitest.vi.fn();
1670
- const setStatusBarTranslucent = vitest.vi.fn();
1671
- const setStatusBarNetworkActivityIndicatorVisible = vitest.vi.fn();
1672
- return {
1673
- default: { StatusBar },
1674
- StatusBar,
1675
- setStatusBarStyle,
1676
- setStatusBarHidden,
1677
- setStatusBarBackgroundColor,
1678
- setStatusBarTranslucent,
1679
- setStatusBarNetworkActivityIndicatorVisible
1680
- };
1681
- }
1682
- }
1683
- }
1684
- });
1685
- }
1686
- //#endregion
1687
- //#region src/presets/device-info.ts
1688
- const STRINGS = {
1689
- getBrand: "Apple",
1690
- getModel: "iPhone",
1691
- getDeviceId: "iPhone14,2",
1692
- getSystemName: "iOS",
1693
- getSystemVersion: "17.0",
1694
- getVersion: "1.0.0",
1695
- getReadableVersion: "1.0.0.1",
1696
- getBuildNumber: "1",
1697
- getBundleId: "com.example.app",
1698
- getApplicationName: "Example",
1699
- getDeviceName: "iPhone",
1700
- getUniqueId: "mock-unique-id",
1701
- getInstallReferrer: "",
1702
- getDeviceType: "Handset",
1703
- getUserAgent: "vitest-native",
1704
- getCarrier: "",
1705
- getManufacturer: "Apple"
1706
- };
1707
- const BOOLEANS = {
1708
- hasNotch: true,
1709
- hasDynamicIsland: false,
1710
- isTablet: false,
1711
- isEmulator: false,
1712
- isPinOrFingerprintSet: false,
1713
- isCameraPresent: true,
1714
- isLandscape: false,
1715
- isLowBatteryLevel: false,
1716
- isHeadphonesConnected: false
1717
- };
1718
- const NUMBERS = {
1719
- getFontScale: 1,
1720
- getBatteryLevel: 1,
1721
- getTotalMemory: 4e9,
1722
- getUsedMemory: 1e9,
1723
- getApiLevel: 33
1724
- };
1725
- function deviceInfo() {
1726
- return builtInPreset({
1727
- name: "deviceInfo",
1728
- modules: { "react-native-device-info": {
1729
- exports: [
1730
- ...Object.keys(STRINGS),
1731
- ...Object.keys(BOOLEANS),
1732
- ...Object.keys(NUMBERS),
1733
- ...Object.keys(STRINGS).map((k) => k + "Sync"),
1734
- ...Object.keys(BOOLEANS).map((k) => k + "Sync"),
1735
- ...Object.keys(NUMBERS).map((k) => k + "Sync")
1736
- ],
1737
- factory: () => {
1738
- const api = {};
1739
- for (const [k, v] of Object.entries({
1740
- ...STRINGS,
1741
- ...BOOLEANS,
1742
- ...NUMBERS
1743
- })) {
1744
- api[k] = () => Promise.resolve(v);
1745
- api[k + "Sync"] = () => v;
1746
- }
1747
- for (const k of [
1748
- "hasNotch",
1749
- "hasDynamicIsland",
1750
- "isTablet",
1751
- "getDeviceType"
1752
- ]) {
1753
- const src = {
1754
- ...STRINGS,
1755
- ...BOOLEANS
1756
- };
1757
- api[k] = () => src[k];
1758
- }
1759
- api.getUniqueIdSync = () => STRINGS.getUniqueId;
1760
- return {
1761
- __esModule: true,
1762
- default: api,
1763
- ...api
1764
- };
1765
- }
1766
- } }
1767
- });
1768
- }
1769
- //#endregion
1770
- //#region src/presets/mmkv.ts
1771
- function mmkv() {
1772
- return builtInPreset({
1773
- name: "mmkv",
1774
- modules: { "react-native-mmkv": {
1775
- exports: [
1776
- "MMKV",
1777
- "createMMKV",
1778
- "useMMKV",
1779
- "useMMKVString",
1780
- "useMMKVNumber",
1781
- "useMMKVBoolean",
1782
- "useMMKVObject",
1783
- "useMMKVBuffer",
1784
- "useMMKVListener",
1785
- "Mode"
1786
- ],
1787
- factory: () => {
1788
- class MMKV {
1789
- _store = /* @__PURE__ */ new Map();
1790
- set(key, value) {
1791
- this._store.set(key, value);
1792
- }
1793
- getString(key) {
1794
- const v = this._store.get(key);
1795
- return typeof v === "string" ? v : void 0;
1796
- }
1797
- getNumber(key) {
1798
- const v = this._store.get(key);
1799
- return typeof v === "number" ? v : void 0;
1800
- }
1801
- getBoolean(key) {
1802
- const v = this._store.get(key);
1803
- return typeof v === "boolean" ? v : void 0;
1804
- }
1805
- getBuffer(key) {
1806
- const v = this._store.get(key);
1807
- return v instanceof Uint8Array ? v : void 0;
1808
- }
1809
- contains(key) {
1810
- return this._store.has(key);
1811
- }
1812
- delete(key) {
1813
- this._store.delete(key);
1814
- }
1815
- getAllKeys() {
1816
- return [...this._store.keys()];
1817
- }
1818
- clearAll() {
1819
- this._store.clear();
1820
- }
1821
- recrypt() {}
1822
- addOnValueChangedListener() {
1823
- return { remove() {} };
1824
- }
1825
- }
1826
- const shared = new MMKV();
1827
- const createMMKV = () => new MMKV();
1828
- const useMMKV = () => shared;
1829
- function makeHook(get) {
1830
- return (key, instance) => {
1831
- const m = instance ?? shared;
1832
- const [value, setValue] = (0, react.useState)(get(m, key));
1833
- const set = (v) => {
1834
- if (v === void 0) m.delete(key);
1835
- else m.set(key, v);
1836
- setValue(v);
1837
- };
1838
- return [value, set];
1839
- };
1840
- }
1841
- return {
1842
- __esModule: true,
1843
- MMKV,
1844
- createMMKV,
1845
- useMMKV,
1846
- useMMKVString: makeHook((m, k) => m.getString(k)),
1847
- useMMKVNumber: makeHook((m, k) => m.getNumber(k)),
1848
- useMMKVBoolean: makeHook((m, k) => m.getBoolean(k)),
1849
- useMMKVBuffer: makeHook((m, k) => m.getBuffer(k)),
1850
- useMMKVObject: (key, instance) => {
1851
- const m = instance ?? shared;
1852
- const raw = m.getString(key);
1853
- const [value, setValue] = (0, react.useState)(raw ? JSON.parse(raw) : void 0);
1854
- const set = (v) => {
1855
- if (v === void 0) m.delete(key);
1856
- else m.set(key, JSON.stringify(v));
1857
- setValue(v);
1858
- };
1859
- return [value, set];
1860
- },
1861
- useMMKVListener: () => ({ remove() {} }),
1862
- Mode: {
1863
- SINGLE_PROCESS: 0,
1864
- MULTI_PROCESS: 1
1865
- }
1866
- };
1867
- }
1868
- } }
1869
- });
1870
- }
1871
- //#endregion
1872
- //#region src/presets/netinfo.ts
1873
- /**
1874
- * The state every fetch/listener resolves to until a test changes it.
1875
- *
1876
- * Derived from ONE constant so `_reset()` and the initial value cannot drift — the
1877
- * failure mode where `beforeEach(_reset())` masks the default it claims to test.
1878
- *
1879
- * The real library starts at `{ type: 'unknown', isConnected: null, … }` and resolves
1880
- * to the device's actual connection a moment later. A mock has no device, and a null
1881
- * resting state would send every component under test down its offline branch, so the
1882
- * resting state here is a connected wifi device — the same reasoning that gives
1883
- * Dimensions a device-shaped default.
1884
- */
1885
- const RESTING = {
1886
- type: "wifi",
1887
- isConnected: true,
1888
- isInternetReachable: true,
1889
- details: {
1890
- isConnectionExpensive: false,
1891
- ssid: null,
1892
- bssid: null,
1893
- strength: null,
1894
- ipAddress: null,
1895
- subnet: null,
1896
- frequency: null,
1897
- linkSpeed: null,
1898
- rxLinkSpeed: null,
1899
- txLinkSpeed: null
1900
- }
1901
- };
1902
- const state = () => structuredClone(RESTING);
1903
- function netInfo() {
1904
- return builtInPreset({
1905
- name: "netInfo",
1906
- modules: { "@react-native-community/netinfo": {
1907
- exports: [
1908
- "configure",
1909
- "fetch",
1910
- "refresh",
1911
- "addEventListener",
1912
- "useNetInfo",
1913
- "useNetInfoInstance",
1914
- "NetInfoStateType",
1915
- "NetInfoCellularGeneration"
1916
- ],
1917
- factory: () => {
1918
- let current = state();
1919
- const listeners = /* @__PURE__ */ new Set();
1920
- const emit = () => {
1921
- for (const listener of listeners) listener(current);
1922
- };
1923
- const fetch = vitest.vi.fn(async () => current);
1924
- const refresh = vitest.vi.fn(async () => current);
1925
- const configure = vitest.vi.fn(() => {
1926
- listeners.clear();
1927
- });
1928
- const addEventListener = vitest.vi.fn((listener) => {
1929
- listeners.add(listener);
1930
- listener(current);
1931
- return () => {
1932
- listeners.delete(listener);
1933
- };
1934
- });
1935
- const useNetInfo = vitest.vi.fn(() => current);
1936
- const useNetInfoInstance = vitest.vi.fn(() => ({
1937
- netInfo: current,
1938
- refresh
1939
- }));
1940
- const NetInfoStateType = {
1941
- unknown: "unknown",
1942
- none: "none",
1943
- cellular: "cellular",
1944
- wifi: "wifi",
1945
- bluetooth: "bluetooth",
1946
- ethernet: "ethernet",
1947
- wimax: "wimax",
1948
- vpn: "vpn",
1949
- other: "other"
1950
- };
1951
- const NetInfoCellularGeneration = {
1952
- "2g": "2g",
1953
- "3g": "3g",
1954
- "4g": "4g",
1955
- "5g": "5g"
1956
- };
1957
- const api = {
1958
- configure,
1959
- fetch,
1960
- refresh,
1961
- addEventListener,
1962
- useNetInfo,
1963
- useNetInfoInstance
1964
- };
1965
- return {
1966
- ...api,
1967
- NetInfoStateType,
1968
- NetInfoCellularGeneration,
1969
- default: api,
1970
- /** Drive the connection state from a test. */
1971
- _setState: (next) => {
1972
- current = {
1973
- ...current,
1974
- ...next
1975
- };
1976
- emit();
1977
- },
1978
- /** Internal: restore the resting state. Called by resetAllMocks(). */
1979
- _reset: () => {
1980
- current = state();
1981
- listeners.clear();
1982
- }
1983
- };
1984
- }
1985
- } }
1986
- });
1987
- }
1988
- //#endregion
1989
- //#region src/presets/svg.ts
1990
- const SVG_COMPONENTS = [
1991
- "Svg",
1992
- "Circle",
1993
- "Ellipse",
1994
- "G",
1995
- "Text",
1996
- "TSpan",
1997
- "TextPath",
1998
- "Path",
1999
- "Polygon",
2000
- "Polyline",
2001
- "Line",
2002
- "Rect",
2003
- "Use",
2004
- "Image",
2005
- "Symbol",
2006
- "Defs",
2007
- "LinearGradient",
2008
- "RadialGradient",
2009
- "Stop",
2010
- "ClipPath",
2011
- "Pattern",
2012
- "Mask",
2013
- "Marker",
2014
- "ForeignObject",
2015
- "FeBlend",
2016
- "FeColorMatrix",
2017
- "FeGaussianBlur",
2018
- "FeMerge",
2019
- "FeOffset"
2020
- ];
2021
- function svg() {
2022
- return builtInPreset({
2023
- name: "svg",
2024
- modules: { "react-native-svg": {
2025
- exports: [
2026
- ...SVG_COMPONENTS,
2027
- "SvgXml",
2028
- "SvgUri",
2029
- "SvgCss",
2030
- "SvgCssUri"
2031
- ],
2032
- factory: () => {
2033
- const make = (name) => {
2034
- const C = react.default.forwardRef((props, ref) => react.default.createElement(name, {
2035
- ...props,
2036
- ref
2037
- }, props.children));
2038
- C.displayName = name;
2039
- return C;
2040
- };
2041
- const out = { __esModule: true };
2042
- for (const name of SVG_COMPONENTS) out[name] = make(name);
2043
- out.SvgXml = make("SvgXml");
2044
- out.SvgUri = make("SvgUri");
2045
- out.SvgCss = make("SvgCss");
2046
- out.SvgCssUri = make("SvgCssUri");
2047
- out.default = out.Svg;
2048
- return out;
2049
- }
2050
- } }
2051
- });
2052
- }
2053
- //#endregion
2054
- //#region src/presets/webview.ts
2055
- function webview() {
2056
- return builtInPreset({
2057
- name: "webview",
2058
- modules: { "react-native-webview": {
2059
- exports: ["WebView"],
2060
- factory: () => {
2061
- const WebView = react.default.forwardRef((props, ref) => {
2062
- react.default.useImperativeHandle(ref, () => ({
2063
- reload: () => {},
2064
- stopLoading: () => {},
2065
- goBack: () => {},
2066
- goForward: () => {},
2067
- injectJavaScript: () => {},
2068
- postMessage: () => {},
2069
- clearCache: () => {}
2070
- }));
2071
- return react.default.createElement("WebView", props, props.children);
2072
- });
2073
- WebView.displayName = "WebView";
2074
- return {
2075
- __esModule: true,
2076
- default: WebView,
2077
- WebView
2078
- };
2079
- }
2080
- } }
2081
- });
2082
- }
2083
- //#endregion
2084
- //#region src/presets/vector-icons.ts
2085
- const DEFAULT_ICON_SIZE = 12;
2086
- const DEFAULT_ICON_COLOR = "black";
2087
- function vectorIcons() {
2088
- return builtInPreset({
2089
- name: "vectorIcons",
2090
- modules: { "@react-native-vector-icons/common": {
2091
- exports: [
2092
- "createIconSet",
2093
- "DEFAULT_ICON_COLOR",
2094
- "DEFAULT_ICON_SIZE",
2095
- "isDynamicLoadingEnabled",
2096
- "isDynamicLoadingSupported",
2097
- "setDynamicLoadingEnabled",
2098
- "setDynamicLoadingErrorCallback"
2099
- ],
2100
- factory: () => {
2101
- const createIconSet = (_glyphMap, _options) => {
2102
- const Icon = react.default.forwardRef((props, ref) => {
2103
- const { size = DEFAULT_ICON_SIZE, color = DEFAULT_ICON_COLOR, style, children, ...rest } = props;
2104
- return react.default.createElement("Text", {
2105
- ref,
2106
- selectable: false,
2107
- ...rest,
2108
- style: [{
2109
- fontSize: size,
2110
- color
2111
- }, style]
2112
- }, children);
2113
- });
2114
- Icon.displayName = "Icon";
2115
- Icon.getImageSource = async () => null;
2116
- Icon.getImageSourceSync = () => null;
2117
- Icon.getFontFamily = () => "";
2118
- Icon.hasIcon = () => false;
2119
- Icon.getRawGlyphMap = () => ({});
2120
- Icon.loadFont = async () => {};
2121
- return Icon;
2122
- };
2123
- const noop = () => {};
2124
- return {
2125
- createIconSet,
2126
- DEFAULT_ICON_COLOR,
2127
- DEFAULT_ICON_SIZE,
2128
- isDynamicLoadingEnabled: () => false,
2129
- isDynamicLoadingSupported: () => false,
2130
- setDynamicLoadingEnabled: noop,
2131
- setDynamicLoadingErrorCallback: noop,
2132
- default: {
2133
- createIconSet,
2134
- DEFAULT_ICON_COLOR,
2135
- DEFAULT_ICON_SIZE
2136
- }
2137
- };
2138
- }
2139
- } }
2140
- });
2141
- }
2142
- //#endregion
2143
- //#region src/presets/flash-list.ts
2144
- function flashList() {
2145
- return builtInPreset({
2146
- name: "flashList",
2147
- modules: { "@shopify/flash-list": {
2148
- exports: [
2149
- "FlashList",
2150
- "AnimatedFlashList",
2151
- "LayoutCommitObserver",
2152
- "RenderTargetOptions",
2153
- "useRecyclingState",
2154
- "useLayoutState",
2155
- "useMappingHelper",
2156
- "useFlashListContext",
2157
- "useBenchmark"
2158
- ],
2159
- factory: () => {
2160
- const renderElement = (Component) => {
2161
- if (Component == null) return null;
2162
- if (react.default.isValidElement(Component)) return Component;
2163
- return react.default.createElement(Component);
2164
- };
2165
- function createFlashList(name) {
2166
- const List = react.default.forwardRef((props, ref) => {
2167
- const { data, renderItem, keyExtractor, extraData, ListHeaderComponent, ListFooterComponent, ListEmptyComponent, ...rest } = props;
2168
- react.default.useImperativeHandle(ref, () => ({
2169
- scrollToEnd: () => {},
2170
- scrollToIndex: () => {},
2171
- scrollToItem: () => {},
2172
- scrollToOffset: () => {},
2173
- scrollToTop: () => {},
2174
- flashScrollIndicators: () => {},
2175
- recordInteraction: () => {},
2176
- recomputeViewableItems: () => {},
2177
- prepareForLayoutAnimationRender: () => {},
2178
- getScrollableNode: () => null,
2179
- getNativeScrollRef: () => null
2180
- }));
2181
- const items = Array.isArray(data) ? data : [];
2182
- const rows = items.length === 0 ? renderElement(ListEmptyComponent) : items.map((item, index) => {
2183
- const element = renderItem ? renderItem({
2184
- item,
2185
- index,
2186
- extraData,
2187
- target: "Cell"
2188
- }) : null;
2189
- if (element == null) return null;
2190
- const key = keyExtractor ? keyExtractor(item, index) : String(index);
2191
- return react.default.createElement(react.default.Fragment, { key }, element);
2192
- });
2193
- return react.default.createElement(name, rest, renderElement(ListHeaderComponent), rows, renderElement(ListFooterComponent));
2194
- });
2195
- List.displayName = name;
2196
- return List;
2197
- }
2198
- const FlashList = createFlashList("FlashList");
2199
- const LayoutCommitObserver = react.default.forwardRef((props, ref) => react.default.createElement("LayoutCommitObserver", {
2200
- ...props,
2201
- ref
2202
- }, props.children));
2203
- LayoutCommitObserver.displayName = "LayoutCommitObserver";
2204
- return {
2205
- __esModule: true,
2206
- default: FlashList,
2207
- FlashList,
2208
- AnimatedFlashList: createFlashList("AnimatedFlashList"),
2209
- LayoutCommitObserver,
2210
- RenderTargetOptions: {
2211
- Cell: "Cell",
2212
- StickyHeader: "StickyHeader",
2213
- Measurement: "Measurement"
2214
- },
2215
- ViewToken: function ViewToken() {},
2216
- useRecyclingState: (initialState) => react.default.useState(initialState),
2217
- useLayoutState: (initialState) => react.default.useState(initialState),
2218
- useMappingHelper: () => ({ getMappingKey: (_item, index) => String(index) }),
2219
- useFlashListContext: () => void 0,
2220
- useBenchmark: () => {}
2221
- };
2222
- }
2223
- } }
2224
- });
2225
- }
2226
- //#endregion
2227
- //#region src/mocks/components/TextInput.ts
2228
- function createTextInputMock() {
2229
- const TextInput = react.default.forwardRef((props, ref) => {
2230
- const instanceMethods = {
2231
- focus: vitest.vi.fn(),
2232
- blur: vitest.vi.fn(),
2233
- clear: vitest.vi.fn(),
2234
- isFocused: vitest.vi.fn(() => false),
2235
- setNativeProps: vitest.vi.fn()
2236
- };
2237
- react.default.useImperativeHandle(ref, () => instanceMethods);
2238
- return react.default.createElement("TextInput", {
2239
- ...props,
2240
- ref
2241
- });
2242
- });
2243
- TextInput.displayName = "TextInput";
2244
- return TextInput;
2245
- }
2246
- //#endregion
2247
- //#region src/mocks/components/ScrollView.ts
2248
- function createScrollViewMock() {
2249
- const ScrollView = react.default.forwardRef((props, ref) => {
2250
- const { children, refreshControl, ...rest } = props;
2251
- const instanceMethods = {
2252
- scrollTo: vitest.vi.fn(),
2253
- scrollToEnd: vitest.vi.fn(),
2254
- flashScrollIndicators: vitest.vi.fn(),
2255
- getScrollResponder: vitest.vi.fn(() => ({})),
2256
- getInnerViewNode: vitest.vi.fn(),
2257
- setNativeProps: vitest.vi.fn()
2258
- };
2259
- react.default.useImperativeHandle(ref, () => instanceMethods);
2260
- return react.default.createElement("RCTScrollView", {
2261
- ...rest,
2262
- ref
2263
- }, refreshControl, react.default.createElement("View", null, children));
2264
- });
2265
- ScrollView.displayName = "ScrollView";
2266
- return ScrollView;
2267
- }
2268
- //#endregion
2269
- //#region src/mocks/components/FlatList.ts
2270
- function createFlatListMock() {
2271
- const FlatList = react.default.forwardRef((props, ref) => {
2272
- const { data, renderItem, keyExtractor, ListHeaderComponent, ListFooterComponent, ListEmptyComponent, ItemSeparatorComponent, refreshControl, ...rest } = props;
2273
- const instanceMethods = {
2274
- scrollToEnd: vitest.vi.fn(),
2275
- scrollToIndex: vitest.vi.fn(),
2276
- scrollToItem: vitest.vi.fn(),
2277
- scrollToOffset: vitest.vi.fn(),
2278
- recordInteraction: vitest.vi.fn(),
2279
- flashScrollIndicators: vitest.vi.fn(),
2280
- getScrollResponder: vitest.vi.fn(() => ({})),
2281
- getNativeScrollRef: vitest.vi.fn(),
2282
- getScrollableNode: vitest.vi.fn(),
2283
- setNativeProps: vitest.vi.fn()
2284
- };
2285
- react.default.useImperativeHandle(ref, () => instanceMethods);
2286
- const children = [];
2287
- if (ListHeaderComponent) children.push(react.default.createElement("FlatList-Header", { key: "__header" }, typeof ListHeaderComponent === "function" ? react.default.createElement(ListHeaderComponent) : ListHeaderComponent));
2288
- if (data && data.length > 0) data.forEach((item, index) => {
2289
- const key = keyExtractor ? keyExtractor(item, index) : String(index);
2290
- children.push(react.default.createElement(react.default.Fragment, { key }, renderItem({
2291
- item,
2292
- index,
2293
- separators: {
2294
- highlight: vitest.vi.fn(),
2295
- unhighlight: vitest.vi.fn(),
2296
- updateProps: vitest.vi.fn()
2297
- }
2298
- })));
2299
- if (ItemSeparatorComponent && index < data.length - 1) children.push(react.default.createElement(react.default.Fragment, { key: `separator-${index}` }, typeof ItemSeparatorComponent === "function" ? react.default.createElement(ItemSeparatorComponent) : ItemSeparatorComponent));
2300
- });
2301
- else if (ListEmptyComponent) children.push(react.default.createElement("FlatList-Empty", { key: "__empty" }, typeof ListEmptyComponent === "function" ? react.default.createElement(ListEmptyComponent) : ListEmptyComponent));
2302
- if (ListFooterComponent) children.push(react.default.createElement("FlatList-Footer", { key: "__footer" }, typeof ListFooterComponent === "function" ? react.default.createElement(ListFooterComponent) : ListFooterComponent));
2303
- if (refreshControl) children.unshift(refreshControl);
2304
- return react.default.createElement("FlatList", {
2305
- ...rest,
2306
- ref
2307
- }, ...children);
2308
- });
2309
- FlatList.displayName = "FlatList";
2310
- return FlatList;
2311
- }
2312
- //#endregion
2313
- //#region src/mocks/components/SectionList.ts
2314
- function createSectionListMock() {
2315
- const SectionList = react.default.forwardRef((props, ref) => {
2316
- const { sections, renderItem, renderSectionHeader, renderSectionFooter, keyExtractor, refreshControl, ListEmptyComponent, ListHeaderComponent, ListFooterComponent, ItemSeparatorComponent, SectionSeparatorComponent, ...rest } = props;
2317
- const instanceMethods = {
2318
- scrollToEnd: vitest.vi.fn(),
2319
- scrollToIndex: vitest.vi.fn(),
2320
- scrollToLocation: vitest.vi.fn(),
2321
- recordInteraction: vitest.vi.fn(),
2322
- flashScrollIndicators: vitest.vi.fn(),
2323
- getScrollResponder: vitest.vi.fn(() => ({})),
2324
- getNativeScrollRef: vitest.vi.fn(),
2325
- getScrollableNode: vitest.vi.fn(),
2326
- setNativeProps: vitest.vi.fn()
2327
- };
2328
- react.default.useImperativeHandle(ref, () => instanceMethods);
2329
- const children = [];
2330
- if (ListHeaderComponent) children.push(react.default.createElement("SectionList-Header", { key: "__header" }, typeof ListHeaderComponent === "function" ? react.default.createElement(ListHeaderComponent) : ListHeaderComponent));
2331
- if (sections) sections.forEach((section, sectionIndex) => {
2332
- if (renderSectionHeader) children.push(react.default.createElement(react.default.Fragment, { key: `header-${sectionIndex}` }, renderSectionHeader({ section })));
2333
- if (SectionSeparatorComponent && sectionIndex > 0) children.push(react.default.createElement(react.default.Fragment, { key: `section-sep-${sectionIndex}` }, typeof SectionSeparatorComponent === "function" ? react.default.createElement(SectionSeparatorComponent) : SectionSeparatorComponent));
2334
- if (section.data) section.data.forEach((item, index) => {
2335
- const key = keyExtractor ? keyExtractor(item, index) : `${sectionIndex}-${index}`;
2336
- children.push(react.default.createElement(react.default.Fragment, { key }, renderItem({
2337
- item,
2338
- index,
2339
- section,
2340
- separators: {
2341
- highlight: vitest.vi.fn(),
2342
- unhighlight: vitest.vi.fn(),
2343
- updateProps: vitest.vi.fn()
2344
- }
2345
- })));
2346
- if (ItemSeparatorComponent && index < section.data.length - 1) children.push(react.default.createElement(react.default.Fragment, { key: `sep-${sectionIndex}-${index}` }, typeof ItemSeparatorComponent === "function" ? react.default.createElement(ItemSeparatorComponent) : ItemSeparatorComponent));
2347
- });
2348
- if (renderSectionFooter) children.push(react.default.createElement(react.default.Fragment, { key: `footer-${sectionIndex}` }, renderSectionFooter({ section })));
2349
- });
2350
- if (ListFooterComponent) children.push(react.default.createElement("SectionList-Footer", { key: "__footer" }, typeof ListFooterComponent === "function" ? react.default.createElement(ListFooterComponent) : ListFooterComponent));
2351
- if (refreshControl) children.unshift(refreshControl);
2352
- if ((!sections || sections.length === 0) && ListEmptyComponent) children.push(react.default.createElement("SectionList-Empty", { key: "__empty" }, typeof ListEmptyComponent === "function" ? react.default.createElement(ListEmptyComponent) : ListEmptyComponent));
2353
- return react.default.createElement("SectionList", {
2354
- ...rest,
2355
- ref
2356
- }, ...children);
2357
- });
2358
- SectionList.displayName = "SectionList";
2359
- return SectionList;
2360
- }
2361
- //#endregion
2362
- //#region src/mocks/components/VirtualizedList.ts
2363
- function createVirtualizedListMock() {
2364
- const VirtualizedList = react.default.forwardRef((props, ref) => {
2365
- const { data, renderItem, keyExtractor, getItemCount, getItem, ListHeaderComponent, ListFooterComponent, ListEmptyComponent, ...rest } = props;
2366
- const instanceMethods = {
2367
- scrollToEnd: vitest.vi.fn(),
2368
- scrollToIndex: vitest.vi.fn(),
2369
- scrollToItem: vitest.vi.fn(),
2370
- scrollToOffset: vitest.vi.fn(),
2371
- recordInteraction: vitest.vi.fn(),
2372
- flashScrollIndicators: vitest.vi.fn(),
2373
- getScrollResponder: vitest.vi.fn(() => ({})),
2374
- getNativeScrollRef: vitest.vi.fn(),
2375
- getScrollableNode: vitest.vi.fn(),
2376
- setNativeProps: vitest.vi.fn()
2377
- };
2378
- react.default.useImperativeHandle(ref, () => instanceMethods);
2379
- const children = [];
2380
- if (ListHeaderComponent) children.push(react.default.createElement("VirtualizedList-Header", { key: "__header" }, typeof ListHeaderComponent === "function" ? react.default.createElement(ListHeaderComponent) : ListHeaderComponent));
2381
- const itemCount = getItemCount ? getItemCount(data) : data ? data.length : 0;
2382
- if (itemCount > 0) for (let index = 0; index < itemCount; index++) {
2383
- const item = getItem ? getItem(data, index) : data[index];
2384
- const key = keyExtractor ? keyExtractor(item, index) : String(index);
2385
- children.push(react.default.createElement(react.default.Fragment, { key }, renderItem({
2386
- item,
2387
- index,
2388
- separators: {}
2389
- })));
2390
- }
2391
- else if (ListEmptyComponent) children.push(react.default.createElement("VirtualizedList-Empty", { key: "__empty" }, typeof ListEmptyComponent === "function" ? react.default.createElement(ListEmptyComponent) : ListEmptyComponent));
2392
- if (ListFooterComponent) children.push(react.default.createElement("VirtualizedList-Footer", { key: "__footer" }, typeof ListFooterComponent === "function" ? react.default.createElement(ListFooterComponent) : ListFooterComponent));
2393
- return react.default.createElement("VirtualizedList", {
2394
- ...rest,
2395
- ref
2396
- }, ...children);
2397
- });
2398
- VirtualizedList.displayName = "VirtualizedList";
2399
- return VirtualizedList;
2400
- }
2401
- //#endregion
2402
- //#region src/mocks/components/TouchableOpacity.ts
2403
- function createTouchableOpacityMock() {
2404
- const TouchableOpacity = react.default.forwardRef((props, ref) => react.default.createElement("TouchableOpacity", buildPressableHostProps(props, ref)));
2405
- TouchableOpacity.displayName = "TouchableOpacity";
2406
- return TouchableOpacity;
2407
- }
2408
- //#endregion
2409
- //#region src/mocks/components/TouchableHighlight.ts
2410
- function createTouchableHighlightMock() {
2411
- const TouchableHighlight = react.default.forwardRef((props, ref) => react.default.createElement("TouchableHighlight", buildPressableHostProps(props, ref)));
2412
- TouchableHighlight.displayName = "TouchableHighlight";
2413
- return TouchableHighlight;
2414
- }
2415
- //#endregion
2416
- //#region src/mocks/components/TouchableWithoutFeedback.ts
2417
- function createTouchableWithoutFeedbackMock() {
2418
- const TouchableWithoutFeedback = react.default.forwardRef((props, ref) => react.default.createElement("TouchableWithoutFeedback", buildPressableHostProps(props, ref)));
2419
- TouchableWithoutFeedback.displayName = "TouchableWithoutFeedback";
2420
- return TouchableWithoutFeedback;
2421
- }
2422
- //#endregion
2423
- //#region src/presets/bottom-sheet.ts
2424
- function bottomSheet() {
2425
- return builtInPreset({
2426
- name: "bottomSheet",
2427
- modules: { "@gorhom/bottom-sheet": {
2428
- exports: [
2429
- "BottomSheetModal",
2430
- "BottomSheetModalProvider",
2431
- "BottomSheetView",
2432
- "BottomSheetDraggableView",
2433
- "BottomSheetScrollView",
2434
- "BottomSheetFlatList",
2435
- "BottomSheetSectionList",
2436
- "BottomSheetVirtualizedList",
2437
- "BottomSheetFlashList",
2438
- "BottomSheetTextInput",
2439
- "BottomSheetBackdrop",
2440
- "BottomSheetFooter",
2441
- "BottomSheetFooterContainer",
2442
- "BottomSheetHandle",
2443
- "TouchableOpacity",
2444
- "TouchableHighlight",
2445
- "TouchableWithoutFeedback",
2446
- "useBottomSheet",
2447
- "useBottomSheetModal",
2448
- "useBottomSheetInternal",
2449
- "useBottomSheetModalInternal",
2450
- "useBottomSheetSpringConfigs",
2451
- "useBottomSheetTimingConfigs",
2452
- "useBottomSheetDynamicSnapPoints",
2453
- "createBottomSheetScrollableComponent",
2454
- "enableLogging",
2455
- "SNAP_POINT_TYPE",
2456
- "SHEET_STATE",
2457
- "SCROLLABLE_TYPE",
2458
- "SCROLLABLE_STATUS",
2459
- "ANIMATION_STATUS",
2460
- "ANIMATION_SOURCE",
2461
- "ANIMATION_METHOD",
2462
- "KEYBOARD_STATUS",
2463
- "GESTURE_SOURCE"
2464
- ],
2465
- factory: () => {
2466
- function container(name, methods = {}) {
2467
- const Component = react.default.forwardRef((props, ref) => {
2468
- react.default.useImperativeHandle(ref, () => methods);
2469
- return react.default.createElement(name, props, props.children);
2470
- });
2471
- Component.displayName = name;
2472
- return Component;
2473
- }
2474
- const sheetMethods = {
2475
- expand: () => {},
2476
- collapse: () => {},
2477
- close: () => {},
2478
- forceClose: () => {},
2479
- snapToIndex: () => {},
2480
- snapToPosition: () => {}
2481
- };
2482
- const modalMethods = {
2483
- ...sheetMethods,
2484
- present: () => {},
2485
- dismiss: () => {}
2486
- };
2487
- return {
2488
- __esModule: true,
2489
- default: container("BottomSheet", sheetMethods),
2490
- BottomSheetModal: container("BottomSheetModal", modalMethods),
2491
- BottomSheetModalProvider: container("BottomSheetModalProvider"),
2492
- BottomSheetView: container("BottomSheetView"),
2493
- BottomSheetDraggableView: container("BottomSheetDraggableView"),
2494
- BottomSheetBackdrop: container("BottomSheetBackdrop"),
2495
- BottomSheetFooter: container("BottomSheetFooter"),
2496
- BottomSheetFooterContainer: container("BottomSheetFooterContainer"),
2497
- BottomSheetHandle: container("BottomSheetHandle"),
2498
- BottomSheetScrollView: createScrollViewMock(),
2499
- BottomSheetFlatList: createFlatListMock(),
2500
- BottomSheetSectionList: createSectionListMock(),
2501
- BottomSheetVirtualizedList: createVirtualizedListMock(),
2502
- BottomSheetFlashList: createFlatListMock(),
2503
- BottomSheetTextInput: createTextInputMock(),
2504
- TouchableOpacity: createTouchableOpacityMock(),
2505
- TouchableHighlight: createTouchableHighlightMock(),
2506
- TouchableWithoutFeedback: createTouchableWithoutFeedbackMock(),
2507
- useBottomSheet: () => ({
2508
- ...sheetMethods,
2509
- animatedIndex: { value: 0 },
2510
- animatedPosition: { value: 0 }
2511
- }),
2512
- useBottomSheetModal: () => ({
2513
- dismiss: vitest.vi.fn(),
2514
- dismissAll: vitest.vi.fn()
2515
- }),
2516
- useBottomSheetInternal: () => ({}),
2517
- useBottomSheetModalInternal: () => ({}),
2518
- useBottomSheetSpringConfigs: (config) => config,
2519
- useBottomSheetTimingConfigs: (config) => config,
2520
- useBottomSheetDynamicSnapPoints: () => ({
2521
- animatedHandleHeight: { value: 0 },
2522
- animatedSnapPoints: { value: [] },
2523
- animatedContentHeight: { value: 0 },
2524
- handleContentLayout: vitest.vi.fn()
2525
- }),
2526
- createBottomSheetScrollableComponent: vitest.vi.fn(() => createScrollViewMock()),
2527
- enableLogging: vitest.vi.fn(),
2528
- SNAP_POINT_TYPE: {
2529
- PROVIDED: 0,
2530
- DYNAMIC: 1
2531
- },
2532
- SHEET_STATE: {
2533
- CLOSED: 0,
2534
- OPENED: 1,
2535
- EXTENDED: 2,
2536
- OVER_EXTENDED: 3,
2537
- FILL_PARENT: 4
2538
- },
2539
- SCROLLABLE_TYPE: {
2540
- UNDETERMINED: 0,
2541
- VIEW: 1,
2542
- FLATLIST: 2,
2543
- SCROLLVIEW: 3,
2544
- SECTIONLIST: 4,
2545
- VIRTUALIZEDLIST: 5
2546
- },
2547
- SCROLLABLE_STATUS: {
2548
- LOCKED: 0,
2549
- UNLOCKED: 1,
2550
- UNDETERMINED: 2
2551
- },
2552
- ANIMATION_STATUS: {
2553
- UNDETERMINED: 0,
2554
- RUNNING: 1,
2555
- STOPPED: 2,
2556
- INTERRUPTED: 3
2557
- },
2558
- ANIMATION_SOURCE: {
2559
- NONE: 0,
2560
- MOUNT: 1,
2561
- GESTURE: 2,
2562
- USER: 3,
2563
- CONTAINER_RESIZE: 4,
2564
- SNAP_POINT_CHANGE: 5,
2565
- KEYBOARD: 6
2566
- },
2567
- ANIMATION_METHOD: {
2568
- TIMING: 0,
2569
- SPRING: 1
2570
- },
2571
- KEYBOARD_STATUS: {
2572
- UNDETERMINED: 0,
2573
- SHOWN: 1,
2574
- HIDDEN: 2
2575
- },
2576
- GESTURE_SOURCE: {
2577
- UNDETERMINED: 0,
2578
- SCROLLABLE: 1,
2579
- HANDLE: 2,
2580
- CONTENT: 3
2581
- }
2582
- };
2583
- }
2584
- } }
2585
- });
2586
- }
2587
- //#endregion
2588
- //#region src/mocks/components/View.ts
2589
- function createViewMock() {
2590
- const View = react.default.forwardRef((props, ref) => {
2591
- return react.default.createElement("View", {
2592
- ...props,
2593
- ref
2594
- });
2595
- });
2596
- View.displayName = "View";
2597
- return View;
2598
- }
2599
- //#endregion
2600
- //#region src/presets/keyboard-controller.ts
2601
- function keyboardController() {
2602
- return builtInPreset({
2603
- name: "keyboardController",
2604
- modules: { "react-native-keyboard-controller": {
2605
- exports: [
2606
- "KeyboardProvider",
2607
- "KeyboardControllerView",
2608
- "KeyboardGestureArea",
2609
- "OverKeyboardView",
2610
- "KeyboardBackgroundView",
2611
- "KeyboardExtender",
2612
- "KeyboardStickyView",
2613
- "KeyboardAvoidingView",
2614
- "KeyboardAwareScrollView",
2615
- "KeyboardChatScrollView",
2616
- "KeyboardToolbar",
2617
- "KeyboardController",
2618
- "KeyboardEvents",
2619
- "AndroidSoftInputModes",
2620
- "DefaultKeyboardToolbarTheme",
2621
- "useKeyboardAnimation",
2622
- "useReanimatedKeyboardAnimation",
2623
- "useResizeMode",
2624
- "useGenericKeyboardHandler",
2625
- "useKeyboardHandler",
2626
- "useKeyboardContext",
2627
- "useKeyboardState",
2628
- "useReanimatedFocusedInput",
2629
- "useFocusedInputHandler",
2630
- "useKeyboardController",
2631
- "useWindowDimensions"
2632
- ],
2633
- factory: () => {
2634
- function hostComponent(name) {
2635
- const Component = react.default.forwardRef((props, ref) => react.default.createElement(name, {
2636
- ...props,
2637
- ref
2638
- }, props.children));
2639
- Component.displayName = name;
2640
- return Component;
2641
- }
2642
- const sharedValue = (value) => ({
2643
- value,
2644
- get: () => value,
2645
- set: () => {}
2646
- });
2647
- const animationValues = {
2648
- animated: {
2649
- progress: sharedValue(0),
2650
- height: sharedValue(0)
2651
- },
2652
- reanimated: {
2653
- progress: sharedValue(0),
2654
- height: sharedValue(0)
2655
- }
2656
- };
2657
- const lastKeyboardEvent = {
2658
- height: 0,
2659
- duration: 0,
2660
- timestamp: 0,
2661
- target: 0,
2662
- type: "default",
2663
- appearance: "default"
2664
- };
2665
- const keyboardState = {
2666
- ...lastKeyboardEvent,
2667
- isVisible: false
2668
- };
2669
- const focusedInput = { input: sharedValue({
2670
- target: 1,
2671
- parentScrollViewTarget: -1,
2672
- layout: {
2673
- x: 0,
2674
- y: 0,
2675
- width: 200,
2676
- height: 40,
2677
- absoluteX: 0,
2678
- absoluteY: 100
2679
- }
2680
- }) };
2681
- const KeyboardToolbar = Object.assign(createViewMock(), {
2682
- Background: hostComponent("KeyboardToolbar.Background"),
2683
- Content: hostComponent("KeyboardToolbar.Content"),
2684
- Prev: hostComponent("KeyboardToolbar.Prev"),
2685
- Next: hostComponent("KeyboardToolbar.Next"),
2686
- Done: hostComponent("KeyboardToolbar.Done"),
2687
- Group: hostComponent("KeyboardToolbar.Group")
2688
- });
2689
- return {
2690
- KeyboardProvider: hostComponent("KeyboardProvider"),
2691
- KeyboardControllerView: hostComponent("KeyboardControllerView"),
2692
- KeyboardGestureArea: hostComponent("KeyboardGestureArea"),
2693
- OverKeyboardView: hostComponent("OverKeyboardView"),
2694
- KeyboardBackgroundView: hostComponent("KeyboardBackgroundView"),
2695
- KeyboardExtender: hostComponent("KeyboardExtender"),
2696
- KeyboardStickyView: createViewMock(),
2697
- KeyboardAvoidingView: createViewMock(),
2698
- KeyboardAwareScrollView: createScrollViewMock(),
2699
- KeyboardChatScrollView: createScrollViewMock(),
2700
- KeyboardToolbar,
2701
- KeyboardController: {
2702
- setInputMode: vitest.vi.fn(),
2703
- setDefaultMode: vitest.vi.fn(),
2704
- preload: vitest.vi.fn(),
2705
- dismiss: vitest.vi.fn(() => Promise.resolve()),
2706
- setFocusTo: vitest.vi.fn(),
2707
- isVisible: vitest.vi.fn(() => false),
2708
- state: vitest.vi.fn(() => lastKeyboardEvent),
2709
- viewPositionInWindow: vitest.vi.fn(() => Promise.resolve({
2710
- x: 0,
2711
- y: 0,
2712
- width: 0,
2713
- height: 0
2714
- }))
2715
- },
2716
- KeyboardEvents: { addListener: vitest.vi.fn(() => ({ remove: vitest.vi.fn() })) },
2717
- AndroidSoftInputModes: {
2718
- SOFT_INPUT_ADJUST_NOTHING: 48,
2719
- SOFT_INPUT_ADJUST_PAN: 32,
2720
- SOFT_INPUT_ADJUST_RESIZE: 16,
2721
- SOFT_INPUT_ADJUST_UNSPECIFIED: 0,
2722
- SOFT_INPUT_IS_FORWARD_NAVIGATION: 256,
2723
- SOFT_INPUT_MASK_ADJUST: 240,
2724
- SOFT_INPUT_MASK_STATE: 15,
2725
- SOFT_INPUT_MODE_CHANGED: 512,
2726
- SOFT_INPUT_STATE_ALWAYS_HIDDEN: 3,
2727
- SOFT_INPUT_STATE_ALWAYS_VISIBLE: 5,
2728
- SOFT_INPUT_STATE_HIDDEN: 2,
2729
- SOFT_INPUT_STATE_UNCHANGED: 1,
2730
- SOFT_INPUT_STATE_UNSPECIFIED: 0,
2731
- SOFT_INPUT_STATE_VISIBLE: 4
2732
- },
2733
- DefaultKeyboardToolbarTheme: {
2734
- light: {
2735
- primary: "#2c2c2c",
2736
- disabled: "#B0BEC5",
2737
- background: "#f3f3f4",
2738
- ripple: "#bcbcbcbc"
2739
- },
2740
- dark: {
2741
- primary: "#fafafa",
2742
- disabled: "#707070",
2743
- background: "#2C2C2E",
2744
- ripple: "#F8F8F888"
2745
- }
2746
- },
2747
- useKeyboardAnimation: () => animationValues.animated,
2748
- useReanimatedKeyboardAnimation: () => animationValues.reanimated,
2749
- useResizeMode: () => {},
2750
- useGenericKeyboardHandler: () => {},
2751
- useKeyboardHandler: () => {},
2752
- useKeyboardContext: () => animationValues,
2753
- useKeyboardState: (selector) => selector ? selector(keyboardState) : keyboardState,
2754
- useReanimatedFocusedInput: () => focusedInput,
2755
- useFocusedInputHandler: () => {},
2756
- useKeyboardController: () => ({
2757
- enabled: true,
2758
- setEnabled: vitest.vi.fn()
2759
- }),
2760
- useWindowDimensions: () => ({
2761
- width: 390,
2762
- height: 844,
2763
- scale: 3,
2764
- fontScale: 1
2765
- })
2766
- };
2767
- }
2768
- } }
2769
- });
2770
- }
2771
- //#endregion
2772
- //#region src/presets/worklets.ts
2773
- const RuntimeKind = {
2774
- ReactNative: 1,
2775
- UI: 2,
2776
- Worker: 3
2777
- };
2778
- const NOOP = () => {};
2779
- const ID = (value) => value;
2780
- const invoke = (callback) => callback();
2781
- function worklets() {
2782
- return builtInPreset({
2783
- name: "worklets",
2784
- modules: { "react-native-worklets": {
2785
- exports: [
2786
- "runOnJS",
2787
- "runOnUI",
2788
- "runOnUIAsync",
2789
- "runOnUISync",
2790
- "scheduleOnRN",
2791
- "scheduleOnUI",
2792
- "runOnRuntime",
2793
- "runOnRuntimeAsync",
2794
- "runOnRuntimeSync",
2795
- "scheduleOnRuntime",
2796
- "executeOnUIRuntimeSync",
2797
- "createWorkletRuntime",
2798
- "getRuntimeKind",
2799
- "isRNRuntime",
2800
- "isUIRuntime",
2801
- "isWorkerRuntime",
2802
- "isWorkletRuntime",
2803
- "RuntimeKind",
2804
- "makeShareable",
2805
- "makeShareableCloneRecursive",
2806
- "makeShareableCloneOnUIRecursive",
2807
- "isShareable",
2808
- "isShareableRef",
2809
- "createShareable",
2810
- "shareableMappingCache",
2811
- "createSerializable",
2812
- "isSerializableRef",
2813
- "registerCustomSerializable",
2814
- "serializableMappingCache",
2815
- "createSynchronizable",
2816
- "isSynchronizable",
2817
- "getStaticFeatureFlag",
2818
- "getDynamicFeatureFlag",
2819
- "setDynamicFeatureFlag",
2820
- "callMicrotasks",
2821
- "isWorkletFunction",
2822
- "WorkletsModule",
2823
- "UIRuntimeId"
2824
- ],
2825
- factory: () => {
2826
- const runOnJS = (fn) => fn;
2827
- const runOnUI = (fn) => fn;
2828
- const runOnUIAsync = (worklet, ...args) => Promise.resolve(worklet(...args));
2829
- const api = {
2830
- __esModule: true,
2831
- runOnJS,
2832
- runOnUI,
2833
- runOnUIAsync,
2834
- runOnUISync: invoke,
2835
- scheduleOnRN: (fn, ...args) => fn(...args),
2836
- scheduleOnUI: (worklet, ...args) => worklet(...args),
2837
- runOnRuntime: ID,
2838
- runOnRuntimeAsync: (_runtime, worklet, ...args) => Promise.resolve(worklet(...args)),
2839
- runOnRuntimeSync: (_runtime, worklet, ...args) => worklet(...args),
2840
- scheduleOnRuntime: invoke,
2841
- executeOnUIRuntimeSync: ID,
2842
- callMicrotasks: NOOP,
2843
- createWorkletRuntime: () => ({}),
2844
- getRuntimeKind: () => RuntimeKind.ReactNative,
2845
- RuntimeKind,
2846
- isRNRuntime: () => true,
2847
- isUIRuntime: () => false,
2848
- isWorkerRuntime: () => false,
2849
- isWorkletRuntime: () => false,
2850
- UIRuntimeId: 1,
2851
- makeShareable: ID,
2852
- makeShareableCloneRecursive: ID,
2853
- makeShareableCloneOnUIRecursive: ID,
2854
- createShareable: ID,
2855
- isShareable: () => false,
2856
- isShareableRef: () => true,
2857
- shareableMappingCache: /* @__PURE__ */ new Map(),
2858
- createSerializable: ID,
2859
- isSerializableRef: ID,
2860
- registerCustomSerializable: NOOP,
2861
- serializableMappingCache: /* @__PURE__ */ new Map(),
2862
- createSynchronizable: ID,
2863
- isSynchronizable: () => false,
2864
- getStaticFeatureFlag: () => false,
2865
- getDynamicFeatureFlag: () => false,
2866
- setDynamicFeatureFlag: NOOP,
2867
- isWorkletFunction: () => false,
2868
- WorkletsModule: {}
2869
- };
2870
- api.default = api;
2871
- return api;
2872
- }
2873
- } }
2874
- });
2875
- }
2876
- //#endregion
2877
- //#region src/presets/unistyles.ts
2878
- let rnCache = null;
2879
- /** The active React Native: the mock engine's, or real RN under the native engine. */
2880
- function getRN() {
2881
- if (rnCache) return rnCache;
2882
- try {
2883
- const base = node_path.default.join(process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd(), "package.json");
2884
- rnCache = (0, node_module.createRequire)(base)("react-native");
2885
- } catch {
2886
- rnCache = {};
2887
- }
2888
- return rnCache;
2889
- }
2890
- const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2891
- /** src/utils.ts `deepMergeObjects` (withUnistyles' merge). */
2892
- function deepMergeObjects(...sources) {
2893
- const target = {};
2894
- for (const source of sources) {
2895
- if (source === void 0 || source === null) continue;
2896
- for (const key of Object.keys(source)) {
2897
- const sourceValue = source[key];
2898
- const targetValue = target[key];
2899
- target[key] = Object(sourceValue) === sourceValue && Object(targetValue) === targetValue ? deepMergeObjects(targetValue, sourceValue) : sourceValue;
2900
- }
2901
- }
2902
- return target;
2903
- }
2904
- /** cxx/common/Helpers.h `isPlatformColor`: PlatformColor, DynamicColorIOS, Android resources. */
2905
- function isPlatformColor(value) {
2906
- const jsiObject = (v) => v !== null && typeof v === "object";
2907
- return jsiObject(value.semantic) || jsiObject(value.dynamic) && "dark" in value.dynamic && "light" in value.dynamic || jsiObject(value.resource_paths);
2908
- }
2909
- const MQ = /:([hw])\[(\d+)(?:,\s*(\d+|Infinity))?]/;
2910
- const MQ_WIDTH = /:(w)\[(\d+)(?:,\s*(\d+|Infinity))?]/;
2911
- const MQ_HEIGHT = /:(h)\[(\d+)(?:,\s*(\d+|Infinity))?]/;
2912
- /** cxx/core/MediaQueries.cpp: an `mq` style key's range; no upper bound means exactly `from`. */
2913
- function styleMqMatches(key, screen) {
2914
- if (!MQ.test(key)) return false;
2915
- const range = (match) => {
2916
- if (!match) return void 0;
2917
- const from = Number(match[2]);
2918
- return {
2919
- from,
2920
- to: match[3] === void 0 ? from : match[3] === "Infinity" ? Infinity : Number(match[3])
2921
- };
2922
- };
2923
- const width = range(MQ_WIDTH.exec(key));
2924
- const height = range(MQ_HEIGHT.exec(key));
2925
- if (width && width.from > width.to || height && height.from > height.to) return false;
2926
- const within = (r, value) => !r || value >= r.from && value <= r.to;
2927
- return within(width, screen.width) && within(height, screen.height);
2928
- }
2929
- /** src/utils.ts `parseMq` and `isValidMq`, and useMedia's visibility rule (Display/Hide). */
2930
- function mediaMatches(query, screen) {
2931
- if (typeof query !== "string" || !MQ.test(query)) return false;
2932
- const [, w, fromW, toW] = MQ_WIDTH.exec(query) || [];
2933
- const [, h, fromH, toH] = MQ_HEIGHT.exec(query) || [];
2934
- const bound = (present, value) => !present || value === "Infinity" || value === void 0 ? void 0 : Number(value);
2935
- const minWidth = bound(w, fromW);
2936
- const maxWidth = bound(w, toW);
2937
- const minHeight = bound(h, fromH);
2938
- const maxHeight = bound(h, toH);
2939
- if (minWidth !== void 0 && maxWidth !== void 0 && minWidth > maxWidth) return false;
2940
- if (minHeight !== void 0 && maxHeight !== void 0 && minHeight > maxHeight) return false;
2941
- if (minWidth !== void 0 && screen.width < minWidth) return false;
2942
- if (maxWidth !== void 0 && screen.width > maxWidth) return false;
2943
- if (minHeight !== void 0 && screen.height < minHeight) return false;
2944
- if (maxHeight !== void 0 && screen.height > maxHeight) return false;
2945
- return true;
2946
- }
2947
- /** cxx/common/Helpers.h `variantsToPairs`: the selection as the device keys it. */
2948
- function variantPairs(selected) {
2949
- const pairs = /* @__PURE__ */ new Map();
2950
- for (const [name, value] of Object.entries(selected)) if (typeof value === "boolean") pairs.set(name, value ? "true" : "false");
2951
- else if (typeof value === "string") pairs.set(name, value);
2952
- else if (typeof value === "number") pairs.set(name, String(Math.trunc(value)));
2953
- return pairs;
2954
- }
2955
- /** cxx/parser/Parser.cpp `getValueFromBreakpoints`: `mq` keys first, then breakpoints down. */
2956
- function valueFromBreakpoints(value, ctx) {
2957
- for (const key of Object.keys(value)) if (styleMqMatches(key, ctx.screen)) return value[key];
2958
- const orientation = ctx.screen.width > ctx.screen.height ? "landscape" : "portrait";
2959
- if (ctx.sortedBreakpoints.length === 0 && orientation in value) return value[orientation];
2960
- if (ctx.breakpoint === void 0) return void 0;
2961
- const index = ctx.sortedBreakpoints.findIndex(([name]) => name === ctx.breakpoint);
2962
- for (let i = index; i >= 0; i--) {
2963
- const name = ctx.sortedBreakpoints[i][0];
2964
- if (name in value) return value[name];
2965
- }
2966
- }
2967
- /** cxx/parser/Parser.cpp `parseSecondLevel`. */
2968
- function parseSecondLevel(value, ctx) {
2969
- if (value === null || typeof value !== "object") return typeof value === "string" || typeof value === "number" || value == null ? value : void 0;
2970
- if (Array.isArray(value)) return void 0;
2971
- if (isPlatformColor(value)) return value;
2972
- const parsed = {};
2973
- for (const [key, nested] of Object.entries(value)) if (key === "boxShadow" && typeof nested === "string") parsed[key] = nested;
2974
- else if (nested === null || typeof nested !== "object") parsed[key] = typeof nested === "function" ? void 0 : nested;
2975
- else if (isPlatformColor(nested)) parsed[key] = nested;
2976
- else if (key === "transform" && Array.isArray(nested)) parsed[key] = parseTransforms(nested, ctx);
2977
- else if ((key === "boxShadow" || key === "filter") && Array.isArray(nested)) parsed[key] = nested.filter(isObject).map((item) => parseSecondLevel(item, ctx));
2978
- else if (key === "fontVariant") parsed[key] = nested;
2979
- else if (key === "shadowOffset" || key === "textShadowOffset" || key === "dropShadow") parsed[key] = parseSecondLevel(nested, ctx);
2980
- else if (!Array.isArray(nested)) parsed[key] = valueFromBreakpoints(nested, ctx);
2981
- return parsed;
2982
- }
2983
- /** cxx/parser/Parser.cpp `parseTransforms`: an entry whose value resolves to undefined is dropped. */
2984
- function parseTransforms(transforms, ctx) {
2985
- return transforms.filter(isObject).map((item) => parseSecondLevel(item, ctx)).filter((item) => Object.values(item).some((v) => v !== void 0));
2986
- }
2987
- /** cxx/parser/Parser.cpp `parseVariants`, `getStylesForVariant`, `parseCompoundVariants`. */
2988
- function variantStyles(style, selected, ctx) {
2989
- const pairs = variantPairs(selected);
2990
- const parsed = {};
2991
- for (const [group, options] of Object.entries(style.variants)) {
2992
- const chosen = pairs.get(group);
2993
- const key = chosen ?? "default";
2994
- const hasKey = isObject(options) && key in options;
2995
- if (!hasKey || chosen === void 0) pairs.set(group, key);
2996
- const styles = hasKey ? options[key] : void 0;
2997
- if (isObject(styles)) Object.assign(parsed, parseSecondLevel(styles, ctx));
2998
- }
2999
- if (Array.isArray(style.compoundVariants) && pairs.size > 0) for (const compound of style.compoundVariants) {
3000
- if (!isObject(compound)) continue;
3001
- if ([...pairs].every(([group, value]) => {
3002
- if (!(group in compound)) return true;
3003
- const condition = compound[group];
3004
- return (typeof condition === "boolean" ? String(condition) : typeof condition === "string" ? condition : "") === value;
3005
- })) Object.assign(parsed, parseSecondLevel(compound.styles, ctx));
3006
- }
3007
- return parsed;
3008
- }
3009
- /** cxx/parser/Parser.cpp `parseFirstLevel`: one style as the device applies it. */
3010
- function parseStyle(style, selected, ctx) {
3011
- if (!isObject(style)) return style;
3012
- const parsed = {};
3013
- for (const [key, value] of Object.entries(style)) {
3014
- if (key === "_web" || key === "uni__dependencies") continue;
3015
- if (key === "variants" || key === "compoundVariants") continue;
3016
- if (key === "boxShadow" && typeof value === "string") parsed[key] = value;
3017
- else if (typeof value === "number" || typeof value === "string" || value == null) parsed[key] = value;
3018
- else if (typeof value === "boolean") {
3019
- if (key === "includeFontPadding") parsed[key] = value;
3020
- } else if (typeof value !== "object") {} else if (key === "transform" && Array.isArray(value)) parsed[key] = parseTransforms(value, ctx);
3021
- else if ((key === "boxShadow" || key === "filter") && Array.isArray(value)) parsed[key] = value.filter(isObject).map((item) => parseSecondLevel(item, ctx));
3022
- else if (key === "fontVariant" && Array.isArray(value)) parsed[key] = value;
3023
- else if (key === "shadowOffset" || key === "textShadowOffset") parsed[key] = parseSecondLevel(value, ctx);
3024
- else if (isPlatformColor(value)) parsed[key] = value;
3025
- else if (Array.isArray(value)) parsed[key] = void 0;
3026
- else parsed[key] = parseSecondLevel(valueFromBreakpoints(value, ctx), ctx);
3027
- }
3028
- if (isObject(style.variants)) Object.assign(parsed, variantStyles(style, selected, ctx));
3029
- return parsed;
3030
- }
3031
- /** src/specs/NativePlatform/NativePlatform.nitro.ts */
3032
- const UnistyleDependency = {
3033
- Theme: 0,
3034
- ThemeName: 1,
3035
- AdaptiveThemes: 2,
3036
- Breakpoints: 3,
3037
- Variants: 4,
3038
- ColorScheme: 5,
3039
- Dimensions: 6,
3040
- Orientation: 7,
3041
- ContentSizeCategory: 8,
3042
- Insets: 9,
3043
- PixelRatio: 10,
3044
- FontScale: 11,
3045
- StatusBar: 12,
3046
- NavigationBar: 13,
3047
- Ime: 14,
3048
- Rtl: 15
3049
- };
3050
- for (const [name, value] of Object.entries({ ...UnistyleDependency })) UnistyleDependency[value] = name;
3051
- function unistyles() {
3052
- return builtInPreset({
3053
- name: "unistyles",
3054
- modules: {
3055
- "react-native-unistyles": {
3056
- exports: [
3057
- "StyleSheet",
3058
- "UnistylesRuntime",
3059
- "UnistyleDependency",
3060
- "ColorScheme",
3061
- "Orientation",
3062
- "StatusBarStyle",
3063
- "mq",
3064
- "withUnistyles",
3065
- "useUnistyles",
3066
- "createUnistylesElement",
3067
- "IOSContentSizeCategory",
3068
- "AndroidContentSizeCategory",
3069
- "WebContentSizeCategory",
3070
- "Display",
3071
- "Hide",
3072
- "ScopedTheme",
3073
- "useServerUnistyles",
3074
- "hydrateServerUnistyles",
3075
- "getServerUnistyles",
3076
- "resetServerUnistyles"
3077
- ],
3078
- factory: () => buildUnistyles()
3079
- },
3080
- "react-native-unistyles/reanimated": {
3081
- exports: ["useAnimatedTheme", "useAnimatedVariantColor"],
3082
- factory: () => {
3083
- const shared = (value) => ({
3084
- value,
3085
- get: () => value,
3086
- set: vitest.vi.fn()
3087
- });
3088
- const unistylesModule = globalThis.__vitest_native_preset_mocks?.["react-native-unistyles"];
3089
- return {
3090
- useAnimatedTheme: vitest.vi.fn(() => shared(unistylesModule?.useUnistyles().theme ?? {})),
3091
- useAnimatedVariantColor: vitest.vi.fn(() => ({
3092
- fromValue: shared("#000000"),
3093
- toValue: shared("#FFFFFF")
3094
- }))
3095
- };
3096
- }
3097
- }
3098
- }
3099
- });
3100
- }
3101
- function buildUnistyles() {
3102
- const configured = () => ({
3103
- themes: {},
3104
- sortedBreakpoints: [],
3105
- themeName: void 0,
3106
- prefersAdaptive: false,
3107
- usePoints: false,
3108
- configured: false
3109
- });
3110
- let resting = configured();
3111
- let registry = configured();
3112
- let scopedTheme;
3113
- let version = 0;
3114
- const listeners = /* @__PURE__ */ new Set();
3115
- const notify = () => {
3116
- version++;
3117
- for (const listener of listeners) listener();
3118
- };
3119
- const subscribe = (listener) => {
3120
- listeners.add(listener);
3121
- const onPlatformChange = () => {
3122
- version++;
3123
- listener();
3124
- };
3125
- const appearance = getRN().Appearance?.addChangeListener?.(onPlatformChange);
3126
- const dimensions = getRN().Dimensions?.addEventListener?.("change", onPlatformChange);
3127
- return () => {
3128
- listeners.delete(listener);
3129
- appearance?.remove?.();
3130
- dimensions?.remove?.();
3131
- };
3132
- };
3133
- const useRuntimeVersion = () => react.default.useSyncExternalStore(subscribe, () => version);
3134
- const deviceError = (message, cause) => new Error(message, cause === void 0 ? void 0 : { cause });
3135
- const assertThat = (condition, message) => {
3136
- if (!condition) throw deviceError(message);
3137
- };
3138
- const hasAdaptiveThemes = () => registry.prefersAdaptive && "light" in registry.themes && "dark" in registry.themes;
3139
- const rawScreen = () => {
3140
- const dims = getRN().Dimensions?.get?.("screen");
3141
- return {
3142
- width: dims?.width ?? 0,
3143
- height: dims?.height ?? 0
3144
- };
3145
- };
3146
- const pixelRatio = () => getRN().PixelRatio?.get?.() ?? 1;
3147
- /** HybridStyleSheet::parseBreakpoints / Parser: points mode divides by the pixel ratio. */
3148
- const breakpointScreen = () => {
3149
- const screen = rawScreen();
3150
- const ratio = registry.usePoints ? pixelRatio() : 1;
3151
- return {
3152
- width: screen.width / ratio,
3153
- height: screen.height / ratio
3154
- };
3155
- };
3156
- const colorScheme = () => getRN().Appearance?.getColorScheme?.() ?? "unspecified";
3157
- /** helpers::getBreakpointFromScreenWidth */
3158
- const currentBreakpoint = () => {
3159
- const pairs = registry.sortedBreakpoints;
3160
- if (pairs.length === 0) return void 0;
3161
- const width = Math.trunc(breakpointScreen().width);
3162
- let found = pairs[0][0];
3163
- for (const [name, min] of pairs) if (width >= min) found = name;
3164
- return found;
3165
- };
3166
- /** The selected theme: adaptive themes follow the colour scheme (HybridUnistylesRuntime). */
3167
- const selectedThemeName = () => hasAdaptiveThemes() ? colorScheme() === "dark" ? "dark" : "light" : registry.themeName;
3168
- const themeNameInScope = () => scopedTheme ?? selectedThemeName();
3169
- const themeByName = (name) => {
3170
- if (name !== void 0 && name === scopedTheme) assertThat(name in registry.themes, `Unistyles: You're trying to use scoped theme '${name}' but it wasn't registered.`);
3171
- return name !== void 0 && registry.themes[name] || Object.values(registry.themes)[0] || {};
3172
- };
3173
- const currentTheme = () => themeByName(themeNameInScope());
3174
- const insets = {
3175
- top: 0,
3176
- left: 0,
3177
- right: 0,
3178
- bottom: 0,
3179
- ime: 0
3180
- };
3181
- const bar = {
3182
- width: 0,
3183
- height: 0
3184
- };
3185
- const miniRuntime = {
3186
- get themeName() {
3187
- return themeNameInScope();
3188
- },
3189
- get breakpoint() {
3190
- return currentBreakpoint();
3191
- },
3192
- get hasAdaptiveThemes() {
3193
- return hasAdaptiveThemes();
3194
- },
3195
- get colorScheme() {
3196
- return colorScheme();
3197
- },
3198
- contentSizeCategory: "Medium",
3199
- insets,
3200
- get pixelRatio() {
3201
- return pixelRatio();
3202
- },
3203
- get fontScale() {
3204
- return getRN().PixelRatio?.getFontScale?.() ?? 1;
3205
- },
3206
- get rtl() {
3207
- return getRN().I18nManager?.isRTL ?? false;
3208
- },
3209
- get isLandscape() {
3210
- const s = rawScreen();
3211
- return s.width > s.height;
3212
- },
3213
- get isPortrait() {
3214
- const s = rawScreen();
3215
- return s.width <= s.height;
3216
- },
3217
- navigationBar: bar,
3218
- get screen() {
3219
- return rawScreen();
3220
- },
3221
- statusBar: bar
3222
- };
3223
- const assertRegistered = (name, message) => assertThat(name in registry.themes, message);
3224
- const UnistylesRuntime = {
3225
- get themeName() {
3226
- return selectedThemeName();
3227
- },
3228
- get breakpoint() {
3229
- return currentBreakpoint();
3230
- },
3231
- get breakpoints() {
3232
- return Object.fromEntries(registry.sortedBreakpoints);
3233
- },
3234
- get hasAdaptiveThemes() {
3235
- return hasAdaptiveThemes();
3236
- },
3237
- get colorScheme() {
3238
- return colorScheme();
3239
- },
3240
- contentSizeCategory: "Medium",
3241
- get orientation() {
3242
- return miniRuntime.isLandscape ? "landscape" : "portrait";
3243
- },
3244
- get isPortrait() {
3245
- return miniRuntime.isPortrait;
3246
- },
3247
- get isLandscape() {
3248
- return miniRuntime.isLandscape;
3249
- },
3250
- get pixelRatio() {
3251
- return miniRuntime.pixelRatio;
3252
- },
3253
- get fontScale() {
3254
- return miniRuntime.fontScale;
3255
- },
3256
- get rtl() {
3257
- return miniRuntime.rtl;
3258
- },
3259
- insets,
3260
- get screen() {
3261
- return rawScreen();
3262
- },
3263
- miniRuntime,
3264
- name: "UnistylesRuntime",
3265
- statusBar: {
3266
- ...bar,
3267
- name: "StatusBar",
3268
- setHidden: vitest.vi.fn(),
3269
- setStyle: vitest.vi.fn(),
3270
- equals: () => false
3271
- },
3272
- navigationBar: {
3273
- ...bar,
3274
- name: "NavigationBar",
3275
- setHidden: vitest.vi.fn(),
3276
- dispose: vitest.vi.fn(),
3277
- equals: () => false
3278
- },
3279
- getTheme: vitest.vi.fn((name) => {
3280
- if (name === void 0) return themeByName(selectedThemeName());
3281
- assertRegistered(name, `Unistyles: You're trying to get theme '${name}' but it wasn't registered.`);
3282
- return registry.themes[name];
3283
- }),
3284
- setTheme: vitest.vi.fn((name) => {
3285
- assertThat(!hasAdaptiveThemes(), `Unistyles: You're trying to set theme to: '${name}', but adaptiveThemes are enabled.`);
3286
- assertRegistered(name, `Unistyles: You're trying to set theme to: '${name}', but it wasn't registered.`);
3287
- registry.themeName = name;
3288
- notify();
3289
- }),
3290
- updateTheme: vitest.vi.fn((name, updater) => {
3291
- assertRegistered(name, `Unistyles: You're trying to update theme '${name}' but it wasn't registered.`);
3292
- registry.themes = {
3293
- ...registry.themes,
3294
- [name]: updater(registry.themes[name])
3295
- };
3296
- notify();
3297
- }),
3298
- setAdaptiveThemes: vitest.vi.fn((enabled) => {
3299
- registry.themeName = selectedThemeName();
3300
- registry.prefersAdaptive = enabled;
3301
- notify();
3302
- }),
3303
- setImmersiveMode: vitest.vi.fn(),
3304
- setRootViewBackgroundColor: vitest.vi.fn(),
3305
- dispose: vitest.vi.fn(),
3306
- equals: () => false
3307
- };
3308
- const StyleSheet = {
3309
- get absoluteFill() {
3310
- return getRN().StyleSheet.absoluteFill;
3311
- },
3312
- get absoluteFillObject() {
3313
- return getRN().StyleSheet.absoluteFill;
3314
- },
3315
- /** HybridStyleSheet::getHairlineWidth */
3316
- get hairlineWidth() {
3317
- const ratio = pixelRatio();
3318
- return Math.round(ratio * .4) / ratio || 1 / ratio;
3319
- },
3320
- compose: (a, b) => getRN().StyleSheet.compose(a, b),
3321
- flatten: (style) => getRN().StyleSheet.flatten(style),
3322
- create: vitest.vi.fn((stylesheet) => {
3323
- assertThat(typeof stylesheet === "function" || isObject(stylesheet), "StyleSheet.create expected to be called with object or function.");
3324
- let selected = {};
3325
- const raw = /* @__PURE__ */ new Map();
3326
- const parsed = /* @__PURE__ */ new Map();
3327
- const stateKey = () => {
3328
- const screen = rawScreen();
3329
- return [
3330
- version,
3331
- themeNameInScope(),
3332
- screen.width,
3333
- screen.height,
3334
- colorScheme(),
3335
- pixelRatio(),
3336
- miniRuntime.rtl
3337
- ].join("|");
3338
- };
3339
- const resolve = (key) => {
3340
- if (typeof stylesheet !== "function") return stylesheet;
3341
- const cached = raw.get(key);
3342
- if (cached) return cached;
3343
- let sheet;
3344
- try {
3345
- sheet = stylesheet(currentTheme(), miniRuntime);
3346
- } catch (error) {
3347
- if (registry.configured) throw error;
3348
- throw deviceError("Unistyles: One of your stylesheets is trying to get the theme, but no theme has been selected yet. Did you forget to call StyleSheet.configure? If you called it, make sure you did so before any StyleSheet.create. In tests, import the module that calls StyleSheet.configure from a setup file.", error);
3349
- }
3350
- raw.clear();
3351
- raw.set(key, sheet);
3352
- return sheet;
3353
- };
3354
- const context = () => ({
3355
- screen: breakpointScreen(),
3356
- sortedBreakpoints: registry.sortedBreakpoints,
3357
- breakpoint: currentBreakpoint()
3358
- });
3359
- const styles = { useVariants: vitest.vi.fn((variants) => {
3360
- selected = { ...variants };
3361
- }) };
3362
- const initial = resolve(stateKey());
3363
- for (const [name, value] of Object.entries(initial)) assertThat(typeof value === "function" || isObject(value), `Unistyles: Style with name '${name}' is not a function or object.`);
3364
- for (const name of Object.keys(initial)) Object.defineProperty(styles, name, {
3365
- enumerable: true,
3366
- get() {
3367
- const key = stateKey();
3368
- const value = resolve(key)[name];
3369
- if (typeof value === "function") return (...args) => parseStyle(value(...args), selected, context());
3370
- const cacheKey = `${key}|${name}|${JSON.stringify(selected)}`;
3371
- if (!parsed.has(cacheKey)) {
3372
- if (parsed.size > 256) parsed.clear();
3373
- parsed.set(cacheKey, parseStyle(value, selected, context()));
3374
- }
3375
- return parsed.get(cacheKey);
3376
- }
3377
- });
3378
- return styles;
3379
- }),
3380
- configure: vitest.vi.fn((config) => {
3381
- const next = {
3382
- ...registry,
3383
- configured: true
3384
- };
3385
- let initialTheme;
3386
- for (const [key, value] of Object.entries(config ?? {})) if (key === "settings") {
3387
- assertThat(isObject(value), "StyleSheet.configure's settings must be an object.");
3388
- next.usePoints = false;
3389
- for (const [setting, settingValue] of Object.entries(value)) if (setting === "adaptiveThemes") {
3390
- assertThat(typeof settingValue === "boolean", "StyleSheet.configure's adaptiveThemes must be of boolean type.");
3391
- next.prefersAdaptive = settingValue;
3392
- } else if (setting === "initialTheme") {
3393
- if (typeof settingValue === "function") {
3394
- const result = settingValue();
3395
- assertThat(typeof result === "string", "StyleSheet.configure's initialTheme resolved from function is not a string. Please check your initialTheme function.");
3396
- initialTheme = result;
3397
- } else {
3398
- assertThat(typeof settingValue === "string", "StyleSheet.configure's initialTheme must be either a string or a function.");
3399
- initialTheme = settingValue;
3400
- }
3401
- } else if (setting === "nativeBreakpointsMode") {
3402
- assertThat(typeof settingValue === "string", "StyleSheet.configure's nativeBreakpointsMode must be a string");
3403
- assertThat(settingValue === "pixels" || settingValue === "points", "StyleSheet.configure's nativeBreakpointsMode must be one of: pixels or points");
3404
- next.usePoints = settingValue === "points";
3405
- } else if (setting !== "CSSVars") throw deviceError(`StyleSheet.configure's settings received unexpected key: '${setting}'`);
3406
- } else if (key === "breakpoints") {
3407
- assertThat(isObject(value), "StyleSheet.configure's breakpoints must be an object.");
3408
- const pairs = Object.entries(value).map(([name, min]) => {
3409
- assertThat(typeof min === "number", `value for breakpoint ${name} is not a number.`);
3410
- return [name, min];
3411
- });
3412
- pairs.sort(([, a], [, b]) => a - b);
3413
- assertThat(pairs.length > 0, "StyleSheet.configure's breakpoints can't be empty.");
3414
- assertThat(pairs[0][1] === 0, "StyleSheet.configure's first breakpoint must start from 0.");
3415
- next.sortedBreakpoints = pairs;
3416
- } else if (key === "themes") {
3417
- assertThat(isObject(value), "StyleSheet.configure's themes must be an object.");
3418
- const themes = { ...next.themes };
3419
- for (const [name, theme] of Object.entries(value)) {
3420
- assertThat(isObject(theme), `StyleSheet.configure's registered theme '${name}' must be an object.`);
3421
- themes[name] = theme;
3422
- }
3423
- next.themes = themes;
3424
- } else throw deviceError(`StyleSheet.configure received unexpected key: '${key}'.`);
3425
- const names = Object.keys(next.themes);
3426
- const adaptive = next.prefersAdaptive && "light" in next.themes && "dark" in next.themes;
3427
- assertThat(!next.prefersAdaptive || adaptive, "Unistyles: You're trying to enable adaptiveThemes, but you didn't register both 'light' and 'dark' themes.");
3428
- if (initialTheme === void 0) {
3429
- if (!adaptive && names.length === 1) next.themeName = names[0];
3430
- } else {
3431
- assertThat(!adaptive, "Unistyles: You're trying to set initial theme and enable adaptiveThemes, but these options are mutually exclusive.");
3432
- assertThat(initialTheme in next.themes, `Unistyles: You're trying to select theme '${initialTheme}' but it wasn't registered.`);
3433
- next.themeName = initialTheme;
3434
- }
3435
- registry = next;
3436
- resting = { ...next };
3437
- notify();
3438
- }),
3439
- addChangeListener: vitest.vi.fn(() => () => {}),
3440
- init: vitest.vi.fn(),
3441
- jsMethods: {
3442
- processColor: () => null,
3443
- parseBoxShadowString: () => []
3444
- },
3445
- name: "StyleSheet",
3446
- dispose: vitest.vi.fn(),
3447
- equals: () => false
3448
- };
3449
- const mqValue = (value) => {
3450
- if (typeof value === "number") return value;
3451
- if (value === null || value === void 0) return 0;
3452
- return Object.fromEntries(registry.sortedBreakpoints)[value] ?? 0;
3453
- };
3454
- const range = (axis, min = 0, max = Number.POSITIVE_INFINITY) => `:${axis}[${mqValue(min)}, ${mqValue(max)}]`;
3455
- const mq = {
3456
- only: {
3457
- width: (min, max) => range("w", min, max),
3458
- height: (min, max) => range("h", min, max)
3459
- },
3460
- width: (wMin, wMax) => ({ and: { height: (hMin, hMax) => range("w", wMin, wMax) + range("h", hMin, hMax) } }),
3461
- height: (hMin, hMax) => ({ and: { width: (wMin, wMax) => range("w", wMin, wMax) + range("h", hMin, hMax) } })
3462
- };
3463
- /** src/core/useUnistyles: the theme in scope when the component mounted. */
3464
- const useUnistyles = () => {
3465
- useRuntimeVersion();
3466
- const [scoped] = react.default.useState(scopedTheme);
3467
- return {
3468
- theme: scoped !== void 0 ? themeByName(scoped) : currentTheme(),
3469
- rt: UnistylesRuntime
3470
- };
3471
- };
3472
- function Display({ mq: query, children }) {
3473
- useRuntimeVersion();
3474
- return mediaMatches(query, rawScreen()) ? react.default.createElement(react.default.Fragment, null, children) : null;
3475
- }
3476
- function Hide({ mq: query, children }) {
3477
- useRuntimeVersion();
3478
- return mediaMatches(query, rawScreen()) ? null : react.default.createElement(react.default.Fragment, null, children);
3479
- }
3480
- function ApplyScopedTheme({ name }) {
3481
- scopedTheme = name;
3482
- react.default.useLayoutEffect(() => {
3483
- scopedTheme = name;
3484
- });
3485
- return null;
3486
- }
3487
- const withScope = (name, previous, children) => react.default.createElement(react.default.Fragment, null, react.default.createElement(ApplyScopedTheme, {
3488
- key: "apply",
3489
- name
3490
- }), children, react.default.createElement(ApplyScopedTheme, {
3491
- key: "dispose",
3492
- name: previous
3493
- }));
3494
- function ScopedTheme({ name, invertedAdaptive, reset, children }) {
3495
- useRuntimeVersion();
3496
- const previous = scopedTheme;
3497
- if (name !== void 0) return withScope(name, previous, children);
3498
- if (invertedAdaptive && hasAdaptiveThemes()) return withScope(colorScheme() === "dark" ? "light" : "dark", previous, children);
3499
- if (reset) return withScope(void 0, previous, children);
3500
- return react.default.createElement(react.default.Fragment, null, children);
3501
- }
3502
- /** src/core/withUnistyles/withUnistyles.native.tsx */
3503
- const flattenStyle = (style) => (Array.isArray(style) ? style.flat(Infinity) : [style]).filter(Boolean).reduce((merged, item) => Object.assign(merged, item), {});
3504
- const withUnistyles = (Component, mappings) => react.default.forwardRef((props, ref) => {
3505
- const { theme } = useUnistyles();
3506
- const { key: mappingsKey, ...mappingsProps } = mappings?.(theme, miniRuntime) ?? {};
3507
- const { key: uniPropsKey, ...uniProps } = props.uniProps?.(theme, miniRuntime) ?? {};
3508
- const finalProps = {
3509
- ...deepMergeObjects(mappingsProps, uniProps, props),
3510
- ...props.style ? { style: flattenStyle(props.style) } : {},
3511
- ...props.contentContainerStyle ? { contentContainerStyle: flattenStyle(props.contentContainerStyle) } : {}
3512
- };
3513
- return react.default.createElement(Component, {
3514
- key: uniPropsKey || mappingsKey,
3515
- ...finalProps,
3516
- ref
3517
- });
3518
- });
3519
- return {
3520
- StyleSheet,
3521
- UnistylesRuntime,
3522
- UnistyleDependency,
3523
- ColorScheme: {
3524
- Light: "light",
3525
- Dark: "dark",
3526
- Unspecified: "unspecified"
3527
- },
3528
- Orientation: {
3529
- Portrait: "portrait",
3530
- Landscape: "landscape"
3531
- },
3532
- StatusBarStyle: {
3533
- Default: "default",
3534
- Light: "light",
3535
- Dark: "dark"
3536
- },
3537
- IOSContentSizeCategory: {
3538
- AccessibilityExtraExtraExtraLarge: "accessibilityExtraExtraExtraLarge",
3539
- AccessibilityExtraExtraLarge: "accessibilityExtraExtraLarge",
3540
- AccessibilityExtraLarge: "accessibilityExtraLarge",
3541
- AccessibilityLarge: "accessibilityLarge",
3542
- AccessibilityMedium: "accessibilityMedium",
3543
- ExtraExtraExtraLarge: "xxxLarge",
3544
- ExtraExtraLarge: "xxLarge",
3545
- ExtraLarge: "xLarge",
3546
- Large: "Large",
3547
- Medium: "Medium",
3548
- Small: "Small",
3549
- ExtraSmall: "xSmall",
3550
- Unspecified: "unspecified"
3551
- },
3552
- AndroidContentSizeCategory: {
3553
- Small: "Small",
3554
- Default: "Default",
3555
- Large: "Large",
3556
- ExtraLarge: "ExtraLarge",
3557
- Huge: "Huge",
3558
- ExtraHuge: "ExtraHuge",
3559
- ExtraExtraHuge: "ExtraExtraHuge"
3560
- },
3561
- WebContentSizeCategory: { Unspecified: "web-unspecified" },
3562
- mq,
3563
- useUnistyles,
3564
- withUnistyles,
3565
- createUnistylesElement: (Component) => Component,
3566
- Display,
3567
- Hide,
3568
- ScopedTheme,
3569
- useServerUnistyles: () => null,
3570
- hydrateServerUnistyles: () => {},
3571
- getServerUnistyles: () => null,
3572
- resetServerUnistyles: () => {},
3573
- _reset: () => {
3574
- registry = {
3575
- ...resting,
3576
- themes: { ...resting.themes }
3577
- };
3578
- scopedTheme = void 0;
3579
- version++;
3580
- }
3581
- };
3582
- }
3583
- //#endregion
3584
- //#region src/presets/esm-export-names.ts
3585
- /** Metro's order for a module path without an extension: platform files first. */
3586
- function sourceExtensions(platform) {
3587
- return [
3588
- `.${platform}.js`,
3589
- ".native.js",
3590
- ".js"
3591
- ];
3592
- }
3593
- function resolveRelative(from, request, extensions) {
3594
- const base = node_path.default.resolve(node_path.default.dirname(from), request);
3595
- for (const candidate of [
3596
- base,
3597
- ...extensions.map((ext) => base + ext),
3598
- ...extensions.map((ext) => node_path.default.join(base, `index${ext}`))
3599
- ]) if (node_fs.default.statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
3600
- throw new require_errors.VitestNativeError("PRESET_UNAVAILABLE", `cannot resolve '${request}' from ${from}`);
3601
- }
3602
- function bindingNames(pattern, names) {
3603
- if (pattern.type === "Identifier") names.add(pattern.name);
3604
- else if (pattern.type === "ObjectPattern") for (const p of pattern.properties) bindingNames(p.type === "RestElement" ? p : p.value, names);
3605
- else if (pattern.type === "ArrayPattern") {
3606
- for (const p of pattern.elements) if (p) bindingNames(p, names);
3607
- } else if (pattern.type === "RestElement") bindingNames(pattern.argument, names);
3608
- else if (pattern.type === "AssignmentPattern") bindingNames(pattern.left, names);
3609
- }
3610
- function exportedName(node) {
3611
- return node.type === "Literal" ? String(node.value) : node.name;
3612
- }
3613
- /**
3614
- * The named exports of the ESM module `entry` on `platform`, following `export *`
3615
- * through relative paths. `default` is left out: `export *` does not re-export it, and a preset's
3616
- * module serves its default separately.
3617
- */
3618
- function esmExportNames(entry, platform = "ios") {
3619
- const extensions = sourceExtensions(platform);
3620
- const { parseAst } = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)("vite");
3621
- const names = /* @__PURE__ */ new Set();
3622
- const visited = /* @__PURE__ */ new Set();
3623
- const visit = (file) => {
3624
- if (visited.has(file)) return;
3625
- visited.add(file);
3626
- for (const node of parseAst(node_fs.default.readFileSync(file, "utf8")).body) if (node.type === "ExportAllDeclaration") {
3627
- if (node.exported) names.add(exportedName(node.exported));
3628
- else if (String(node.source.value).startsWith(".")) visit(resolveRelative(file, node.source.value, extensions));
3629
- else throw new require_errors.VitestNativeError("PRESET_UNAVAILABLE", `${file} re-exports a package ('${node.source.value}')`);
3630
- } else if (node.type === "ExportNamedDeclaration") {
3631
- for (const spec of node.specifiers) names.add(exportedName(spec.exported));
3632
- const decl = node.declaration;
3633
- if (decl?.type === "VariableDeclaration") for (const d of decl.declarations) bindingNames(d.id, names);
3634
- else if (decl?.id) names.add(decl.id.name);
3635
- }
3636
- };
3637
- visit(entry);
3638
- names.delete("default");
3639
- return [...names].sort();
3640
- }
3641
- //#endregion
3642
- //#region src/presets/skia.ts
3643
- /** Skia's package names: `react-native-skia` from 2.15.0, the Shopify scope before. */
3644
- const SKIA_PACKAGES = ["react-native-skia", "@shopify/react-native-skia"];
3645
- const OPT_OUT = "A project whose tests do not use Skia can turn the preset off: reactNative({ presets: { skia: false } }).";
3646
- /**
3647
- * The installed package's directory, resolved from `root`, or null when absent: the
3648
- * nearest `node_modules/<name>`, as Node looks it up. Read from disk rather than
3649
- * through require(): under the mock engine, once a preset module's require() bridge is
3650
- * installed, a request for the package resolves to the module's virtual id
3651
- * (cjs-bridge.ts), and an `exports` map may not expose `./package.json`.
3652
- */
3653
- function packageDir(name, root) {
3654
- for (let dir = node_path.default.resolve(root);; dir = node_path.default.dirname(dir)) {
3655
- const candidate = node_path.default.join(dir, "node_modules", name);
3656
- if (node_fs.default.existsSync(node_path.default.join(candidate, "package.json"))) return node_fs.default.realpathSync(candidate);
3657
- if (dir === node_path.default.dirname(dir)) break;
3658
- }
3659
- try {
3660
- const manifest = (0, node_module.createRequire)(node_path.default.join(root, "package.json")).resolve(`${name}/package.json`);
3661
- return node_path.default.isAbsolute(manifest) && node_fs.default.existsSync(manifest) ? node_path.default.dirname(manifest) : null;
3662
- } catch {
3663
- return null;
3664
- }
3665
- }
3666
- /** The project root in a test worker, where the plugin sets it. */
3667
- function workerRoot() {
3668
- return process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
3669
- }
3670
- function messageOf(error) {
3671
- return error instanceof Error ? error.message : String(error);
3672
- }
3673
- async function loadCanvasKit(dir) {
3674
- try {
3675
- return await (0, node_module.createRequire)(node_path.default.join(dir, "package.json"))("canvaskit-wasm/bin/full/canvaskit")({});
3676
- } catch (cause) {
3677
- throw new require_errors.VitestNativeError("PRESET_UNAVAILABLE", `the skia preset could not load CanvasKit, Skia's WebAssembly build, from ${dir}: ${messageOf(cause)}. ${OPT_OUT}`, { cause });
3678
- }
3679
- }
3680
- function skiaModule(name) {
3681
- return {
3682
- exports: [],
3683
- exportsFor({ projectRoot, platform }) {
3684
- const dir = packageDir(name, projectRoot);
3685
- if (!dir) return null;
3686
- try {
3687
- return esmExportNames(node_path.default.join(dir, "lib/module/index.js"), platform);
3688
- } catch (cause) {
3689
- throw new require_errors.VitestNativeError("PRESET_UNAVAILABLE", `the skia preset could not read the named exports of '${name}' from its ESM build in ${dir}: ${messageOf(cause)}. ${OPT_OUT}`, { cause });
3690
- }
3691
- },
3692
- factory: () => {
3693
- const dir = packageDir(name, workerRoot());
3694
- if (!dir) throw new require_errors.VitestNativeError("PRESET_UNAVAILABLE", `the skia preset's mock for '${name}' needs '${name}' installed, and it does not resolve from ${workerRoot()}.`);
3695
- const CanvasKit = globalThis.CanvasKit;
3696
- if (!CanvasKit) throw new require_errors.VitestNativeError("PRESET_NOT_PREPARED", "the skia preset's mock was built before CanvasKit loaded. The setup file loads it before each test file; a mock built outside a test run needs `await presets.skia().prepare()` first.");
3697
- const skiaRequire = (0, node_module.createRequire)(node_path.default.join(dir, "package.json"));
3698
- const { Mock } = skiaRequire("./lib/commonjs/mock");
3699
- const mock = Mock(CanvasKit);
3700
- const reanimatedHelpers = skiaRequire("./lib/commonjs/external/reanimated");
3701
- const realMatchFont = mock.matchFont;
3702
- return {
3703
- ...reanimatedHelpers,
3704
- ...mock,
3705
- matchFont: (style = {}, fontMgr) => fontMgr === void 0 ? mock.Skia.Font(void 0, style.fontSize ?? 14) : realMatchFont(style, fontMgr),
3706
- useFont: (_source, size = 14) => mock.Skia.Font(void 0, size)
3707
- };
3708
- }
3709
- };
3710
- }
3711
- function skia() {
3712
- return builtInPreset({
3713
- name: "skia",
3714
- async prepare() {
3715
- const root = workerRoot();
3716
- const dir = SKIA_PACKAGES.map((name) => packageDir(name, root)).find((d) => d !== null);
3717
- if (!dir) throw new require_errors.VitestNativeError("PRESET_UNAVAILABLE", `the skia preset is enabled, and neither ${SKIA_PACKAGES.join(" nor ")} resolves from ${root}. ${OPT_OUT}`);
3718
- if (globalThis.CanvasKit) return;
3719
- globalThis.CanvasKit = await loadCanvasKit(dir);
3720
- },
3721
- modules: Object.fromEntries(SKIA_PACKAGES.map((name) => [name, skiaModule(name)]))
3722
- });
3723
- }
3724
- //#endregion
3725
- //#region src/presets/index.ts
3726
- var presets_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
3727
- asyncStorage: () => asyncStorage,
3728
- bottomSheet: () => bottomSheet,
3729
- deviceInfo: () => deviceInfo,
3730
- expo: () => expo,
3731
- flashList: () => flashList,
3732
- gestureHandler: () => gestureHandler,
3733
- keyboardController: () => keyboardController,
3734
- mmkv: () => mmkv,
3735
- navigation: () => navigation,
3736
- netInfo: () => netInfo,
3737
- reanimated: () => reanimated,
3738
- safeAreaContext: () => safeAreaContext,
3739
- screens: () => screens,
3740
- skia: () => skia,
3741
- svg: () => svg,
3742
- unistyles: () => unistyles,
3743
- vectorIcons: () => vectorIcons,
3744
- webview: () => webview,
3745
- worklets: () => worklets
3746
- });
3747
- //#endregion
3748
- Object.defineProperty(exports, "BUILT_IN_PRESET", {
3749
- enumerable: true,
3750
- get: function() {
3751
- return BUILT_IN_PRESET;
3752
- }
3753
- });
3754
- Object.defineProperty(exports, "asyncStorage", {
3755
- enumerable: true,
3756
- get: function() {
3757
- return asyncStorage;
3758
- }
3759
- });
3760
- Object.defineProperty(exports, "bottomSheet", {
3761
- enumerable: true,
3762
- get: function() {
3763
- return bottomSheet;
3764
- }
3765
- });
3766
- Object.defineProperty(exports, "buildPressableHostProps", {
3767
- enumerable: true,
3768
- get: function() {
3769
- return buildPressableHostProps;
3770
- }
3771
- });
3772
- Object.defineProperty(exports, "createFlatListMock", {
3773
- enumerable: true,
3774
- get: function() {
3775
- return createFlatListMock;
3776
- }
3777
- });
3778
- Object.defineProperty(exports, "createPressableMock", {
3779
- enumerable: true,
3780
- get: function() {
3781
- return createPressableMock;
3782
- }
3783
- });
3784
- Object.defineProperty(exports, "createScrollViewMock", {
3785
- enumerable: true,
3786
- get: function() {
3787
- return createScrollViewMock;
3788
- }
3789
- });
3790
- Object.defineProperty(exports, "createSectionListMock", {
3791
- enumerable: true,
3792
- get: function() {
3793
- return createSectionListMock;
3794
- }
3795
- });
3796
- Object.defineProperty(exports, "createTextInputMock", {
3797
- enumerable: true,
3798
- get: function() {
3799
- return createTextInputMock;
3800
- }
3801
- });
3802
- Object.defineProperty(exports, "createTouchableHighlightMock", {
3803
- enumerable: true,
3804
- get: function() {
3805
- return createTouchableHighlightMock;
3806
- }
3807
- });
3808
- Object.defineProperty(exports, "createTouchableOpacityMock", {
3809
- enumerable: true,
3810
- get: function() {
3811
- return createTouchableOpacityMock;
3812
- }
3813
- });
3814
- Object.defineProperty(exports, "createTouchableWithoutFeedbackMock", {
3815
- enumerable: true,
3816
- get: function() {
3817
- return createTouchableWithoutFeedbackMock;
3818
- }
3819
- });
3820
- Object.defineProperty(exports, "createViewMock", {
3821
- enumerable: true,
3822
- get: function() {
3823
- return createViewMock;
3824
- }
3825
- });
3826
- Object.defineProperty(exports, "createVirtualizedListMock", {
3827
- enumerable: true,
3828
- get: function() {
3829
- return createVirtualizedListMock;
3830
- }
3831
- });
3832
- Object.defineProperty(exports, "deviceInfo", {
3833
- enumerable: true,
3834
- get: function() {
3835
- return deviceInfo;
3836
- }
3837
- });
3838
- Object.defineProperty(exports, "expo", {
3839
- enumerable: true,
3840
- get: function() {
3841
- return expo;
3842
- }
3843
- });
3844
- Object.defineProperty(exports, "flashList", {
3845
- enumerable: true,
3846
- get: function() {
3847
- return flashList;
3848
- }
3849
- });
3850
- Object.defineProperty(exports, "gestureHandler", {
3851
- enumerable: true,
3852
- get: function() {
3853
- return gestureHandler;
3854
- }
3855
- });
3856
- Object.defineProperty(exports, "keyboardController", {
3857
- enumerable: true,
3858
- get: function() {
3859
- return keyboardController;
3860
- }
3861
- });
3862
- Object.defineProperty(exports, "mmkv", {
3863
- enumerable: true,
3864
- get: function() {
3865
- return mmkv;
3866
- }
3867
- });
3868
- Object.defineProperty(exports, "navigation", {
3869
- enumerable: true,
3870
- get: function() {
3871
- return navigation;
3872
- }
3873
- });
3874
- Object.defineProperty(exports, "netInfo", {
3875
- enumerable: true,
3876
- get: function() {
3877
- return netInfo;
3878
- }
3879
- });
3880
- Object.defineProperty(exports, "presets_exports", {
3881
- enumerable: true,
3882
- get: function() {
3883
- return presets_exports;
3884
- }
3885
- });
3886
- Object.defineProperty(exports, "reanimated", {
3887
- enumerable: true,
3888
- get: function() {
3889
- return reanimated;
3890
- }
3891
- });
3892
- Object.defineProperty(exports, "safeAreaContext", {
3893
- enumerable: true,
3894
- get: function() {
3895
- return safeAreaContext;
3896
- }
3897
- });
3898
- Object.defineProperty(exports, "screens", {
3899
- enumerable: true,
3900
- get: function() {
3901
- return screens;
3902
- }
3903
- });
3904
- Object.defineProperty(exports, "skia", {
3905
- enumerable: true,
3906
- get: function() {
3907
- return skia;
3908
- }
3909
- });
3910
- Object.defineProperty(exports, "svg", {
3911
- enumerable: true,
3912
- get: function() {
3913
- return svg;
3914
- }
3915
- });
3916
- Object.defineProperty(exports, "unistyles", {
3917
- enumerable: true,
3918
- get: function() {
3919
- return unistyles;
3920
- }
3921
- });
3922
- Object.defineProperty(exports, "vectorIcons", {
3923
- enumerable: true,
3924
- get: function() {
3925
- return vectorIcons;
3926
- }
3927
- });
3928
- Object.defineProperty(exports, "webview", {
3929
- enumerable: true,
3930
- get: function() {
3931
- return webview;
3932
- }
3933
- });
3934
- Object.defineProperty(exports, "worklets", {
3935
- enumerable: true,
3936
- get: function() {
3937
- return worklets;
3938
- }
3939
- });