vitest-native 0.9.0 → 0.10.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 (53) hide show
  1. package/CHANGELOG.md +731 -0
  2. package/README.md +32 -1
  3. package/dist/cli.cjs +163 -27
  4. package/dist/cli.mjs +162 -26
  5. package/dist/{ecosystem-EFtHnKS9.mjs → ecosystem-CO5vqExO.mjs} +77 -15
  6. package/dist/{ecosystem-BIWaVwYL.cjs → ecosystem-IuZ-Gv0R.cjs} +78 -16
  7. package/dist/errors-Dm5yLNTF.mjs +64 -0
  8. package/dist/errors-flXDIeWk.cjs +75 -0
  9. package/dist/errors.d.mts +46 -0
  10. package/dist/errors.mjs +78 -0
  11. package/dist/helpers.cjs +6 -23
  12. package/dist/helpers.d.cts +0 -6
  13. package/dist/helpers.d.mts +0 -6
  14. package/dist/helpers.mjs +6 -23
  15. package/dist/{index-CEgRDdhd.d.cts → index-BJL4cQ-l.d.cts} +9 -4
  16. package/dist/{index-j-0tueBr.d.mts → index-CvCU0cLl.d.mts} +9 -4
  17. package/dist/index.d.mts +8 -6
  18. package/dist/index.mjs +245 -59
  19. package/dist/jest-compat/interop.mjs +15 -0
  20. package/dist/jest-compat/setup.mjs +102 -7
  21. package/dist/matchers.cjs +16 -7
  22. package/dist/matchers.mjs +16 -7
  23. package/dist/native/hooks.mjs +75 -1
  24. package/dist/native/loader.mjs +26 -6
  25. package/dist/native/module-reset.mjs +63 -0
  26. package/dist/native/registry.mjs +80 -11
  27. package/dist/native/resolve.d.mts +22 -0
  28. package/dist/native/resolve.mjs +21 -13
  29. package/dist/native/runner.mjs +21 -0
  30. package/dist/native/setup.mjs +4 -2
  31. package/dist/native/transform.mjs +108 -3
  32. package/dist/native/worker.mjs +59 -16
  33. package/dist/{pool-CJmjRgsB.mjs → pool-Bcxp4Qrg.mjs} +2 -1
  34. package/dist/{pool-DzsEo9vv.cjs → pool-CFND7plG.cjs} +2 -1
  35. package/dist/{preset-map-CNsZKfvu.mjs → preset-map-BpDG_D5m.mjs} +0 -1
  36. package/dist/{preset-map-CG4FMtsl.cjs → preset-map-DxilQ4pI.cjs} +0 -1
  37. package/dist/{presets-C4faM3ds.cjs → presets-BGTqVH6C.cjs} +94 -50
  38. package/dist/{presets-CuDrNA_W.mjs → presets-CK85x8ey.mjs} +94 -50
  39. package/dist/presets.d.mts +1 -1
  40. package/dist/presets.mjs +1 -1
  41. package/dist/rntl-matchers.d.ts +35 -0
  42. package/dist/serializer.cjs +33 -3
  43. package/dist/serializer.mjs +33 -3
  44. package/dist/setup.mjs +234 -71
  45. package/docs/release-readiness.md +22 -5
  46. package/docs/versioning.md +133 -0
  47. package/package.json +25 -35
  48. package/dist/index.cjs +0 -788
  49. package/dist/index.d.cts +0 -14
  50. package/dist/presets.cjs +0 -18
  51. package/dist/presets.d.cts +0 -2
  52. package/dist/setup.cjs +0 -2702
  53. package/dist/setup.d.cts +0 -1
package/dist/setup.cjs DELETED
@@ -1,2702 +0,0 @@
1
- const require_chunk = require("./chunk-CZWwpsFl.cjs");
2
- const require_preset_map = require("./preset-map-CG4FMtsl.cjs");
3
- const require_presets = require("./presets-C4faM3ds.cjs");
4
- const require_serializer = require("./serializer.cjs");
5
- const require_matchers = require("./matchers.cjs");
6
- let node_path = require("node:path");
7
- node_path = require_chunk.__toESM(node_path, 1);
8
- let node_module = require("node:module");
9
- let vitest = require("vitest");
10
- let react = require("react");
11
- react = require_chunk.__toESM(react, 1);
12
- //#region src/mocks/components/Text.ts
13
- function createTextMock() {
14
- const Text = react.default.forwardRef((props, ref) => {
15
- const { onPress, onLongPress, disabled, accessibilityRole, ...rest } = props;
16
- const resolvedRole = accessibilityRole ?? (!disabled && (onPress || onLongPress) ? "link" : void 0);
17
- return react.default.createElement("Text", {
18
- accessible: true,
19
- ...rest,
20
- ...onPress ? { onPress } : {},
21
- ...onLongPress ? { onLongPress } : {},
22
- ...disabled ? { disabled } : {},
23
- ...resolvedRole ? { accessibilityRole: resolvedRole } : {},
24
- ref
25
- });
26
- });
27
- Text.displayName = "Text";
28
- return Text;
29
- }
30
- //#endregion
31
- //#region src/mocks/components/Image.ts
32
- function createImageMock() {
33
- const Image = react.default.forwardRef((props, ref) => {
34
- return react.default.createElement("Image", {
35
- ...props,
36
- ref
37
- });
38
- });
39
- Image.displayName = "Image";
40
- Image.getSize = vitest.vi.fn((_uri, success, _failure) => {
41
- Promise.resolve().then(() => success(100, 100));
42
- });
43
- Image.getSizeWithHeaders = vitest.vi.fn((_uri, _headers, success, _failure) => {
44
- Promise.resolve().then(() => success(100, 100));
45
- });
46
- Image.prefetch = vitest.vi.fn(() => Promise.resolve(true));
47
- Image.queryCache = vitest.vi.fn(() => Promise.resolve({}));
48
- Image.resolveAssetSource = vitest.vi.fn((source) => {
49
- if (typeof source === "number") return {
50
- uri: `asset://${source}`,
51
- width: 100,
52
- height: 100
53
- };
54
- return source;
55
- });
56
- return Image;
57
- }
58
- //#endregion
59
- //#region src/mocks/components/Modal.ts
60
- function createModalMock() {
61
- const Modal = react.default.forwardRef((props, ref) => {
62
- const { visible = true, children, ...rest } = props;
63
- if (!visible) return null;
64
- return react.default.createElement("Modal", {
65
- ...rest,
66
- visible,
67
- ref
68
- }, children);
69
- });
70
- Modal.displayName = "Modal";
71
- return Modal;
72
- }
73
- //#endregion
74
- //#region src/mocks/components/TouchableNativeFeedback.ts
75
- function createTouchableNativeFeedbackMock() {
76
- const TouchableNativeFeedback = react.default.forwardRef((props, ref) => {
77
- const { disabled, accessibilityState, ...rest } = props;
78
- const mergedA11yState = disabled || accessibilityState ? {
79
- ...accessibilityState,
80
- ...disabled ? { disabled: true } : {}
81
- } : void 0;
82
- if (disabled) {
83
- delete rest.onPress;
84
- delete rest.onPressIn;
85
- delete rest.onPressOut;
86
- delete rest.onLongPress;
87
- }
88
- return react.default.createElement("TouchableNativeFeedback", {
89
- accessible: true,
90
- ...disabled ? { pointerEvents: "none" } : {},
91
- ...rest,
92
- ...mergedA11yState ? { accessibilityState: mergedA11yState } : {},
93
- ref
94
- });
95
- });
96
- TouchableNativeFeedback.displayName = "TouchableNativeFeedback";
97
- return TouchableNativeFeedback;
98
- }
99
- //#endregion
100
- //#region src/mocks/components/ActivityIndicator.ts
101
- function createActivityIndicatorMock() {
102
- const ActivityIndicator = react.default.forwardRef((props, ref) => {
103
- return react.default.createElement("ActivityIndicator", {
104
- ...props,
105
- ref
106
- });
107
- });
108
- ActivityIndicator.displayName = "ActivityIndicator";
109
- return ActivityIndicator;
110
- }
111
- //#endregion
112
- //#region src/mocks/components/Button.ts
113
- function createButtonMock() {
114
- function Button(props) {
115
- const { title, onPress, disabled, color, accessibilityLabel, accessibilityState, ...rest } = props;
116
- const hostProps = require_presets.buildPressableHostProps({
117
- ...rest,
118
- onPress,
119
- disabled,
120
- accessibilityState,
121
- accessibilityLabel: accessibilityLabel || title,
122
- accessibilityRole: "button"
123
- }, void 0);
124
- return react.default.createElement("View", hostProps, react.default.createElement("Text", {
125
- style: color ? { color } : void 0,
126
- disabled
127
- }, title));
128
- }
129
- Button.displayName = "Button";
130
- return Button;
131
- }
132
- //#endregion
133
- //#region src/mocks/components/Switch.ts
134
- function createSwitchMock() {
135
- const Switch = react.default.forwardRef((props, ref) => {
136
- return react.default.createElement("RCTSwitch", {
137
- accessibilityRole: "switch",
138
- ...props,
139
- ref
140
- });
141
- });
142
- Switch.displayName = "Switch";
143
- return Switch;
144
- }
145
- //#endregion
146
- //#region src/mocks/components/RefreshControl.ts
147
- function createRefreshControlMock() {
148
- const RefreshControl = react.default.forwardRef((props, ref) => {
149
- return react.default.createElement("RefreshControl", {
150
- ...props,
151
- ref
152
- });
153
- });
154
- RefreshControl.displayName = "RefreshControl";
155
- return RefreshControl;
156
- }
157
- //#endregion
158
- //#region src/mocks/components/StatusBar.ts
159
- function createStatusBarMock() {
160
- function StatusBar(props) {
161
- return react.default.createElement("StatusBar", props);
162
- }
163
- StatusBar.displayName = "StatusBar";
164
- StatusBar.setBarStyle = vitest.vi.fn();
165
- StatusBar.setBackgroundColor = vitest.vi.fn();
166
- StatusBar.setHidden = vitest.vi.fn();
167
- StatusBar.setNetworkActivityIndicatorVisible = vitest.vi.fn();
168
- StatusBar.setTranslucent = vitest.vi.fn();
169
- StatusBar.pushStackEntry = vitest.vi.fn(() => ({}));
170
- StatusBar.popStackEntry = vitest.vi.fn();
171
- StatusBar.replaceStackEntry = vitest.vi.fn(() => ({}));
172
- StatusBar.currentHeight = 44;
173
- return StatusBar;
174
- }
175
- //#endregion
176
- //#region src/mocks/components/SafeAreaView.ts
177
- function createSafeAreaViewMock() {
178
- const SafeAreaView = react.default.forwardRef((props, ref) => {
179
- return react.default.createElement("SafeAreaView", {
180
- ...props,
181
- ref
182
- });
183
- });
184
- SafeAreaView.displayName = "SafeAreaView";
185
- return SafeAreaView;
186
- }
187
- //#endregion
188
- //#region src/mocks/components/KeyboardAvoidingView.ts
189
- function createKeyboardAvoidingViewMock() {
190
- const KeyboardAvoidingView = react.default.forwardRef((props, ref) => {
191
- return react.default.createElement("KeyboardAvoidingView", {
192
- ...props,
193
- ref
194
- });
195
- });
196
- KeyboardAvoidingView.displayName = "KeyboardAvoidingView";
197
- return KeyboardAvoidingView;
198
- }
199
- //#endregion
200
- //#region src/mocks/components/ImageBackground.ts
201
- function createImageBackgroundMock() {
202
- const ImageBackground = react.default.forwardRef((props, ref) => {
203
- const { children, style, imageStyle, source, ...rest } = props;
204
- return react.default.createElement("ImageBackground", {
205
- ...rest,
206
- ref,
207
- style
208
- }, react.default.createElement("Image", {
209
- source,
210
- style: imageStyle
211
- }), children);
212
- });
213
- ImageBackground.displayName = "ImageBackground";
214
- return ImageBackground;
215
- }
216
- //#endregion
217
- //#region src/mocks/components/InputAccessoryView.ts
218
- function createInputAccessoryViewMock() {
219
- const InputAccessoryView = react.default.forwardRef((props, ref) => {
220
- return react.default.createElement("InputAccessoryView", {
221
- ...props,
222
- ref
223
- });
224
- });
225
- InputAccessoryView.displayName = "InputAccessoryView";
226
- return InputAccessoryView;
227
- }
228
- //#endregion
229
- //#region src/mocks/components/DrawerLayoutAndroid.ts
230
- function createDrawerLayoutAndroidMock() {
231
- const DrawerLayoutAndroid = react.default.forwardRef((props, ref) => {
232
- const { children, ...rest } = props;
233
- return react.default.createElement("DrawerLayoutAndroid", {
234
- ...rest,
235
- ref
236
- }, children);
237
- });
238
- DrawerLayoutAndroid.displayName = "DrawerLayoutAndroid";
239
- return DrawerLayoutAndroid;
240
- }
241
- //#endregion
242
- //#region src/mocks/apis/Platform.ts
243
- function createPlatformMock(os = "ios") {
244
- return {
245
- OS: os,
246
- Version: os === "ios" ? "17.0" : 34,
247
- isPad: false,
248
- isTVOS: false,
249
- isTV: false,
250
- isVision: false,
251
- isTesting: true,
252
- select: vitest.vi.fn((specifics) => {
253
- return specifics[os] ?? specifics.native ?? specifics.default;
254
- }),
255
- constants: {
256
- reactNativeVersion: {
257
- major: 0,
258
- minor: 76,
259
- patch: 0
260
- },
261
- osVersion: os === "ios" ? 17 : 34,
262
- systemName: os === "ios" ? "iOS" : "Android",
263
- isTesting: true
264
- }
265
- };
266
- }
267
- //#endregion
268
- //#region src/mocks/apis/Dimensions.ts
269
- function createDimensionsMock() {
270
- const defaults = {
271
- window: {
272
- width: 390,
273
- height: 844,
274
- scale: 3,
275
- fontScale: 1
276
- },
277
- screen: {
278
- width: 390,
279
- height: 844,
280
- scale: 3,
281
- fontScale: 1
282
- }
283
- };
284
- const state = {
285
- window: { ...defaults.window },
286
- screen: { ...defaults.screen }
287
- };
288
- const listeners = /* @__PURE__ */ new Set();
289
- return {
290
- get: vitest.vi.fn((dim) => ({ ...state[dim] })),
291
- set: vitest.vi.fn((dims) => {
292
- for (const [key, value] of Object.entries(dims)) if (key in state && value) Object.assign(state[key], value);
293
- listeners.forEach((fn) => fn({
294
- window: { ...state.window },
295
- screen: { ...state.screen }
296
- }));
297
- }),
298
- addEventListener: vitest.vi.fn((_type, handler) => {
299
- listeners.add(handler);
300
- return { remove: () => listeners.delete(handler) };
301
- }),
302
- _reset: () => {
303
- Object.assign(state.window, defaults.window);
304
- Object.assign(state.screen, defaults.screen);
305
- listeners.clear();
306
- }
307
- };
308
- }
309
- //#endregion
310
- //#region src/mocks/apis/StyleSheet.ts
311
- function flattenImpl(style) {
312
- if (style == null || style === false) return void 0;
313
- if (!Array.isArray(style)) return style;
314
- const result = {};
315
- let hasAny = false;
316
- for (const item of style) {
317
- const flattened = flattenImpl(item);
318
- if (flattened != null) {
319
- hasAny = true;
320
- Object.assign(result, flattened);
321
- }
322
- }
323
- return hasAny ? result : void 0;
324
- }
325
- function createStyleSheetMock(getScale = () => 3) {
326
- const sheet = {
327
- create: vitest.vi.fn((styles) => {
328
- return styles;
329
- }),
330
- flatten: vitest.vi.fn((style) => flattenImpl(style)),
331
- compose: vitest.vi.fn((a, b) => [a, b]),
332
- absoluteFill: {
333
- position: "absolute",
334
- left: 0,
335
- right: 0,
336
- top: 0,
337
- bottom: 0
338
- },
339
- absoluteFillObject: {
340
- position: "absolute",
341
- left: 0,
342
- right: 0,
343
- top: 0,
344
- bottom: 0
345
- },
346
- setStyleAttributePreprocessor: vitest.vi.fn()
347
- };
348
- Object.defineProperty(sheet, "hairlineWidth", {
349
- enumerable: true,
350
- configurable: true,
351
- get() {
352
- const ratio = getScale();
353
- const width = Math.round(.4 * ratio) / ratio;
354
- return width === 0 ? 1 / ratio : width;
355
- }
356
- });
357
- return sheet;
358
- }
359
- //#endregion
360
- //#region src/mocks/apis/Animated.ts
361
- const IDENTITY_EASING = (t) => t;
362
- function interpolateSegment(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight) {
363
- let result = input;
364
- if (result < inputMin) {
365
- if (extrapolateLeft === "identity") return result;
366
- else if (extrapolateLeft === "clamp") result = inputMin;
367
- }
368
- if (result > inputMax) {
369
- if (extrapolateRight === "identity") return result;
370
- else if (extrapolateRight === "clamp") result = inputMax;
371
- }
372
- if (outputMin === outputMax) return outputMin;
373
- if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax;
374
- if (inputMin === -Infinity) result = -result;
375
- else if (inputMax === Infinity) result = result - inputMin;
376
- else result = (result - inputMin) / (inputMax - inputMin);
377
- result = easing(result);
378
- if (outputMin === -Infinity) result = -result;
379
- else if (outputMax === Infinity) result = result + outputMin;
380
- else result = result * (outputMax - outputMin) + outputMin;
381
- return result;
382
- }
383
- function findRangeIndex(input, inputRange) {
384
- let i;
385
- for (i = 1; i < inputRange.length - 1; ++i) if (inputRange[i] >= input) break;
386
- return i - 1;
387
- }
388
- function interpolateNumeric(value, inputRange, outputRange, extrapolate, extrapolateLeft, extrapolateRight, easing) {
389
- const i = findRangeIndex(value, inputRange);
390
- return interpolateSegment(value, inputRange[i], inputRange[i + 1], outputRange[i], outputRange[i + 1], easing, extrapolateLeft ?? extrapolate, extrapolateRight ?? extrapolate);
391
- }
392
- const NAMED_COLORS = {
393
- red: [
394
- 255,
395
- 0,
396
- 0,
397
- 1
398
- ],
399
- green: [
400
- 0,
401
- 128,
402
- 0,
403
- 1
404
- ],
405
- blue: [
406
- 0,
407
- 0,
408
- 255,
409
- 1
410
- ],
411
- white: [
412
- 255,
413
- 255,
414
- 255,
415
- 1
416
- ],
417
- black: [
418
- 0,
419
- 0,
420
- 0,
421
- 1
422
- ],
423
- transparent: [
424
- 0,
425
- 0,
426
- 0,
427
- 0
428
- ],
429
- yellow: [
430
- 255,
431
- 255,
432
- 0,
433
- 1
434
- ],
435
- cyan: [
436
- 0,
437
- 255,
438
- 255,
439
- 1
440
- ],
441
- magenta: [
442
- 255,
443
- 0,
444
- 255,
445
- 1
446
- ],
447
- orange: [
448
- 255,
449
- 165,
450
- 0,
451
- 1
452
- ],
453
- purple: [
454
- 128,
455
- 0,
456
- 128,
457
- 1
458
- ],
459
- gray: [
460
- 128,
461
- 128,
462
- 128,
463
- 1
464
- ],
465
- grey: [
466
- 128,
467
- 128,
468
- 128,
469
- 1
470
- ]
471
- };
472
- function colorToRgba(input) {
473
- const s = input.toLowerCase().trim();
474
- if (NAMED_COLORS[s]) return [...NAMED_COLORS[s]];
475
- let m;
476
- if (m = s.match(/^#([0-9a-f]{3})$/)) {
477
- const [r, g, b] = m[1].split("");
478
- return [
479
- parseInt(r + r, 16),
480
- parseInt(g + g, 16),
481
- parseInt(b + b, 16),
482
- 1
483
- ];
484
- }
485
- if (m = s.match(/^#([0-9a-f]{6})$/)) {
486
- const n = m[1];
487
- return [
488
- parseInt(n.slice(0, 2), 16),
489
- parseInt(n.slice(2, 4), 16),
490
- parseInt(n.slice(4, 6), 16),
491
- 1
492
- ];
493
- }
494
- if (m = s.match(/^#([0-9a-f]{8})$/)) {
495
- const n = m[1];
496
- return [
497
- parseInt(n.slice(0, 2), 16),
498
- parseInt(n.slice(2, 4), 16),
499
- parseInt(n.slice(4, 6), 16),
500
- parseInt(n.slice(6, 8), 16) / 255
501
- ];
502
- }
503
- const compact = s.replace(/\s+/g, "");
504
- if (m = compact.match(/^rgb\(([\d.]+),([\d.]+),([\d.]+)\)$/)) return [
505
- +m[1],
506
- +m[2],
507
- +m[3],
508
- 1
509
- ];
510
- if (m = compact.match(/^rgba\(([\d.]+),([\d.]+),([\d.]+),([\d.]+)\)$/)) return [
511
- +m[1],
512
- +m[2],
513
- +m[3],
514
- +m[4]
515
- ];
516
- return null;
517
- }
518
- const NUMERIC_COMPONENT_RE = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
519
- function mapStringToComponents(input) {
520
- const rgba = colorToRgba(input);
521
- if (rgba) return {
522
- isColor: true,
523
- components: rgba
524
- };
525
- const components = [];
526
- let lastMatchEnd = 0;
527
- let match;
528
- NUMERIC_COMPONENT_RE.lastIndex = 0;
529
- while ((match = NUMERIC_COMPONENT_RE.exec(input)) != null) {
530
- if (match.index > lastMatchEnd) components.push(input.substring(lastMatchEnd, match.index));
531
- components.push(parseFloat(match[0]));
532
- lastMatchEnd = match.index + match[0].length;
533
- }
534
- if (components.length === 0) throw new Error("outputRange must contain color or value with numeric component");
535
- if (lastMatchEnd < input.length) components.push(input.substring(lastMatchEnd, input.length));
536
- return {
537
- isColor: false,
538
- components
539
- };
540
- }
541
- function prepareStringInterpolation(outputRange) {
542
- const mapped = outputRange.map(mapStringToComponents);
543
- const isColor = mapped[0].isColor;
544
- if (!mapped.every((o) => o.isColor === isColor)) throw new Error("All elements of output range should either be a color or a string with numeric components");
545
- const first = mapped[0].components;
546
- if (!mapped.every((o) => o.components.length === first.length)) throw new Error("All elements of output range should have the same number of components");
547
- if (!mapped.every((o) => o.components.every((c, i) => typeof c === "number" || c === first[i]))) throw new Error("All elements of output range should have the same non-numeric components");
548
- const numericComponents = mapped.map((o) => isColor ? o.components : o.components.filter((c) => typeof c === "number"));
549
- return {
550
- isColor,
551
- template: first,
552
- perSlotRanges: numericComponents[0].map((_, i) => numericComponents.map((c) => c[i]))
553
- };
554
- }
555
- function interpolateString(prepared, value, inputRange, extrapolate, extrapolateLeft, extrapolateRight, easing) {
556
- const slots = prepared.perSlotRanges.map((range) => interpolateNumeric(value, inputRange, range, extrapolate, extrapolateLeft, extrapolateRight, easing));
557
- if (prepared.isColor) {
558
- const r = slots.map((v, i) => i < 3 ? Math.round(v) : Math.round(v * 1e3) / 1e3);
559
- return `rgba(${r[0]}, ${r[1]}, ${r[2]}, ${r[3]})`;
560
- }
561
- let i = 0;
562
- return prepared.template.map((c) => typeof c === "number" ? slots[i++] : c).join("");
563
- }
564
- function checkValidRanges(inputRange, outputRange) {
565
- if (inputRange.length === 2 && inputRange[0] === -Infinity && inputRange[1] === Infinity) throw new Error("inputRange cannot be [-Infinity, Infinity]");
566
- if (inputRange.length < 2) throw new Error("inputRange must have at least 2 elements");
567
- for (let i = 1; i < inputRange.length; ++i) if (!(inputRange[i] >= inputRange[i - 1])) throw new Error("inputRange must be monotonically non-decreasing " + String(inputRange));
568
- if (inputRange.length !== outputRange.length) throw new Error("inputRange (" + inputRange.length + ") and outputRange (" + outputRange.length + ") must have the same length");
569
- }
570
- var AnimatedNode = class {
571
- _listeners = /* @__PURE__ */ new Map();
572
- _children = /* @__PURE__ */ new Set();
573
- _listenerIdCounter = 0;
574
- getValue() {
575
- return this.__getValue();
576
- }
577
- _attachToParents() {}
578
- _detachFromParents() {}
579
- _consumerCount() {
580
- return this._listeners.size + this._children.size;
581
- }
582
- addListener(callback) {
583
- const id = String(++this._listenerIdCounter);
584
- this._listeners.set(id, callback);
585
- if (this._consumerCount() === 1) this._attachToParents();
586
- return id;
587
- }
588
- removeListener(id) {
589
- if (this._listeners.delete(id) && this._consumerCount() === 0) this._detachFromParents();
590
- }
591
- removeAllListeners() {
592
- const had = this._listeners.size > 0;
593
- this._listeners.clear();
594
- if (had && this._consumerCount() === 0) this._detachFromParents();
595
- }
596
- /** Graph edge: `fn` runs whenever this node's value may have changed. */
597
- __addChild(fn) {
598
- this._children.add(fn);
599
- if (this._consumerCount() === 1) this._attachToParents();
600
- }
601
- __removeChild(fn) {
602
- if (this._children.delete(fn) && this._consumerCount() === 0) this._detachFromParents();
603
- }
604
- /** Notify consumers with the node's CURRENT (offset-inclusive) value. */
605
- _notify() {
606
- if (this._listeners.size > 0) {
607
- const value = this.__getValue();
608
- this._listeners.forEach((fn) => fn({ value }));
609
- }
610
- this._children.forEach((fn) => fn());
611
- }
612
- interpolate(config) {
613
- const { inputRange, outputRange } = config || {};
614
- if (!inputRange || !outputRange || inputRange.length < 2 || outputRange.length < 2) return new AnimatedValue(Number(this.__getValue()) || 0);
615
- return new AnimatedInterpolation(this, config);
616
- }
617
- stopAnimation(callback) {
618
- callback?.(this.__getValue());
619
- }
620
- resetAnimation(callback) {
621
- callback?.(this.__getValue());
622
- }
623
- toJSON() {
624
- return this.__getValue();
625
- }
626
- };
627
- var AnimatedValue = class extends AnimatedNode {
628
- _value;
629
- _offset = 0;
630
- _tracking = null;
631
- constructor(value = 0) {
632
- super();
633
- this._value = value;
634
- }
635
- setValue(value) {
636
- this._value = value;
637
- this._notify();
638
- }
639
- __getValue() {
640
- return this._value + this._offset;
641
- }
642
- setOffset(offset) {
643
- this._offset = offset;
644
- }
645
- flattenOffset() {
646
- this._value += this._offset;
647
- this._offset = 0;
648
- }
649
- extractOffset() {
650
- this._offset += this._value;
651
- this._value = 0;
652
- }
653
- };
654
- var AnimatedInterpolation = class extends AnimatedNode {
655
- _parent;
656
- _config;
657
- _preparedString = null;
658
- constructor(parent, config) {
659
- super();
660
- this._parent = parent;
661
- this._config = config;
662
- const { inputRange, outputRange } = config;
663
- checkValidRanges(inputRange, outputRange);
664
- if (typeof outputRange[0] === "string") this._preparedString = prepareStringInterpolation(outputRange);
665
- }
666
- _propagate = () => this._notify();
667
- _attachToParents() {
668
- this._parent.__addChild(this._propagate);
669
- }
670
- _detachFromParents() {
671
- this._parent.__removeChild(this._propagate);
672
- }
673
- __getValue() {
674
- const { inputRange, outputRange, extrapolate = "extend", extrapolateLeft, extrapolateRight, easing = IDENTITY_EASING } = this._config;
675
- const input = Number(this._parent.__getValue());
676
- if (this._preparedString) return interpolateString(this._preparedString, input, inputRange, extrapolate, extrapolateLeft, extrapolateRight, easing);
677
- return interpolateNumeric(input, inputRange, outputRange, extrapolate, extrapolateLeft, extrapolateRight, easing);
678
- }
679
- interpolate(config) {
680
- if (this._preparedString) throw new Error("Cannot chain an interpolation off a string-valued interpolation");
681
- return super.interpolate(config);
682
- }
683
- };
684
- var AnimatedOp = class extends AnimatedNode {
685
- _compute;
686
- _parents;
687
- _propagate = () => this._notify();
688
- constructor(inputs, compute) {
689
- super();
690
- this._compute = compute;
691
- this._parents = inputs.filter((i) => i instanceof AnimatedNode);
692
- }
693
- _attachToParents() {
694
- for (const parent of this._parents) parent.__addChild(this._propagate);
695
- }
696
- _detachFromParents() {
697
- for (const parent of this._parents) parent.__removeChild(this._propagate);
698
- }
699
- __getValue() {
700
- return this._compute();
701
- }
702
- };
703
- /** Numeric value of an operand that may be a node, a number, or junk (→ 0). */
704
- function operandValue(v) {
705
- if (v instanceof AnimatedNode) {
706
- const n = Number(v.__getValue());
707
- return Number.isNaN(n) ? 0 : n;
708
- }
709
- return typeof v === "number" ? v : 0;
710
- }
711
- var AnimatedValueXY = class {
712
- x;
713
- y;
714
- _listenerIdCounter = 0;
715
- _joint = /* @__PURE__ */ new Map();
716
- constructor(value) {
717
- this.x = new AnimatedValue(value?.x ?? 0);
718
- this.y = new AnimatedValue(value?.y ?? 0);
719
- }
720
- setValue(value) {
721
- this.x.setValue(value.x);
722
- this.y.setValue(value.y);
723
- }
724
- setOffset(offset) {
725
- this.x.setOffset(offset.x);
726
- this.y.setOffset(offset.y);
727
- }
728
- flattenOffset() {
729
- this.x.flattenOffset();
730
- this.y.flattenOffset();
731
- }
732
- extractOffset() {
733
- this.x.extractOffset();
734
- this.y.extractOffset();
735
- }
736
- __getValue() {
737
- return {
738
- x: this.x.__getValue(),
739
- y: this.y.__getValue()
740
- };
741
- }
742
- getValue() {
743
- return this.__getValue();
744
- }
745
- stopAnimation(callback) {
746
- callback?.(this.__getValue());
747
- }
748
- resetAnimation(callback) {
749
- callback?.(this.__getValue());
750
- }
751
- addListener(callback) {
752
- const emit = () => callback(this.__getValue());
753
- const id = String(++this._listenerIdCounter);
754
- const pair = {
755
- x: this.x.addListener(emit),
756
- y: this.y.addListener(emit)
757
- };
758
- this._joint.set(id, pair);
759
- return pair;
760
- }
761
- removeListener(id) {
762
- this.x.removeListener(id.x);
763
- this.y.removeListener(id.y);
764
- }
765
- removeAllListeners() {
766
- this.x.removeAllListeners();
767
- this.y.removeAllListeners();
768
- this._joint.clear();
769
- }
770
- getLayout() {
771
- return {
772
- left: this.x,
773
- top: this.y
774
- };
775
- }
776
- getTranslateTransform() {
777
- return [{ translateX: this.x }, { translateY: this.y }];
778
- }
779
- };
780
- const namedColorMap = {
781
- red: [
782
- 255,
783
- 0,
784
- 0,
785
- 1
786
- ],
787
- green: [
788
- 0,
789
- 128,
790
- 0,
791
- 1
792
- ],
793
- blue: [
794
- 0,
795
- 0,
796
- 255,
797
- 1
798
- ],
799
- white: [
800
- 255,
801
- 255,
802
- 255,
803
- 1
804
- ],
805
- black: [
806
- 0,
807
- 0,
808
- 0,
809
- 1
810
- ],
811
- transparent: [
812
- 0,
813
- 0,
814
- 0,
815
- 0
816
- ],
817
- yellow: [
818
- 255,
819
- 255,
820
- 0,
821
- 1
822
- ],
823
- cyan: [
824
- 0,
825
- 255,
826
- 255,
827
- 1
828
- ],
829
- magenta: [
830
- 255,
831
- 0,
832
- 255,
833
- 1
834
- ]
835
- };
836
- function parseColorString(color) {
837
- const rgba = color.replace(/\s+/g, "").match(/^rgba?\((\d+),(\d+),(\d+)(?:,([\d.]+))?\)$/);
838
- if (rgba) return [
839
- parseInt(rgba[1]),
840
- parseInt(rgba[2]),
841
- parseInt(rgba[3]),
842
- rgba[4] != null ? parseFloat(rgba[4]) : 1
843
- ];
844
- const hex8 = color.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
845
- if (hex8) return [
846
- parseInt(hex8[1], 16),
847
- parseInt(hex8[2], 16),
848
- parseInt(hex8[3], 16),
849
- parseInt(hex8[4], 16) / 255
850
- ];
851
- const hex6 = color.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
852
- if (hex6) return [
853
- parseInt(hex6[1], 16),
854
- parseInt(hex6[2], 16),
855
- parseInt(hex6[3], 16),
856
- 1
857
- ];
858
- const named = namedColorMap[color.toLowerCase()];
859
- if (named) return named;
860
- return [
861
- 0,
862
- 0,
863
- 0,
864
- 1
865
- ];
866
- }
867
- var AnimatedColor = class extends AnimatedNode {
868
- r;
869
- g;
870
- b;
871
- a;
872
- constructor(color) {
873
- super();
874
- if (typeof color === "string") {
875
- const [r, g, b, a] = parseColorString(color);
876
- this.r = new AnimatedValue(r);
877
- this.g = new AnimatedValue(g);
878
- this.b = new AnimatedValue(b);
879
- this.a = new AnimatedValue(a);
880
- } else if (color && typeof color === "object" && color.r instanceof AnimatedValue) {
881
- this.r = color.r;
882
- this.g = color.g;
883
- this.b = color.b;
884
- this.a = color.a;
885
- } else if (color && typeof color === "object" && typeof color.r === "number") {
886
- this.r = new AnimatedValue(color.r);
887
- this.g = new AnimatedValue(color.g ?? 0);
888
- this.b = new AnimatedValue(color.b ?? 0);
889
- this.a = new AnimatedValue(color.a ?? 1);
890
- } else {
891
- this.r = new AnimatedValue(0);
892
- this.g = new AnimatedValue(0);
893
- this.b = new AnimatedValue(0);
894
- this.a = new AnimatedValue(1);
895
- }
896
- for (const channel of [
897
- this.r,
898
- this.g,
899
- this.b,
900
- this.a
901
- ]) channel.__addChild(() => this._notify());
902
- }
903
- setValue(value) {
904
- if (typeof value === "string") {
905
- const [r, g, b, a] = parseColorString(value);
906
- this.r.setValue(r);
907
- this.g.setValue(g);
908
- this.b.setValue(b);
909
- this.a.setValue(a);
910
- } else if (value && typeof value === "object" && typeof value.r === "number") {
911
- this.r.setValue(value.r);
912
- this.g.setValue(value.g ?? 0);
913
- this.b.setValue(value.b ?? 0);
914
- this.a.setValue(value.a ?? 1);
915
- }
916
- }
917
- __getValue() {
918
- return `rgba(${Math.round(this.r.getValue())}, ${Math.round(this.g.getValue())}, ${Math.round(this.b.getValue())}, ${this.a.getValue()})`;
919
- }
920
- setOffset(_offset) {}
921
- flattenOffset() {}
922
- };
923
- function createAnimation(onStart) {
924
- return {
925
- start: vitest.vi.fn((callback) => {
926
- onStart?.();
927
- callback?.({ finished: true });
928
- }),
929
- stop: vitest.vi.fn((callback) => {
930
- callback?.({ finished: false });
931
- }),
932
- reset: vitest.vi.fn()
933
- };
934
- }
935
- function resolveAnimatedLeaf(v) {
936
- if (v instanceof AnimatedNode) return v.__getValue();
937
- if (v && typeof v === "object" && typeof v.__getValue === "function") return v.__getValue();
938
- if (v && typeof v === "object" && !Array.isArray(v) && typeof v.getValue === "function") return v.getValue();
939
- return v;
940
- }
941
- function resolveAnimatedStyle(style) {
942
- if (Array.isArray(style)) return style.map(resolveAnimatedStyle);
943
- const asLeaf = resolveAnimatedLeaf(style);
944
- if (asLeaf !== style) return asLeaf;
945
- if (style && typeof style === "object") {
946
- const out = {};
947
- for (const key of Object.keys(style)) {
948
- const val = style[key];
949
- if (key === "transform" && Array.isArray(val)) out[key] = val.map((t) => t && typeof t === "object" && !(t instanceof AnimatedNode) ? Object.fromEntries(Object.keys(t).map((tk) => [tk, resolveAnimatedLeaf(t[tk])])) : resolveAnimatedLeaf(t));
950
- else out[key] = resolveAnimatedLeaf(val);
951
- }
952
- return out;
953
- }
954
- return style;
955
- }
956
- function collectAnimatedNodes(style, out) {
957
- if (style instanceof AnimatedNode) {
958
- out.add(style);
959
- return;
960
- }
961
- if (Array.isArray(style)) {
962
- for (const s of style) collectAnimatedNodes(s, out);
963
- return;
964
- }
965
- if (style && typeof style === "object") for (const key of Object.keys(style)) collectAnimatedNodes(style[key], out);
966
- }
967
- function useAnimatedStyleSubscription(style) {
968
- const [, force] = react.default.useReducer((n) => n + 1, 0);
969
- react.default.useEffect(() => {
970
- const nodes = /* @__PURE__ */ new Set();
971
- collectAnimatedNodes(style, nodes);
972
- if (nodes.size === 0) return void 0;
973
- for (const node of nodes) node.__addChild(force);
974
- return () => {
975
- for (const node of nodes) node.__removeChild(force);
976
- };
977
- });
978
- }
979
- function createAnimatedWrapper(displayName) {
980
- const hostName = displayName.replace(/^Animated\./, "");
981
- const Component = react.default.forwardRef((props, ref) => {
982
- useAnimatedStyleSubscription(props?.style);
983
- if (props && props.style !== void 0) {
984
- const { style, ...rest } = props;
985
- return react.default.createElement(hostName, {
986
- ...rest,
987
- style: resolveAnimatedStyle(style),
988
- ref
989
- });
990
- }
991
- return react.default.createElement(hostName, {
992
- ...props,
993
- ref
994
- });
995
- });
996
- Component.displayName = displayName;
997
- return Component;
998
- }
999
- function stopTracking(value) {
1000
- if (value._tracking) {
1001
- value._tracking.source.__removeChild(value._tracking.child);
1002
- value._tracking = null;
1003
- }
1004
- }
1005
- function startTracking(value, toValue) {
1006
- stopTracking(value);
1007
- if (toValue instanceof AnimatedValue) {
1008
- value.setValue(toValue.getValue());
1009
- const child = () => value.setValue(toValue.__getValue());
1010
- toValue.__addChild(child);
1011
- value._tracking = {
1012
- source: toValue,
1013
- child
1014
- };
1015
- } else value.setValue(toValue);
1016
- }
1017
- var AnimatedDiffClamp = class extends AnimatedNode {
1018
- _current;
1019
- constructor(a, min, max) {
1020
- super();
1021
- let lastInput = operandValue(a);
1022
- this._current = Math.min(Math.max(lastInput, min), max);
1023
- if (a instanceof AnimatedNode) a.__addChild(() => {
1024
- const value = Number(a.__getValue());
1025
- const diff = value - lastInput;
1026
- lastInput = value;
1027
- this._current = Math.min(Math.max(this._current + diff, min), max);
1028
- this._notify();
1029
- });
1030
- }
1031
- __getValue() {
1032
- return this._current;
1033
- }
1034
- };
1035
- function createAnimatedMock() {
1036
- return {
1037
- Value: AnimatedValue,
1038
- ValueXY: AnimatedValueXY,
1039
- Color: AnimatedColor,
1040
- timing: vitest.vi.fn((value, config) => {
1041
- return createAnimation(() => {
1042
- if (value instanceof AnimatedValue && config?.toValue != null) startTracking(value, config.toValue);
1043
- });
1044
- }),
1045
- spring: vitest.vi.fn((value, config) => {
1046
- return createAnimation(() => {
1047
- if (value instanceof AnimatedValue && config?.toValue != null) startTracking(value, config.toValue);
1048
- });
1049
- }),
1050
- decay: vitest.vi.fn((_value, _config) => createAnimation()),
1051
- sequence: vitest.vi.fn((animations) => {
1052
- let current = 0;
1053
- let cb;
1054
- return {
1055
- start: vitest.vi.fn((endCallback) => {
1056
- cb = endCallback;
1057
- if (animations.length === 0) {
1058
- cb?.({ finished: true });
1059
- return;
1060
- }
1061
- if (current >= animations.length) current = 0;
1062
- const runNext = (result) => {
1063
- if (!result.finished) {
1064
- cb?.({ finished: false });
1065
- return;
1066
- }
1067
- current++;
1068
- if (current >= animations.length) {
1069
- cb?.({ finished: true });
1070
- return;
1071
- }
1072
- animations[current]?.start(runNext);
1073
- };
1074
- animations[current]?.start(runNext);
1075
- }),
1076
- stop: vitest.vi.fn(() => {
1077
- if (current < animations.length) animations[current]?.stop?.();
1078
- }),
1079
- reset: vitest.vi.fn(() => {
1080
- current = 0;
1081
- for (const anim of animations) anim?.reset?.();
1082
- })
1083
- };
1084
- }),
1085
- parallel: vitest.vi.fn((animations) => {
1086
- let doneCount = 0;
1087
- let hasBeenStopped = false;
1088
- let cb;
1089
- const validAnims = animations.filter(Boolean);
1090
- return {
1091
- start: vitest.vi.fn((endCallback) => {
1092
- cb = endCallback;
1093
- doneCount = 0;
1094
- hasBeenStopped = false;
1095
- if (validAnims.length === 0) {
1096
- cb?.({ finished: true });
1097
- return;
1098
- }
1099
- validAnims.forEach((anim) => {
1100
- anim.start((result) => {
1101
- doneCount++;
1102
- if (!result.finished && !hasBeenStopped) {
1103
- hasBeenStopped = true;
1104
- validAnims.forEach((other) => {
1105
- if (other !== anim) other.stop?.();
1106
- });
1107
- }
1108
- if (doneCount >= validAnims.length) cb?.(result);
1109
- });
1110
- });
1111
- }),
1112
- stop: vitest.vi.fn(() => {
1113
- hasBeenStopped = true;
1114
- validAnims.forEach((anim) => {
1115
- anim.stop?.();
1116
- });
1117
- }),
1118
- reset: vitest.vi.fn(() => {
1119
- for (const anim of validAnims) anim?.reset?.();
1120
- })
1121
- };
1122
- }),
1123
- stagger: vitest.vi.fn((_time, animations) => {
1124
- const validAnims = animations.filter(Boolean);
1125
- let doneCount = 0;
1126
- let hasBeenStopped = false;
1127
- return {
1128
- start: vitest.vi.fn((endCallback) => {
1129
- doneCount = 0;
1130
- hasBeenStopped = false;
1131
- if (validAnims.length === 0) {
1132
- endCallback?.({ finished: true });
1133
- return;
1134
- }
1135
- validAnims.forEach((anim) => {
1136
- anim.start?.((result) => {
1137
- doneCount++;
1138
- if (!result.finished && !hasBeenStopped) {
1139
- hasBeenStopped = true;
1140
- validAnims.forEach((other) => {
1141
- if (other !== anim) other.stop?.();
1142
- });
1143
- }
1144
- if (doneCount >= validAnims.length) endCallback?.(result);
1145
- });
1146
- });
1147
- }),
1148
- stop: vitest.vi.fn(() => {
1149
- hasBeenStopped = true;
1150
- validAnims.forEach((anim) => anim.stop?.());
1151
- }),
1152
- reset: vitest.vi.fn(() => {
1153
- validAnims.forEach((anim) => anim.reset?.());
1154
- })
1155
- };
1156
- }),
1157
- loop: vitest.vi.fn((animation, config) => {
1158
- const iterations = config?.iterations;
1159
- const resetBeforeIteration = config?.resetBeforeIteration !== false;
1160
- let stopped = false;
1161
- let startCallback;
1162
- return {
1163
- start: vitest.vi.fn((endCallback) => {
1164
- stopped = false;
1165
- startCallback = endCallback;
1166
- if (iterations === 0) {
1167
- endCallback?.({ finished: true });
1168
- return;
1169
- }
1170
- let iterationCount = 0;
1171
- const onIteration = (result) => {
1172
- if (stopped || !result.finished) {
1173
- startCallback?.(result);
1174
- return;
1175
- }
1176
- iterationCount++;
1177
- if (iterations != null && iterations > 0 && iterationCount >= iterations) {
1178
- startCallback?.({ finished: true });
1179
- return;
1180
- }
1181
- if (resetBeforeIteration) animation.reset?.();
1182
- animation.start(onIteration);
1183
- };
1184
- if (resetBeforeIteration) animation.reset?.();
1185
- animation.start(onIteration);
1186
- }),
1187
- stop: vitest.vi.fn(() => {
1188
- stopped = true;
1189
- animation.stop?.();
1190
- }),
1191
- reset: vitest.vi.fn(() => {
1192
- animation.reset?.();
1193
- })
1194
- };
1195
- }),
1196
- delay: vitest.vi.fn((_time) => {
1197
- return createAnimation();
1198
- }),
1199
- add: vitest.vi.fn((a, b) => new AnimatedOp([a, b], () => operandValue(a) + operandValue(b))),
1200
- subtract: vitest.vi.fn((a, b) => new AnimatedOp([a, b], () => operandValue(a) - operandValue(b))),
1201
- multiply: vitest.vi.fn((a, b) => new AnimatedOp([a, b], () => operandValue(a) * operandValue(b))),
1202
- divide: vitest.vi.fn((a, b) => new AnimatedOp([a, b], () => {
1203
- const divisor = operandValue(b);
1204
- return divisor === 0 ? 0 : operandValue(a) / divisor;
1205
- })),
1206
- modulo: vitest.vi.fn((a, modulus) => new AnimatedOp([a], () => (operandValue(a) % modulus + modulus) % modulus)),
1207
- diffClamp: vitest.vi.fn((a, min, max) => new AnimatedDiffClamp(a, min, max)),
1208
- event: vitest.vi.fn((argMapping, config) => {
1209
- const handler = vitest.vi.fn((...args) => {
1210
- argMapping.forEach((mapping, index) => {
1211
- if (mapping && args[index]) traverseMapping(mapping, args[index]);
1212
- });
1213
- config?.listener?.(...args);
1214
- });
1215
- function traverseMapping(mapping, value) {
1216
- if (mapping instanceof AnimatedValue && typeof value === "number") {
1217
- mapping.setValue(value);
1218
- return;
1219
- }
1220
- if (typeof mapping === "object" && mapping !== null && typeof value === "object" && value !== null) {
1221
- for (const key of Object.keys(mapping)) if (key in value) traverseMapping(mapping[key], value[key]);
1222
- }
1223
- }
1224
- return handler;
1225
- }),
1226
- forkEvent: vitest.vi.fn((handler, listener) => {
1227
- return (...args) => {
1228
- if (typeof handler === "function") handler(...args);
1229
- else if (handler && handler.__isNative) {}
1230
- listener(...args);
1231
- };
1232
- }),
1233
- unforkEvent: vitest.vi.fn(),
1234
- createAnimatedComponent: vitest.vi.fn((component) => {
1235
- const Wrapper = react.default.forwardRef((props, ref) => {
1236
- useAnimatedStyleSubscription(props?.style);
1237
- if (props && props.style !== void 0) {
1238
- const { style, ...rest } = props;
1239
- return react.default.createElement(component, {
1240
- ...rest,
1241
- style: resolveAnimatedStyle(style),
1242
- ref
1243
- });
1244
- }
1245
- return react.default.createElement(component, {
1246
- ...props,
1247
- ref
1248
- });
1249
- });
1250
- Wrapper.displayName = `Animated(${component.displayName || component.name || "Component"})`;
1251
- return Wrapper;
1252
- }),
1253
- View: createAnimatedWrapper("Animated.View"),
1254
- Text: createAnimatedWrapper("Animated.Text"),
1255
- Image: createAnimatedWrapper("Animated.Image"),
1256
- ScrollView: createAnimatedWrapper("Animated.ScrollView"),
1257
- FlatList: createAnimatedWrapper("Animated.FlatList"),
1258
- SectionList: createAnimatedWrapper("Animated.SectionList")
1259
- };
1260
- }
1261
- //#endregion
1262
- //#region src/mocks/apis/Alert.ts
1263
- function createAlertMock() {
1264
- return {
1265
- alert: vitest.vi.fn(),
1266
- prompt: vitest.vi.fn()
1267
- };
1268
- }
1269
- //#endregion
1270
- //#region src/mocks/apis/Linking.ts
1271
- function createLinkingMock() {
1272
- return {
1273
- openURL: vitest.vi.fn(() => Promise.resolve()),
1274
- canOpenURL: vitest.vi.fn(() => Promise.resolve(true)),
1275
- getInitialURL: vitest.vi.fn(() => Promise.resolve(null)),
1276
- openSettings: vitest.vi.fn(() => Promise.resolve()),
1277
- sendIntent: vitest.vi.fn(() => Promise.resolve()),
1278
- addEventListener: vitest.vi.fn(() => ({ remove: vitest.vi.fn() }))
1279
- };
1280
- }
1281
- //#endregion
1282
- //#region src/mocks/apis/AppState.ts
1283
- function createAppStateMock() {
1284
- const listeners = /* @__PURE__ */ new Map();
1285
- const mock = {
1286
- currentState: "active",
1287
- isAvailable: true,
1288
- addEventListener: vitest.vi.fn((type, handler) => {
1289
- if (!listeners.has(type)) listeners.set(type, /* @__PURE__ */ new Set());
1290
- listeners.get(type).add(handler);
1291
- return { remove: vitest.vi.fn(() => listeners.get(type)?.delete(handler)) };
1292
- }),
1293
- _setState: (state) => {
1294
- mock.currentState = state;
1295
- listeners.get("change")?.forEach((fn) => fn(state));
1296
- },
1297
- _reset: () => {
1298
- mock.currentState = "active";
1299
- listeners.clear();
1300
- }
1301
- };
1302
- return mock;
1303
- }
1304
- //#endregion
1305
- //#region src/mocks/apis/Keyboard.ts
1306
- function createKeyboardMock() {
1307
- let visible = false;
1308
- let keyboardHeight = 0;
1309
- const listeners = /* @__PURE__ */ new Map();
1310
- return {
1311
- dismiss: vitest.vi.fn(() => {
1312
- visible = false;
1313
- keyboardHeight = 0;
1314
- }),
1315
- addListener: vitest.vi.fn((event, handler) => {
1316
- if (!listeners.has(event)) listeners.set(event, /* @__PURE__ */ new Set());
1317
- listeners.get(event).add(handler);
1318
- return { remove: vitest.vi.fn(() => listeners.get(event)?.delete(handler)) };
1319
- }),
1320
- removeListener: vitest.vi.fn((event, handler) => {
1321
- listeners.get(event)?.delete(handler);
1322
- }),
1323
- removeAllListeners: vitest.vi.fn((event) => {
1324
- if (event) listeners.delete(event);
1325
- else listeners.clear();
1326
- }),
1327
- isVisible: vitest.vi.fn(() => visible),
1328
- metrics: vitest.vi.fn(() => visible ? {
1329
- screenX: 0,
1330
- screenY: 844 - keyboardHeight,
1331
- width: 390,
1332
- height: keyboardHeight
1333
- } : void 0),
1334
- scheduleLayoutAnimation: vitest.vi.fn(),
1335
- _show: (height = 336) => {
1336
- visible = true;
1337
- keyboardHeight = height;
1338
- listeners.get("keyboardDidShow")?.forEach((fn) => fn({ endCoordinates: {
1339
- screenX: 0,
1340
- screenY: 844 - height,
1341
- width: 390,
1342
- height
1343
- } }));
1344
- },
1345
- _hide: () => {
1346
- visible = false;
1347
- keyboardHeight = 0;
1348
- listeners.get("keyboardDidHide")?.forEach((fn) => fn({}));
1349
- },
1350
- _reset: () => {
1351
- visible = false;
1352
- keyboardHeight = 0;
1353
- listeners.clear();
1354
- }
1355
- };
1356
- }
1357
- //#endregion
1358
- //#region src/mocks/apis/BackHandler.ts
1359
- function createBackHandlerMock() {
1360
- const listeners = /* @__PURE__ */ new Set();
1361
- return {
1362
- exitApp: vitest.vi.fn(),
1363
- addEventListener: vitest.vi.fn((event, handler) => {
1364
- if (event === "hardwareBackPress") listeners.add(handler);
1365
- return { remove: vitest.vi.fn(() => listeners.delete(handler)) };
1366
- }),
1367
- _simulateBackPress: () => {
1368
- const handlers = [...listeners].reverse();
1369
- for (const handler of handlers) if (handler() === true) return;
1370
- },
1371
- _reset: () => {
1372
- listeners.clear();
1373
- }
1374
- };
1375
- }
1376
- //#endregion
1377
- //#region src/mocks/apis/Vibration.ts
1378
- function createVibrationMock() {
1379
- return {
1380
- vibrate: vitest.vi.fn(),
1381
- cancel: vitest.vi.fn()
1382
- };
1383
- }
1384
- //#endregion
1385
- //#region src/mocks/apis/PermissionsAndroid.ts
1386
- function createPermissionsAndroidMock() {
1387
- return {
1388
- PERMISSIONS: {
1389
- ACCEPT_HANDOVER: "android.permission.ACCEPT_HANDOVER",
1390
- ACCESS_BACKGROUND_LOCATION: "android.permission.ACCESS_BACKGROUND_LOCATION",
1391
- ACCESS_COARSE_LOCATION: "android.permission.ACCESS_COARSE_LOCATION",
1392
- ACCESS_FINE_LOCATION: "android.permission.ACCESS_FINE_LOCATION",
1393
- ACCESS_MEDIA_LOCATION: "android.permission.ACCESS_MEDIA_LOCATION",
1394
- ACTIVITY_RECOGNITION: "android.permission.ACTIVITY_RECOGNITION",
1395
- BLUETOOTH_ADVERTISE: "android.permission.BLUETOOTH_ADVERTISE",
1396
- BLUETOOTH_CONNECT: "android.permission.BLUETOOTH_CONNECT",
1397
- BLUETOOTH_SCAN: "android.permission.BLUETOOTH_SCAN",
1398
- BODY_SENSORS: "android.permission.BODY_SENSORS",
1399
- BODY_SENSORS_BACKGROUND: "android.permission.BODY_SENSORS_BACKGROUND",
1400
- CALL_PHONE: "android.permission.CALL_PHONE",
1401
- CAMERA: "android.permission.CAMERA",
1402
- GET_ACCOUNTS: "android.permission.GET_ACCOUNTS",
1403
- NEARBY_WIFI_DEVICES: "android.permission.NEARBY_WIFI_DEVICES",
1404
- POST_NOTIFICATIONS: "android.permission.POST_NOTIFICATIONS",
1405
- PROCESS_OUTGOING_CALLS: "android.permission.PROCESS_OUTGOING_CALLS",
1406
- READ_CALENDAR: "android.permission.READ_CALENDAR",
1407
- READ_CALL_LOG: "android.permission.READ_CALL_LOG",
1408
- READ_CONTACTS: "android.permission.READ_CONTACTS",
1409
- READ_EXTERNAL_STORAGE: "android.permission.READ_EXTERNAL_STORAGE",
1410
- READ_MEDIA_AUDIO: "android.permission.READ_MEDIA_AUDIO",
1411
- READ_MEDIA_IMAGES: "android.permission.READ_MEDIA_IMAGES",
1412
- READ_MEDIA_VIDEO: "android.permission.READ_MEDIA_VIDEO",
1413
- READ_PHONE_NUMBERS: "android.permission.READ_PHONE_NUMBERS",
1414
- READ_PHONE_STATE: "android.permission.READ_PHONE_STATE",
1415
- READ_SMS: "android.permission.READ_SMS",
1416
- RECEIVE_MMS: "android.permission.RECEIVE_MMS",
1417
- RECEIVE_SMS: "android.permission.RECEIVE_SMS",
1418
- RECEIVE_WAP_PUSH: "android.permission.RECEIVE_WAP_PUSH",
1419
- RECORD_AUDIO: "android.permission.RECORD_AUDIO",
1420
- SEND_SMS: "android.permission.SEND_SMS",
1421
- USE_SIP: "android.permission.USE_SIP",
1422
- WRITE_CALENDAR: "android.permission.WRITE_CALENDAR",
1423
- WRITE_CALL_LOG: "android.permission.WRITE_CALL_LOG",
1424
- WRITE_CONTACTS: "android.permission.WRITE_CONTACTS",
1425
- WRITE_EXTERNAL_STORAGE: "android.permission.WRITE_EXTERNAL_STORAGE"
1426
- },
1427
- RESULTS: {
1428
- GRANTED: "granted",
1429
- DENIED: "denied",
1430
- NEVER_ASK_AGAIN: "never_ask_again"
1431
- },
1432
- check: vitest.vi.fn(() => Promise.resolve(true)),
1433
- request: vitest.vi.fn(() => Promise.resolve("granted")),
1434
- requestMultiple: vitest.vi.fn((permissions) => Promise.resolve(permissions.reduce((acc, p) => ({
1435
- ...acc,
1436
- [p]: "granted"
1437
- }), {})))
1438
- };
1439
- }
1440
- //#endregion
1441
- //#region src/mocks/apis/Appearance.ts
1442
- function createAppearanceMock() {
1443
- let colorScheme = "light";
1444
- const listeners = /* @__PURE__ */ new Set();
1445
- return {
1446
- getColorScheme: vitest.vi.fn(() => colorScheme),
1447
- setColorScheme: vitest.vi.fn((scheme) => {
1448
- colorScheme = scheme;
1449
- listeners.forEach((fn) => fn({ colorScheme: scheme }));
1450
- }),
1451
- addChangeListener: vitest.vi.fn((listener) => {
1452
- listeners.add(listener);
1453
- return { remove: () => {
1454
- listeners.delete(listener);
1455
- } };
1456
- }),
1457
- _reset: () => {
1458
- colorScheme = "light";
1459
- listeners.clear();
1460
- }
1461
- };
1462
- }
1463
- //#endregion
1464
- //#region src/mocks/apis/PixelRatio.ts
1465
- function createPixelRatioMock(getDimensions) {
1466
- const getScale = () => getDimensions ? getDimensions().scale : 3;
1467
- const getFontScale = () => getDimensions ? getDimensions().fontScale : 1;
1468
- return {
1469
- get: vitest.vi.fn(() => getScale()),
1470
- getFontScale: vitest.vi.fn(() => getFontScale()),
1471
- getPixelSizeForLayoutSize: vitest.vi.fn((layoutSize) => Math.round(layoutSize * getScale())),
1472
- roundToNearestPixel: vitest.vi.fn((layoutSize) => {
1473
- const ratio = getScale();
1474
- return Math.round(layoutSize * ratio) / ratio;
1475
- })
1476
- };
1477
- }
1478
- //#endregion
1479
- //#region src/mocks/apis/LayoutAnimation.ts
1480
- function createLayoutAnimationMock() {
1481
- return {
1482
- configureNext: vitest.vi.fn(),
1483
- create: vitest.vi.fn(() => ({
1484
- duration: 300,
1485
- create: {
1486
- type: "easeInEaseOut",
1487
- property: "opacity"
1488
- },
1489
- update: { type: "easeInEaseOut" },
1490
- delete: {
1491
- type: "easeInEaseOut",
1492
- property: "opacity"
1493
- }
1494
- })),
1495
- Types: {
1496
- spring: "spring",
1497
- linear: "linear",
1498
- easeInEaseOut: "easeInEaseOut",
1499
- easeIn: "easeIn",
1500
- easeOut: "easeOut"
1501
- },
1502
- Properties: {
1503
- opacity: "opacity",
1504
- scaleX: "scaleX",
1505
- scaleY: "scaleY",
1506
- scaleXY: "scaleXY"
1507
- },
1508
- Presets: {
1509
- easeInEaseOut: {
1510
- duration: 300,
1511
- create: {
1512
- type: "easeInEaseOut",
1513
- property: "opacity"
1514
- },
1515
- update: { type: "easeInEaseOut" },
1516
- delete: {
1517
- type: "easeInEaseOut",
1518
- property: "opacity"
1519
- }
1520
- },
1521
- linear: {
1522
- duration: 500,
1523
- create: {
1524
- type: "linear",
1525
- property: "opacity"
1526
- },
1527
- update: { type: "linear" },
1528
- delete: {
1529
- type: "linear",
1530
- property: "opacity"
1531
- }
1532
- },
1533
- spring: {
1534
- duration: 700,
1535
- create: {
1536
- type: "linear",
1537
- property: "opacity"
1538
- },
1539
- update: {
1540
- type: "spring",
1541
- springDamping: .4
1542
- },
1543
- delete: {
1544
- type: "linear",
1545
- property: "opacity"
1546
- }
1547
- }
1548
- }
1549
- };
1550
- }
1551
- //#endregion
1552
- //#region src/mocks/apis/Clipboard.ts
1553
- function createClipboardMock() {
1554
- let content = "";
1555
- return {
1556
- getString: vitest.vi.fn(() => Promise.resolve(content)),
1557
- setString: vitest.vi.fn((text) => {
1558
- content = text;
1559
- }),
1560
- hasString: vitest.vi.fn(() => Promise.resolve(content.length > 0))
1561
- };
1562
- }
1563
- //#endregion
1564
- //#region src/mocks/apis/Share.ts
1565
- function createShareMock() {
1566
- return {
1567
- share: vitest.vi.fn(async () => ({ action: "sharedAction" })),
1568
- sharedAction: "sharedAction",
1569
- dismissedAction: "dismissedAction"
1570
- };
1571
- }
1572
- //#endregion
1573
- //#region src/mocks/apis/AccessibilityInfo.ts
1574
- function createAccessibilityInfoMock() {
1575
- return {
1576
- isScreenReaderEnabled: vitest.vi.fn(async () => false),
1577
- isBoldTextEnabled: vitest.vi.fn(async () => false),
1578
- isGrayscaleEnabled: vitest.vi.fn(async () => false),
1579
- isInvertColorsEnabled: vitest.vi.fn(async () => false),
1580
- isReduceMotionEnabled: vitest.vi.fn(async () => false),
1581
- isReduceTransparencyEnabled: vitest.vi.fn(async () => false),
1582
- prefersCrossFadeTransitions: vitest.vi.fn(async () => false),
1583
- addEventListener: vitest.vi.fn((_eventName, _handler) => ({ remove: vitest.vi.fn() })),
1584
- announceForAccessibility: vitest.vi.fn(),
1585
- announceForAccessibilityWithOptions: vitest.vi.fn(),
1586
- setAccessibilityFocus: vitest.vi.fn(),
1587
- sendAccessibilityEvent: vitest.vi.fn(),
1588
- getRecommendedTimeoutMillis: vitest.vi.fn(async (originalTimeout) => originalTimeout)
1589
- };
1590
- }
1591
- //#endregion
1592
- //#region src/mocks/apis/InteractionManager.ts
1593
- function createInteractionManagerMock() {
1594
- return {
1595
- runAfterInteractions: vitest.vi.fn((task) => {
1596
- (typeof task === "function" ? task : task?.gen)?.();
1597
- const promise = Promise.resolve();
1598
- return {
1599
- then: promise.then.bind(promise),
1600
- done: promise.then.bind(promise),
1601
- cancel: vitest.vi.fn()
1602
- };
1603
- }),
1604
- createInteractionHandle: vitest.vi.fn(() => 1),
1605
- clearInteractionHandle: vitest.vi.fn(),
1606
- setDeadline: vitest.vi.fn()
1607
- };
1608
- }
1609
- //#endregion
1610
- //#region src/mocks/apis/PanResponder.ts
1611
- function createPanResponderMock() {
1612
- return { create: vitest.vi.fn((config = {}) => ({ panHandlers: {
1613
- onStartShouldSetResponder: config.onStartShouldSetPanResponder ? vitest.vi.fn((...args) => config.onStartShouldSetPanResponder(...args)) : vitest.vi.fn(() => false),
1614
- onMoveShouldSetResponder: config.onMoveShouldSetPanResponder ? vitest.vi.fn((...args) => config.onMoveShouldSetPanResponder(...args)) : vitest.vi.fn(() => false),
1615
- onStartShouldSetResponderCapture: config.onStartShouldSetPanResponderCapture ? vitest.vi.fn((...args) => config.onStartShouldSetPanResponderCapture(...args)) : vitest.vi.fn(() => false),
1616
- onMoveShouldSetResponderCapture: config.onMoveShouldSetPanResponderCapture ? vitest.vi.fn((...args) => config.onMoveShouldSetPanResponderCapture(...args)) : vitest.vi.fn(() => false),
1617
- onResponderGrant: config.onPanResponderGrant ?? vitest.vi.fn(),
1618
- onResponderReject: config.onPanResponderReject ?? vitest.vi.fn(),
1619
- onResponderStart: config.onPanResponderStart ?? vitest.vi.fn(),
1620
- onResponderMove: config.onPanResponderMove ?? vitest.vi.fn(),
1621
- onResponderEnd: config.onPanResponderEnd ?? vitest.vi.fn(),
1622
- onResponderRelease: config.onPanResponderRelease ?? vitest.vi.fn(),
1623
- onResponderTerminate: config.onPanResponderTerminate ?? vitest.vi.fn(),
1624
- onResponderTerminationRequest: config.onPanResponderTerminationRequest ?? vitest.vi.fn(() => true)
1625
- } })) };
1626
- }
1627
- //#endregion
1628
- //#region src/mocks/apis/ToastAndroid.ts
1629
- function createToastAndroidMock() {
1630
- return {
1631
- show: vitest.vi.fn(),
1632
- showWithGravity: vitest.vi.fn(),
1633
- showWithGravityAndOffset: vitest.vi.fn(),
1634
- SHORT: 0,
1635
- LONG: 1,
1636
- TOP: 0,
1637
- BOTTOM: 1,
1638
- CENTER: 2
1639
- };
1640
- }
1641
- //#endregion
1642
- //#region src/mocks/apis/ActionSheetIOS.ts
1643
- function createActionSheetIOSMock() {
1644
- return {
1645
- showActionSheetWithOptions: vitest.vi.fn(),
1646
- showShareActionSheetWithOptions: vitest.vi.fn()
1647
- };
1648
- }
1649
- //#endregion
1650
- //#region src/mocks/apis/LogBox.ts
1651
- function createLogBoxMock() {
1652
- return {
1653
- ignoreLogs: vitest.vi.fn(),
1654
- ignoreAllLogs: vitest.vi.fn(),
1655
- uninstall: vitest.vi.fn(),
1656
- install: vitest.vi.fn()
1657
- };
1658
- }
1659
- //#endregion
1660
- //#region src/mocks/apis/Easing.ts
1661
- const NEWTON_ITERATIONS = 4;
1662
- const NEWTON_MIN_SLOPE = .001;
1663
- const SUBDIVISION_PRECISION = 1e-7;
1664
- const SUBDIVISION_MAX_ITERATIONS = 10;
1665
- const kSplineTableSize = 11;
1666
- const kSampleStepSize = 1 / (kSplineTableSize - 1);
1667
- function A(aA1, aA2) {
1668
- return 1 - 3 * aA2 + 3 * aA1;
1669
- }
1670
- function B(aA1, aA2) {
1671
- return 3 * aA2 - 6 * aA1;
1672
- }
1673
- function C(aA1) {
1674
- return 3 * aA1;
1675
- }
1676
- function calcBezier(aT, aA1, aA2) {
1677
- return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
1678
- }
1679
- function getSlope(aT, aA1, aA2) {
1680
- return 3 * A(aA1, aA2) * aT * aT + 2 * B(aA1, aA2) * aT + C(aA1);
1681
- }
1682
- function binarySubdivide(aX, aA, aB, mX1, mX2) {
1683
- let currentX;
1684
- let currentT;
1685
- let i = 0;
1686
- let low = aA;
1687
- let high = aB;
1688
- do {
1689
- currentT = low + (high - low) / 2;
1690
- currentX = calcBezier(currentT, mX1, mX2) - aX;
1691
- if (currentX > 0) high = currentT;
1692
- else low = currentT;
1693
- } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
1694
- return currentT;
1695
- }
1696
- function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
1697
- let guessT = aGuessT;
1698
- for (let i = 0; i < NEWTON_ITERATIONS; ++i) {
1699
- const currentSlope = getSlope(guessT, mX1, mX2);
1700
- if (currentSlope === 0) return guessT;
1701
- const currentX = calcBezier(guessT, mX1, mX2) - aX;
1702
- guessT -= currentX / currentSlope;
1703
- }
1704
- return guessT;
1705
- }
1706
- function bezier(mX1, mY1, mX2, mY2) {
1707
- if (!(mX1 >= 0 && mX1 <= 1 && mX2 >= 0 && mX2 <= 1)) throw new Error("bezier x values must be in [0, 1] range");
1708
- if (mX1 === mY1 && mX2 === mY2) return (x) => x;
1709
- const sampleValues = new Float32Array(kSplineTableSize);
1710
- for (let i = 0; i < kSplineTableSize; ++i) sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
1711
- function getTForX(aX) {
1712
- let intervalStart = 0;
1713
- let currentSample = 1;
1714
- const lastSample = kSplineTableSize - 1;
1715
- for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) intervalStart += kSampleStepSize;
1716
- --currentSample;
1717
- const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
1718
- const guessForT = intervalStart + dist * kSampleStepSize;
1719
- const initialSlope = getSlope(guessForT, mX1, mX2);
1720
- if (initialSlope >= NEWTON_MIN_SLOPE) return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
1721
- else if (initialSlope === 0) return guessForT;
1722
- else return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
1723
- }
1724
- return function(x) {
1725
- if (x === 0 || x === 1) return x;
1726
- return calcBezier(getTForX(x), mY1, mY2);
1727
- };
1728
- }
1729
- function createEasingMock() {
1730
- const easeFn = bezier(.42, 0, 1, 1);
1731
- return {
1732
- linear: vitest.vi.fn((t) => t),
1733
- ease: vitest.vi.fn((t) => easeFn(t)),
1734
- quad: vitest.vi.fn((t) => t * t),
1735
- cubic: vitest.vi.fn((t) => t * t * t),
1736
- poly: vitest.vi.fn((n) => (t) => Math.pow(t, n)),
1737
- sin: vitest.vi.fn((t) => 1 - Math.cos(t * Math.PI / 2)),
1738
- circle: vitest.vi.fn((t) => 1 - Math.sqrt(1 - t * t)),
1739
- exp: vitest.vi.fn((t) => Math.pow(2, 10 * (t - 1))),
1740
- elastic: vitest.vi.fn((bounciness = 1) => (t) => {
1741
- const p = bounciness * Math.PI;
1742
- return 1 - Math.pow(Math.cos(t * Math.PI / 2), 3) * Math.cos(t * p);
1743
- }),
1744
- back: vitest.vi.fn((s = 1.70158) => (t) => t * t * ((s + 1) * t - s)),
1745
- bounce: vitest.vi.fn((t) => {
1746
- if (t < 1 / 2.75) return 7.5625 * t * t;
1747
- if (t < 2 / 2.75) {
1748
- const t2 = t - 1.5 / 2.75;
1749
- return 7.5625 * t2 * t2 + .75;
1750
- }
1751
- if (t < 2.5 / 2.75) {
1752
- const t2 = t - 2.25 / 2.75;
1753
- return 7.5625 * t2 * t2 + .9375;
1754
- }
1755
- const t2 = t - 2.625 / 2.75;
1756
- return 7.5625 * t2 * t2 + .984375;
1757
- }),
1758
- bezier: vitest.vi.fn((x1, y1, x2, y2) => bezier(x1, y1, x2, y2)),
1759
- in: vitest.vi.fn((easing) => easing),
1760
- out: vitest.vi.fn((easing) => (t) => 1 - easing(1 - t)),
1761
- inOut: vitest.vi.fn((easing) => (t) => {
1762
- if (t < .5) return easing(t * 2) / 2;
1763
- return 1 - easing((1 - t) * 2) / 2;
1764
- }),
1765
- step0: vitest.vi.fn((t) => t > 0 ? 1 : 0),
1766
- step1: vitest.vi.fn((t) => t >= 1 ? 1 : 0)
1767
- };
1768
- }
1769
- //#endregion
1770
- //#region src/mocks/apis/I18nManager.ts
1771
- function createI18nManagerMock() {
1772
- const mock = {
1773
- isRTL: false,
1774
- doLeftAndRightSwapInRTL: true,
1775
- allowRTL: vitest.vi.fn((_allow) => {}),
1776
- forceRTL: vitest.vi.fn((force) => {
1777
- mock.isRTL = force;
1778
- }),
1779
- swapLeftAndRightInRTL: vitest.vi.fn((swap) => {
1780
- mock.doLeftAndRightSwapInRTL = swap;
1781
- }),
1782
- getConstants: vitest.vi.fn(() => ({
1783
- isRTL: mock.isRTL,
1784
- doLeftAndRightSwapInRTL: mock.doLeftAndRightSwapInRTL
1785
- })),
1786
- _reset: () => {
1787
- mock.isRTL = false;
1788
- mock.doLeftAndRightSwapInRTL = true;
1789
- }
1790
- };
1791
- return mock;
1792
- }
1793
- //#endregion
1794
- //#region src/mocks/apis/DeviceEventEmitter.ts
1795
- function createDeviceEventEmitterMock() {
1796
- const listeners = /* @__PURE__ */ new Map();
1797
- return {
1798
- addListener: vitest.vi.fn((event, handler) => {
1799
- if (!listeners.has(event)) listeners.set(event, /* @__PURE__ */ new Set());
1800
- listeners.get(event).add(handler);
1801
- return { remove: vitest.vi.fn(() => listeners.get(event)?.delete(handler)) };
1802
- }),
1803
- removeListener: vitest.vi.fn((event, handler) => {
1804
- listeners.get(event)?.delete(handler);
1805
- }),
1806
- removeAllListeners: vitest.vi.fn((event) => {
1807
- if (event) listeners.delete(event);
1808
- else listeners.clear();
1809
- }),
1810
- removeSubscription: vitest.vi.fn(),
1811
- emit: vitest.vi.fn((event, ...args) => {
1812
- listeners.get(event)?.forEach((fn) => fn(...args));
1813
- }),
1814
- listenerCount: vitest.vi.fn((event) => listeners.get(event)?.size ?? 0),
1815
- _reset: () => {
1816
- listeners.clear();
1817
- }
1818
- };
1819
- }
1820
- //#endregion
1821
- //#region src/mocks/apis/useColorScheme.ts
1822
- function createUseColorSchemeMock() {
1823
- let scheme = "light";
1824
- const listeners = /* @__PURE__ */ new Set();
1825
- const hook = () => {
1826
- try {
1827
- const [currentScheme, setCurrentScheme] = react.default.useState(scheme);
1828
- react.default.useEffect(() => {
1829
- listeners.add(setCurrentScheme);
1830
- return () => {
1831
- listeners.delete(setCurrentScheme);
1832
- };
1833
- }, []);
1834
- return currentScheme;
1835
- } catch {
1836
- return scheme;
1837
- }
1838
- };
1839
- hook._setScheme = (s) => {
1840
- scheme = s;
1841
- listeners.forEach((fn) => fn(s));
1842
- };
1843
- hook._resetScheme = (s) => {
1844
- scheme = s;
1845
- listeners.clear();
1846
- };
1847
- return hook;
1848
- }
1849
- //#endregion
1850
- //#region src/mocks/apis/useWindowDimensions.ts
1851
- function createUseWindowDimensionsMock() {
1852
- let dims = {
1853
- width: 390,
1854
- height: 844,
1855
- scale: 3,
1856
- fontScale: 1
1857
- };
1858
- const listeners = /* @__PURE__ */ new Set();
1859
- const hook = () => {
1860
- try {
1861
- const [currentDims, setCurrentDims] = react.default.useState({ ...dims });
1862
- react.default.useEffect(() => {
1863
- listeners.add(setCurrentDims);
1864
- return () => {
1865
- listeners.delete(setCurrentDims);
1866
- };
1867
- }, []);
1868
- return currentDims;
1869
- } catch {
1870
- return { ...dims };
1871
- }
1872
- };
1873
- hook._setDimensions = (d) => {
1874
- dims = {
1875
- ...dims,
1876
- ...d
1877
- };
1878
- listeners.forEach((fn) => fn({ ...dims }));
1879
- };
1880
- hook._resetDimensions = (d) => {
1881
- dims = { ...d };
1882
- listeners.clear();
1883
- };
1884
- return hook;
1885
- }
1886
- //#endregion
1887
- //#region src/mocks/native/NativeModules.ts
1888
- /**
1889
- * Creates a callable proxy — used for module methods.
1890
- * Calling it returns undefined; accessing properties returns another
1891
- * callable proxy (supporting arbitrary depth like Foo.bar.baz()).
1892
- */
1893
- function createCallableProxy() {
1894
- const cache = /* @__PURE__ */ new Map();
1895
- const noop = () => {};
1896
- return new Proxy(noop, {
1897
- get(_target, prop) {
1898
- if (typeof prop === "symbol") return void 0;
1899
- if (cache.has(prop)) return cache.get(prop);
1900
- const child = createCallableProxy();
1901
- cache.set(prop, child);
1902
- return child;
1903
- },
1904
- apply() {}
1905
- });
1906
- }
1907
- /**
1908
- * Creates an object proxy for a native module.
1909
- * typeof returns "object" (matching real RN), property access returns
1910
- * callable proxies so NativeModules.Foo.bar() works without throwing.
1911
- *
1912
- * Property accesses are cached so that NativeModules.Foo === NativeModules.Foo
1913
- * holds true, matching real React Native identity semantics.
1914
- */
1915
- function createModuleProxy$1() {
1916
- const cache = /* @__PURE__ */ new Map();
1917
- return new Proxy({}, { get(_target, prop) {
1918
- if (typeof prop === "symbol") return void 0;
1919
- if (cache.has(prop)) return cache.get(prop);
1920
- const child = createCallableProxy();
1921
- cache.set(prop, child);
1922
- return child;
1923
- } });
1924
- }
1925
- function createNativeModulesMock() {
1926
- const cache = /* @__PURE__ */ new Map();
1927
- return new Proxy({}, { get(_target, prop) {
1928
- if (typeof prop === "symbol") return void 0;
1929
- if (cache.has(prop)) return cache.get(prop);
1930
- const child = createModuleProxy$1();
1931
- cache.set(prop, child);
1932
- return child;
1933
- } });
1934
- }
1935
- //#endregion
1936
- //#region src/mocks/native/TurboModuleRegistry.ts
1937
- function createModuleProxy() {
1938
- return new Proxy({}, { get(_target, prop) {
1939
- if (typeof prop === "symbol") return void 0;
1940
- if (prop === "then") return void 0;
1941
- return () => {};
1942
- } });
1943
- }
1944
- function createTurboModuleRegistryMock() {
1945
- return {
1946
- getEnforcing(_name) {
1947
- return createModuleProxy();
1948
- },
1949
- get(_name) {
1950
- return null;
1951
- }
1952
- };
1953
- }
1954
- //#endregion
1955
- //#region src/mocks/native/UIManager.ts
1956
- function createUIManagerMock() {
1957
- return {
1958
- measure: vitest.vi.fn((_node, callback) => {
1959
- callback(0, 0, 0, 0, 0, 0);
1960
- }),
1961
- measureInWindow: vitest.vi.fn((_node, callback) => {
1962
- callback(0, 0, 0, 0);
1963
- }),
1964
- measureLayout: vitest.vi.fn((_node, _relativeNode, _onFail, onSuccess) => {
1965
- onSuccess(0, 0, 0, 0);
1966
- }),
1967
- setChildren: vitest.vi.fn(),
1968
- manageChildren: vitest.vi.fn(),
1969
- createView: vitest.vi.fn(),
1970
- updateView: vitest.vi.fn(),
1971
- removeSubviewsFromContainerWithID: vitest.vi.fn(),
1972
- replaceExistingNonRootView: vitest.vi.fn(),
1973
- setLayoutAnimationEnabledExperimental: vitest.vi.fn(),
1974
- configureNextLayoutAnimation: vitest.vi.fn(),
1975
- getViewManagerConfig: vitest.vi.fn((_name) => ({})),
1976
- hasViewManagerConfig: vitest.vi.fn((_name) => false),
1977
- dispatchViewManagerCommand: vitest.vi.fn(),
1978
- findSubviewIn: vitest.vi.fn(),
1979
- viewIsDescendantOf: vitest.vi.fn()
1980
- };
1981
- }
1982
- //#endregion
1983
- //#region src/mocks/native/NativeEventEmitter.ts
1984
- function createNativeEventEmitterMock() {
1985
- return class NativeEventEmitter {
1986
- listeners = /* @__PURE__ */ new Map();
1987
- addListener(event, handler) {
1988
- if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
1989
- this.listeners.get(event).add(handler);
1990
- return { remove: () => {
1991
- this.listeners.get(event)?.delete(handler);
1992
- } };
1993
- }
1994
- removeAllListeners(event) {
1995
- if (event) this.listeners.delete(event);
1996
- else this.listeners.clear();
1997
- }
1998
- emit(event, ...args) {
1999
- this.listeners.get(event)?.forEach((handler) => handler(...args));
2000
- }
2001
- listenerCount(event) {
2002
- return this.listeners.get(event)?.size ?? 0;
2003
- }
2004
- };
2005
- }
2006
- //#endregion
2007
- //#region src/mocks/native/NativeComponentRegistry.ts
2008
- function createNativeComponentRegistryMock() {
2009
- return {
2010
- get(name) {
2011
- const Component = react.default.forwardRef((props, ref) => {
2012
- return react.default.createElement(name, {
2013
- ...props,
2014
- ref
2015
- });
2016
- });
2017
- Component.displayName = name;
2018
- return Component;
2019
- },
2020
- getWithFallback(name) {
2021
- return this.get(name);
2022
- }
2023
- };
2024
- }
2025
- //#endregion
2026
- //#region src/mocks/native/requireNativeComponent.ts
2027
- function createRequireNativeComponentMock() {
2028
- return function requireNativeComponent(viewName) {
2029
- const Component = react.default.forwardRef((props, ref) => {
2030
- return react.default.createElement(viewName, {
2031
- ...props,
2032
- ref
2033
- });
2034
- });
2035
- Component.displayName = viewName;
2036
- return Component;
2037
- };
2038
- }
2039
- //#endregion
2040
- //#region src/mocks/registry.ts
2041
- function createAppRegistryMock() {
2042
- return {
2043
- registerComponent: vitest.vi.fn(),
2044
- registerRunnable: vitest.vi.fn(),
2045
- registerSection: vitest.vi.fn(),
2046
- getAppKeys: vitest.vi.fn(() => []),
2047
- unmountApplicationComponentAtRootTag: vitest.vi.fn(),
2048
- runApplication: vitest.vi.fn(),
2049
- setSurfaceProps: vitest.vi.fn(),
2050
- registerHeadlessTask: vitest.vi.fn(),
2051
- registerCancellableHeadlessTask: vitest.vi.fn(),
2052
- startHeadlessTask: vitest.vi.fn(),
2053
- cancelHeadlessTask: vitest.vi.fn()
2054
- };
2055
- }
2056
- function hslToRgb(h, s, l) {
2057
- const sNorm = s / 100;
2058
- const lNorm = l / 100;
2059
- const c = (1 - Math.abs(2 * lNorm - 1)) * sNorm;
2060
- const hPrime = h / 60;
2061
- const x = c * (1 - Math.abs(hPrime % 2 - 1));
2062
- let r1 = 0, g1 = 0, b1 = 0;
2063
- if (hPrime < 1) {
2064
- r1 = c;
2065
- g1 = x;
2066
- } else if (hPrime < 2) {
2067
- r1 = x;
2068
- g1 = c;
2069
- } else if (hPrime < 3) {
2070
- g1 = c;
2071
- b1 = x;
2072
- } else if (hPrime < 4) {
2073
- g1 = x;
2074
- b1 = c;
2075
- } else if (hPrime < 5) {
2076
- r1 = x;
2077
- b1 = c;
2078
- } else {
2079
- r1 = c;
2080
- b1 = x;
2081
- }
2082
- const m = lNorm - c / 2;
2083
- return [
2084
- Math.round((r1 + m) * 255),
2085
- Math.round((g1 + m) * 255),
2086
- Math.round((b1 + m) * 255)
2087
- ];
2088
- }
2089
- function createProcessColorMock() {
2090
- const namedColors = {
2091
- red: 4294901760,
2092
- green: 4278222848,
2093
- blue: 4278190335,
2094
- white: 4294967295,
2095
- black: 4278190080,
2096
- transparent: 0,
2097
- yellow: 4294967040,
2098
- cyan: 4278255615,
2099
- magenta: 4294902015,
2100
- orange: 4294944e3,
2101
- purple: 4286578816,
2102
- gray: 4286611584,
2103
- grey: 4286611584
2104
- };
2105
- return vitest.vi.fn((color) => {
2106
- if (color == null) return null;
2107
- if (typeof color === "number") return color;
2108
- if (typeof color === "string") {
2109
- const lower = color.toLowerCase().trim();
2110
- if (namedColors[lower] != null) return namedColors[lower];
2111
- const hex6 = lower.match(/^#([0-9a-f]{6})$/);
2112
- if (hex6) return 4278190080 + parseInt(hex6[1], 16) >>> 0;
2113
- const hex3 = lower.match(/^#([0-9a-f]{3})$/);
2114
- if (hex3) {
2115
- const [r, g, b] = hex3[1].split("");
2116
- return 4278190080 + parseInt(`${r}${r}${g}${g}${b}${b}`, 16) >>> 0;
2117
- }
2118
- const hex8 = lower.match(/^#([0-9a-f]{8})$/);
2119
- if (hex8) {
2120
- const rgb = parseInt(hex8[1].slice(0, 6), 16);
2121
- return (parseInt(hex8[1].slice(6, 8), 16) << 24) + rgb >>> 0;
2122
- }
2123
- const rgbMatch = lower.match(/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);
2124
- if (rgbMatch) {
2125
- const [, r, g, b] = rgbMatch;
2126
- return (255 << 24) + (parseInt(r) << 16) + (parseInt(g) << 8) + parseInt(b) >>> 0;
2127
- }
2128
- const rgbaMatch = lower.match(/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)$/);
2129
- if (rgbaMatch) {
2130
- const [, r, g, b, a] = rgbaMatch;
2131
- return (Math.round(parseFloat(a) * 255) << 24) + (parseInt(r) << 16) + (parseInt(g) << 8) + parseInt(b) >>> 0;
2132
- }
2133
- const hslMatch = lower.match(/^hsl\(\s*([\d.]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%\s*\)$/);
2134
- if (hslMatch) {
2135
- const [, h, s, l] = hslMatch;
2136
- const [r, g, b] = hslToRgb(parseFloat(h), parseFloat(s), parseFloat(l));
2137
- return (255 << 24) + (r << 16) + (g << 8) + b >>> 0;
2138
- }
2139
- const hslaMatch = lower.match(/^hsla\(\s*([\d.]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%\s*,\s*([\d.]+)\s*\)$/);
2140
- if (hslaMatch) {
2141
- const [, h, s, l, a] = hslaMatch;
2142
- const [r, g, b] = hslToRgb(parseFloat(h), parseFloat(s), parseFloat(l));
2143
- return (Math.round(parseFloat(a) * 255) << 24) + (r << 16) + (g << 8) + b >>> 0;
2144
- }
2145
- }
2146
- });
2147
- }
2148
- function createFindNodeHandleMock() {
2149
- return vitest.vi.fn((_componentOrHandle) => null);
2150
- }
2151
- function createPlatformColorMock() {
2152
- return vitest.vi.fn((..._names) => "PlatformColor");
2153
- }
2154
- function createDynamicColorIOSMock() {
2155
- return vitest.vi.fn((_config) => "DynamicColorIOS");
2156
- }
2157
- function createSettingsMock() {
2158
- const settings = {};
2159
- return {
2160
- get: vitest.vi.fn((key) => settings[key]),
2161
- set: vitest.vi.fn((obj) => Object.assign(settings, obj)),
2162
- watchKeys: vitest.vi.fn(() => 0),
2163
- clearWatch: vitest.vi.fn()
2164
- };
2165
- }
2166
- function createDeviceInfoMock() {
2167
- return { getConstants: vitest.vi.fn(() => ({ Dimensions: {
2168
- window: {
2169
- width: 390,
2170
- height: 844,
2171
- scale: 3,
2172
- fontScale: 1
2173
- },
2174
- screen: {
2175
- width: 390,
2176
- height: 844,
2177
- scale: 3,
2178
- fontScale: 1
2179
- }
2180
- } })) };
2181
- }
2182
- function createVirtualizedSectionListMock() {
2183
- const VirtualizedSectionList = react.default.forwardRef((props, ref) => {
2184
- const { sections, renderItem, renderSectionHeader, keyExtractor, ...rest } = props;
2185
- const children = [];
2186
- if (sections) sections.forEach((section, sectionIndex) => {
2187
- if (renderSectionHeader) children.push(react.default.createElement(react.default.Fragment, { key: `h-${sectionIndex}` }, renderSectionHeader({ section })));
2188
- if (section.data) section.data.forEach((item, index) => {
2189
- const key = keyExtractor ? keyExtractor(item, index) : `${sectionIndex}-${index}`;
2190
- children.push(react.default.createElement(react.default.Fragment, { key }, renderItem({
2191
- item,
2192
- index,
2193
- section,
2194
- separators: {}
2195
- })));
2196
- });
2197
- });
2198
- return react.default.createElement("VirtualizedSectionList", {
2199
- ...rest,
2200
- ref
2201
- }, ...children);
2202
- });
2203
- VirtualizedSectionList.displayName = "VirtualizedSectionList";
2204
- return VirtualizedSectionList;
2205
- }
2206
- function createTouchableMock() {
2207
- return {
2208
- Mixin: {},
2209
- TOUCH_TARGET_DEBUG: false,
2210
- renderDebugView: vitest.vi.fn(() => null)
2211
- };
2212
- }
2213
- function createUseAnimatedValueMock() {
2214
- return vitest.vi.fn((initialValue) => {
2215
- const ref = react.default.useRef(null);
2216
- if (ref.current == null) ref.current = new AnimatedValue(initialValue);
2217
- return ref.current;
2218
- });
2219
- }
2220
- function createUseAnimatedValueXYMock() {
2221
- return vitest.vi.fn((initialValue) => {
2222
- const ref = react.default.useRef(null);
2223
- if (ref.current == null) ref.current = new AnimatedValueXY(initialValue);
2224
- return ref.current;
2225
- });
2226
- }
2227
- function createUseAnimatedColorMock() {
2228
- return vitest.vi.fn((initialValue) => {
2229
- const ref = react.default.useRef(null);
2230
- if (ref.current == null) ref.current = new AnimatedColor(initialValue);
2231
- return ref.current;
2232
- });
2233
- }
2234
- function buildReactNativeMock(platform = "ios") {
2235
- const mock = {
2236
- View: require_presets.createViewMock(),
2237
- Text: createTextMock(),
2238
- Image: createImageMock(),
2239
- TextInput: require_presets.createTextInputMock(),
2240
- ScrollView: require_presets.createScrollViewMock(),
2241
- FlatList: require_presets.createFlatListMock(),
2242
- SectionList: require_presets.createSectionListMock(),
2243
- Modal: createModalMock(),
2244
- Pressable: require_presets.createPressableMock(),
2245
- TouchableOpacity: require_presets.createTouchableOpacityMock(),
2246
- TouchableHighlight: require_presets.createTouchableHighlightMock(),
2247
- TouchableWithoutFeedback: require_presets.createTouchableWithoutFeedbackMock(),
2248
- TouchableNativeFeedback: createTouchableNativeFeedbackMock(),
2249
- ActivityIndicator: createActivityIndicatorMock(),
2250
- Button: createButtonMock(),
2251
- Switch: createSwitchMock(),
2252
- RefreshControl: createRefreshControlMock(),
2253
- StatusBar: createStatusBarMock(),
2254
- SafeAreaView: createSafeAreaViewMock(),
2255
- KeyboardAvoidingView: createKeyboardAvoidingViewMock(),
2256
- ImageBackground: createImageBackgroundMock(),
2257
- VirtualizedList: require_presets.createVirtualizedListMock(),
2258
- InputAccessoryView: createInputAccessoryViewMock(),
2259
- DrawerLayoutAndroid: createDrawerLayoutAndroidMock(),
2260
- Platform: createPlatformMock(platform),
2261
- Dimensions: createDimensionsMock(),
2262
- StyleSheet: createStyleSheetMock(() => mock.Dimensions.get("window").scale),
2263
- Animated: createAnimatedMock(),
2264
- Alert: createAlertMock(),
2265
- Linking: createLinkingMock(),
2266
- AppState: createAppStateMock(),
2267
- Keyboard: createKeyboardMock(),
2268
- BackHandler: createBackHandlerMock(),
2269
- Vibration: createVibrationMock(),
2270
- PermissionsAndroid: createPermissionsAndroidMock(),
2271
- Appearance: createAppearanceMock(),
2272
- PixelRatio: void 0,
2273
- LayoutAnimation: createLayoutAnimationMock(),
2274
- Clipboard: createClipboardMock(),
2275
- Share: createShareMock(),
2276
- AccessibilityInfo: createAccessibilityInfoMock(),
2277
- InteractionManager: createInteractionManagerMock(),
2278
- PanResponder: createPanResponderMock(),
2279
- ToastAndroid: createToastAndroidMock(),
2280
- ActionSheetIOS: createActionSheetIOSMock(),
2281
- LogBox: createLogBoxMock(),
2282
- Easing: createEasingMock(),
2283
- I18nManager: createI18nManagerMock(),
2284
- DeviceEventEmitter: createDeviceEventEmitterMock(),
2285
- useColorScheme: createUseColorSchemeMock(),
2286
- useWindowDimensions: createUseWindowDimensionsMock(),
2287
- NativeModules: createNativeModulesMock(),
2288
- TurboModuleRegistry: createTurboModuleRegistryMock(),
2289
- UIManager: createUIManagerMock(),
2290
- NativeEventEmitter: createNativeEventEmitterMock(),
2291
- NativeAppEventEmitter: createDeviceEventEmitterMock(),
2292
- EventEmitter: createNativeEventEmitterMock(),
2293
- NativeComponentRegistry: createNativeComponentRegistryMock(),
2294
- requireNativeComponent: createRequireNativeComponentMock(),
2295
- AppRegistry: createAppRegistryMock(),
2296
- VirtualizedSectionList: createVirtualizedSectionListMock(),
2297
- Touchable: createTouchableMock(),
2298
- processColor: createProcessColorMock(),
2299
- findNodeHandle: createFindNodeHandleMock(),
2300
- PlatformColor: createPlatformColorMock(),
2301
- DynamicColorIOS: createDynamicColorIOSMock(),
2302
- Settings: createSettingsMock(),
2303
- DeviceInfo: createDeviceInfoMock(),
2304
- useAnimatedValue: createUseAnimatedValueMock(),
2305
- useAnimatedValueXY: createUseAnimatedValueXYMock(),
2306
- useAnimatedColor: createUseAnimatedColorMock(),
2307
- RootTagContext: react.default.createContext(null),
2308
- ReactNativeVersion: {
2309
- major: 0,
2310
- minor: 76,
2311
- patch: 0
2312
- },
2313
- Systrace: {
2314
- beginEvent: vitest.vi.fn(),
2315
- endEvent: vitest.vi.fn(),
2316
- beginAsyncEvent: vitest.vi.fn(() => 0),
2317
- endAsyncEvent: vitest.vi.fn(),
2318
- counterEvent: vitest.vi.fn(),
2319
- isEnabled: vitest.vi.fn(() => false)
2320
- },
2321
- DevSettings: {
2322
- addMenuItem: vitest.vi.fn(),
2323
- reload: vitest.vi.fn()
2324
- },
2325
- Networking: {
2326
- addListener: vitest.vi.fn(),
2327
- removeListeners: vitest.vi.fn()
2328
- },
2329
- unstable_batchedUpdates: vitest.vi.fn((fn) => fn()),
2330
- registerCallableModule: vitest.vi.fn(),
2331
- codegenNativeCommands: vitest.vi.fn(() => ({})),
2332
- codegenNativeComponent: vitest.vi.fn((name) => name),
2333
- UTFSequence: {
2334
- BOM: "",
2335
- BULLET: "•",
2336
- MIDDOT: "·",
2337
- NBSP: "\xA0"
2338
- },
2339
- ProgressBarAndroid: (() => {
2340
- const C = react.default.forwardRef((props, ref) => react.default.createElement("ProgressBarAndroid", {
2341
- ...props,
2342
- ref
2343
- }));
2344
- C.displayName = "ProgressBarAndroid";
2345
- return C;
2346
- })(),
2347
- PushNotificationIOS: {
2348
- presentLocalNotification: vitest.vi.fn(),
2349
- scheduleLocalNotification: vitest.vi.fn(),
2350
- cancelAllLocalNotifications: vitest.vi.fn(),
2351
- removeAllDeliveredNotifications: vitest.vi.fn(),
2352
- getDeliveredNotifications: vitest.vi.fn(async () => []),
2353
- addEventListener: vitest.vi.fn(() => ({ remove: vitest.vi.fn() })),
2354
- requestPermissions: vitest.vi.fn(async () => ({
2355
- alert: true,
2356
- badge: true,
2357
- sound: true
2358
- })),
2359
- getInitialNotification: vitest.vi.fn(async () => null)
2360
- },
2361
- NativeDialogManagerAndroid: { showAlert: vitest.vi.fn() },
2362
- usePressability: vitest.vi.fn(() => ({})),
2363
- default: void 0
2364
- };
2365
- mock.PixelRatio = createPixelRatioMock(() => mock.Dimensions.get("window"));
2366
- const origSetColorScheme = mock.Appearance.setColorScheme;
2367
- mock.Appearance.setColorScheme = vitest.vi.fn((scheme) => {
2368
- origSetColorScheme(scheme);
2369
- mock.useColorScheme._setScheme(scheme);
2370
- });
2371
- const origDimensionsSet = mock.Dimensions.set;
2372
- mock.Dimensions.set = vitest.vi.fn((dims) => {
2373
- origDimensionsSet(dims);
2374
- if (dims.window) mock.useWindowDimensions._setDimensions(dims.window);
2375
- });
2376
- mock.default = mock;
2377
- return mock;
2378
- }
2379
- //#endregion
2380
- //#region src/cjs-bridge.ts
2381
- /**
2382
- * CJS Bridge — intercepts Node's require('react-native') so CJS consumers
2383
- * (like @testing-library/react-native) resolve to our mocks instead of
2384
- * the real Flow-typed source.
2385
- *
2386
- * Unlike v1, this uses Module._cache injection (no /tmp files) and stores
2387
- * the original _resolveFilename for clean teardown.
2388
- *
2389
- * Safety: This mutates global Module state (Module._resolveFilename and
2390
- * Module._cache). This is necessary because CJS require() has no plugin
2391
- * system — interception is the only option. All mutations are tracked and
2392
- * fully reversed by uninstallCjsBridge() which runs in afterAll().
2393
- * Each vitest worker process gets its own Module state, so there's no
2394
- * cross-test contamination in parallel runs.
2395
- */
2396
- const VIRTUAL_RN_PATH = "\0vitest-native:react-native";
2397
- let originalResolveFilename = null;
2398
- let installed = false;
2399
- let rnMock$1 = null;
2400
- const presetRedirects = /* @__PURE__ */ new Map();
2401
- const presetMocks = /* @__PURE__ */ new Map();
2402
- const leafModulePaths = /* @__PURE__ */ new Set();
2403
- /**
2404
- * The leaf module name a subpath require points at ("pkg/lib/Swipeable" or
2405
- * ".../Platform.ios.js" → "Platform"). Mirrors native/match.mjs.
2406
- */
2407
- function subpathLeafOf(request) {
2408
- const base = request.split("/").pop();
2409
- if (!base) return null;
2410
- return base.split(".")[0] || null;
2411
- }
2412
- /**
2413
- * Wrap a leaf export in Babel-CJS interop shape: the real compiled deep entry
2414
- * exports `{ __esModule: true, default: X }`. A live Proxy keeps
2415
- * direct-property consumers (`require('pkg/Sub').OS`) working too.
2416
- */
2417
- function withDefaultInterop(value) {
2418
- if (value === null || typeof value !== "object" && typeof value !== "function") return {
2419
- __esModule: true,
2420
- default: value
2421
- };
2422
- return new Proxy(value, {
2423
- get: (t, p, r) => p === "default" ? t : p === "__esModule" ? true : Reflect.get(t, p, r),
2424
- has: (t, p) => p === "default" || p === "__esModule" || Reflect.has(t, p)
2425
- });
2426
- }
2427
- /**
2428
- * Get or create a synthetic Module._cache entry for a subpath require whose
2429
- * leaf name matches an export on the mock. Returns its virtual path, or null
2430
- * when the leaf has no matching export (caller falls back to the root mock).
2431
- */
2432
- function leafModulePath(Module, keyPrefix, mock, request) {
2433
- const leaf = subpathLeafOf(request);
2434
- if (!leaf || !Object.prototype.hasOwnProperty.call(mock, leaf)) return null;
2435
- const virtualPath = `${keyPrefix}:${leaf}`;
2436
- if (!Module._cache[virtualPath]) {
2437
- const syntheticModule = new Module(virtualPath);
2438
- syntheticModule.id = virtualPath;
2439
- syntheticModule.filename = virtualPath;
2440
- syntheticModule.loaded = true;
2441
- syntheticModule.exports = withDefaultInterop(mock[leaf]);
2442
- Module._cache[virtualPath] = syntheticModule;
2443
- leafModulePaths.add(virtualPath);
2444
- }
2445
- return virtualPath;
2446
- }
2447
- function installCjsBridge(mockObject) {
2448
- if (installed) return;
2449
- try {
2450
- const Module = require("node:module");
2451
- const syntheticModule = new Module(VIRTUAL_RN_PATH);
2452
- syntheticModule.id = VIRTUAL_RN_PATH;
2453
- syntheticModule.filename = VIRTUAL_RN_PATH;
2454
- syntheticModule.loaded = true;
2455
- syntheticModule.exports = mockObject;
2456
- Module._cache[VIRTUAL_RN_PATH] = syntheticModule;
2457
- rnMock$1 = mockObject;
2458
- originalResolveFilename = Module._resolveFilename;
2459
- Module._resolveFilename = function(request, parent, isMain, options) {
2460
- if (request === "react-native" || request.startsWith("react-native/")) {
2461
- if (request === "react-native/package.json") try {
2462
- return originalResolveFilename.call(this, request, parent, isMain, options);
2463
- } catch {}
2464
- else if (request !== "react-native" && rnMock$1) {
2465
- const leafPath = leafModulePath(Module, VIRTUAL_RN_PATH, rnMock$1, request);
2466
- if (leafPath) return leafPath;
2467
- }
2468
- return VIRTUAL_RN_PATH;
2469
- }
2470
- const exactMatch = presetRedirects.get(request);
2471
- if (exactMatch) return exactMatch;
2472
- const slashIdx = request.indexOf("/", request.startsWith("@") ? request.indexOf("/") + 1 : 0);
2473
- if (slashIdx !== -1) {
2474
- const pkg = request.slice(0, slashIdx);
2475
- const subpathMatch = presetRedirects.get(pkg);
2476
- if (subpathMatch) {
2477
- if (request.endsWith(".json")) try {
2478
- return originalResolveFilename.call(this, request, parent, isMain, options);
2479
- } catch {}
2480
- else {
2481
- const mock = presetMocks.get(pkg);
2482
- const leafPath = mock && leafModulePath(Module, subpathMatch, mock, request);
2483
- if (leafPath) return leafPath;
2484
- }
2485
- return subpathMatch;
2486
- }
2487
- }
2488
- return originalResolveFilename.call(this, request, parent, isMain, options);
2489
- };
2490
- installed = true;
2491
- } catch (e) {
2492
- if (process.env.VITEST_NATIVE_DIAGNOSTICS === "true") console.warn(`[vitest-native] CJS bridge install failed: ${e?.message}`);
2493
- }
2494
- }
2495
- function uninstallCjsBridge() {
2496
- if (!installed) return;
2497
- try {
2498
- const Module = require("node:module");
2499
- if (originalResolveFilename) {
2500
- Module._resolveFilename = originalResolveFilename;
2501
- originalResolveFilename = null;
2502
- }
2503
- delete Module._cache[VIRTUAL_RN_PATH];
2504
- for (const virtualPath of presetRedirects.values()) delete Module._cache[virtualPath];
2505
- presetRedirects.clear();
2506
- presetMocks.clear();
2507
- for (const virtualPath of leafModulePaths) delete Module._cache[virtualPath];
2508
- leafModulePaths.clear();
2509
- rnMock$1 = null;
2510
- installed = false;
2511
- } catch (e) {
2512
- if (process.env.VITEST_NATIVE_DIAGNOSTICS === "true") console.warn(`[vitest-native] CJS bridge uninstall failed: ${e?.message}`);
2513
- }
2514
- }
2515
- function installPresetCjsBridge(moduleName, mockObject) {
2516
- try {
2517
- const Module = require("node:module");
2518
- const virtualPath = `\0vitest-native:preset:${moduleName}`;
2519
- const syntheticModule = new Module(virtualPath);
2520
- syntheticModule.id = virtualPath;
2521
- syntheticModule.filename = virtualPath;
2522
- syntheticModule.loaded = true;
2523
- syntheticModule.exports = mockObject;
2524
- Module._cache[virtualPath] = syntheticModule;
2525
- presetRedirects.set(moduleName, virtualPath);
2526
- presetMocks.set(moduleName, mockObject);
2527
- } catch (e) {
2528
- if (process.env.VITEST_NATIVE_DIAGNOSTICS === "true") console.warn(`[vitest-native] Preset CJS bridge for ${moduleName} failed: ${e?.message}`);
2529
- }
2530
- }
2531
- //#endregion
2532
- //#region src/setup.ts
2533
- /**
2534
- * Auto-injected setup file for vitest-native.
2535
- *
2536
- * This file is added to `test.setupFiles` by the Vite plugin. It:
2537
- * 1. Sets React Native globals (__DEV__, requestAnimationFrame, etc.)
2538
- * 2. Installs the CJS bridge so require('react-native') resolves to mocks
2539
- * 3. Registers vi.mock('react-native') with the full mock object
2540
- * 4. Auto-detects and installs preset mocks
2541
- * 5. Configures @testing-library/react-native host component names
2542
- * 6. Auto-registers RNTL matchers
2543
- * 7. Registers snapshot serializer
2544
- *
2545
- * Options are received via process.env (set by the plugin's config() hook
2546
- * via test.env). This is necessary because the plugin runs in Vite's main
2547
- * process while this setup file runs in Vitest worker processes — globalThis
2548
- * does NOT survive that boundary.
2549
- */
2550
- const platform = process.env.VITEST_NATIVE_PLATFORM || "ios";
2551
- const diagnostics = process.env.VITEST_NATIVE_DIAGNOSTICS === "true";
2552
- const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
2553
- const projectReq = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
2554
- let customMocks = {};
2555
- if (process.env.VITEST_NATIVE_MOCKS) try {
2556
- customMocks = JSON.parse(process.env.VITEST_NATIVE_MOCKS);
2557
- } catch (e) {
2558
- if (diagnostics) console.warn(`[vitest-native] Failed to parse VITEST_NATIVE_MOCKS: ${e?.message}`);
2559
- }
2560
- let explicitPresetNames = null;
2561
- if (process.env.VITEST_NATIVE_PRESET_NAMES) try {
2562
- explicitPresetNames = JSON.parse(process.env.VITEST_NATIVE_PRESET_NAMES);
2563
- } catch (e) {
2564
- if (diagnostics) console.warn(`[vitest-native] Failed to parse VITEST_NATIVE_PRESET_NAMES: ${e?.message}`);
2565
- explicitPresetNames = null;
2566
- }
2567
- const g = globalThis;
2568
- Object.defineProperties(g, {
2569
- __DEV__: {
2570
- configurable: true,
2571
- enumerable: true,
2572
- value: true,
2573
- writable: true
2574
- },
2575
- requestAnimationFrame: {
2576
- configurable: true,
2577
- enumerable: true,
2578
- value: (callback) => setTimeout(() => callback(Date.now()), 0),
2579
- writable: true
2580
- },
2581
- cancelAnimationFrame: {
2582
- configurable: true,
2583
- enumerable: true,
2584
- value: (id) => clearTimeout(id),
2585
- writable: true
2586
- },
2587
- ...typeof g.window === "undefined" ? { window: {
2588
- configurable: true,
2589
- enumerable: true,
2590
- value: g,
2591
- writable: true
2592
- } } : {},
2593
- nativeFabricUIManager: {
2594
- configurable: true,
2595
- enumerable: true,
2596
- value: {},
2597
- writable: true
2598
- }
2599
- });
2600
- if (typeof g.expect === "undefined") Object.defineProperty(g, "expect", {
2601
- configurable: true,
2602
- enumerable: false,
2603
- value: vitest.expect,
2604
- writable: true
2605
- });
2606
- g.IS_REACT_ACT_ENVIRONMENT = true;
2607
- g.IS_REACT_NATIVE_TEST_ENVIRONMENT = true;
2608
- const rnMock = buildReactNativeMock(platform);
2609
- if (Object.keys(customMocks).length > 0) Object.assign(rnMock, customMocks);
2610
- g.__vitest_native_mock = rnMock;
2611
- installCjsBridge(rnMock);
2612
- vitest.vi.mock("react-native", () => rnMock);
2613
- /** Load a preset factory by its export name. */
2614
- function loadPresetFactory(exportName) {
2615
- const factory = require_presets.presets_exports[exportName];
2616
- return typeof factory === "function" ? factory : null;
2617
- }
2618
- function autoDetectPresets() {
2619
- const detected = [];
2620
- const enabled = /* @__PURE__ */ new Set();
2621
- for (const [pkgName, exportName] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) try {
2622
- projectReq.resolve(pkgName);
2623
- if (enabled.has(exportName)) continue;
2624
- const factory = loadPresetFactory(exportName);
2625
- if (factory) {
2626
- detected.push(factory());
2627
- enabled.add(exportName);
2628
- if (diagnostics) console.log(`[vitest-native] Auto-detected ${pkgName} → enabled ${exportName} preset`);
2629
- }
2630
- } catch {}
2631
- return detected;
2632
- }
2633
- function loadExplicitPresets(names) {
2634
- const loaded = [];
2635
- for (const name of names) {
2636
- const factory = loadPresetFactory(name);
2637
- if (factory) loaded.push(factory());
2638
- }
2639
- return loaded;
2640
- }
2641
- const presets = explicitPresetNames ? loadExplicitPresets(explicitPresetNames) : autoDetectPresets();
2642
- g.__vitest_native_preset_mocks = g.__vitest_native_preset_mocks || {};
2643
- for (const preset of presets) for (const [modName, presetModule] of Object.entries(preset.modules)) {
2644
- const presetMock = presetModule.factory();
2645
- installPresetCjsBridge(modName, presetMock);
2646
- g.__vitest_native_preset_mocks[modName] = presetMock;
2647
- if (diagnostics) console.log(`[vitest-native] Registered preset mock: ${modName} (${preset.name})`);
2648
- }
2649
- try {
2650
- const rntl = projectReq("@testing-library/react-native");
2651
- let rntlMajor = 0;
2652
- try {
2653
- const { version } = projectReq("@testing-library/react-native/package.json");
2654
- rntlMajor = Number(String(version).split(".")[0]) || 0;
2655
- } catch {}
2656
- if (rntl?.configure && rntlMajor < 14) rntl.configure({ hostComponentNames: {
2657
- text: "Text",
2658
- textInput: "TextInput",
2659
- switch: "RCTSwitch",
2660
- scrollView: "RCTScrollView",
2661
- modal: "Modal",
2662
- image: "Image",
2663
- button: "Button",
2664
- pressable: "Pressable",
2665
- view: "View",
2666
- activityIndicator: "ActivityIndicator"
2667
- } });
2668
- } catch (e) {
2669
- if (diagnostics) console.log(`[vitest-native] @testing-library/react-native not available: ${e?.message}`);
2670
- }
2671
- try {
2672
- let matchers = null;
2673
- let lastError;
2674
- for (const moduleId of [
2675
- "@testing-library/react-native/matchers",
2676
- "@testing-library/react-native/build/matchers",
2677
- "@testing-library/react-native/dist/matchers"
2678
- ]) try {
2679
- matchers = projectReq(moduleId);
2680
- break;
2681
- } catch (error) {
2682
- lastError = error;
2683
- }
2684
- if (!matchers) throw lastError;
2685
- if (matchers && Object.keys(matchers).length > 0) {
2686
- const matcherFns = {};
2687
- for (const [key, val] of Object.entries(matchers)) if (typeof val === "function" && key !== "__esModule") matcherFns[key] = val;
2688
- if (Object.keys(matcherFns).length > 0) {
2689
- vitest.expect.extend(matcherFns);
2690
- if (diagnostics) console.log(`[vitest-native] Registered ${Object.keys(matcherFns).length} RNTL matchers: ${Object.keys(matcherFns).join(", ")}`);
2691
- }
2692
- }
2693
- } catch (e) {
2694
- if (diagnostics) console.log(`[vitest-native] Could not load RNTL matchers: ${e?.message}`);
2695
- }
2696
- vitest.expect.extend(require_matchers.animatedMatchers);
2697
- if (diagnostics) console.log(`[vitest-native] Registered ${Object.keys(require_matchers.animatedMatchers).length} animated matchers: ${Object.keys(require_matchers.animatedMatchers).join(", ")}`);
2698
- vitest.expect.addSnapshotSerializer(require_serializer.serializer);
2699
- (0, vitest.afterAll)(() => {
2700
- uninstallCjsBridge();
2701
- });
2702
- //#endregion