Update prettier config for the project. (#16303)

* Update prettier config for the project.

* Add prettier to make lint-fix.
This commit is contained in:
Rahul Pratap 2023-06-19 19:09:12 +05:30 committed by GitHub
parent 428616332b
commit c80992b6bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 908 additions and 943 deletions

View File

@ -1,37 +1,37 @@
module.exports = { module.exports = {
"testRunner": "jest", testRunner: 'jest',
"testRegex": "\\.visual\\.js$", testRegex: '\\.visual\\.js$',
"runner-config": "visual-test/config.json", 'runner-config': 'visual-test/config.json',
"devices": { devices: {
"simulator": { simulator: {
"type": "ios.simulator", type: 'ios.simulator',
"device": { device: {
"type": "iPhone 11 Pro" type: 'iPhone 11 Pro',
}
}
}, },
"apps": {
"ios.release": {
"name": "StatusIm",
"type": "ios.app",
"binaryPath": "ios/build/Build/Products/Release-iphonesimulator/StatusIm.app",
"build": "make release-ios"
}, },
"ios.debug": {
"name": "StatusIm",
"type": "ios.app",
"binaryPath": process.env.TEST_BINARY_PATH,
"build": "make run-ios SIMULATOR='iPhone 11 Pro'"
}
}, },
"configurations": { apps: {
"ios.sim.release": { 'ios.release': {
"device": "simulator", name: 'StatusIm',
"app": "ios.release" type: 'ios.app',
binaryPath: 'ios/build/Build/Products/Release-iphonesimulator/StatusIm.app',
build: 'make release-ios',
}, },
"ios.sim.debug": { 'ios.debug': {
"device": "simulator", name: 'StatusIm',
"app": "ios.debug" type: 'ios.app',
} binaryPath: process.env.TEST_BINARY_PATH,
} build: "make run-ios SIMULATOR='iPhone 11 Pro'",
} },
},
configurations: {
'ios.sim.release': {
device: 'simulator',
app: 'ios.release',
},
'ios.sim.debug': {
device: 'simulator',
app: 'ios.debug',
},
},
};

View File

@ -1,4 +1,4 @@
module.exports = { module.exports = {
root: true, root: true,
extends: '@react-native-community', extends: '@react-native-community',
}; };

7
.prettierignore Normal file
View File

@ -0,0 +1,7 @@
*
!*.js
!*/
*.clj-kondo
*.shadow-cljs
modules
result

View File

@ -1,7 +1,9 @@
module.exports = { module.exports = {
bracketSpacing: false, arrowParens: 'always',
bracketSameLine: true, printWidth: 120,
semi: true,
singleQuote: true, singleQuote: true,
tabWidth: 2,
trailingComma: 'all', trailingComma: 'all',
tabWidth: 4, useTabs: false,
}; };

View File

@ -306,14 +306,16 @@ lint: ##@test Run code style checks
@sh scripts/lint-re-frame-in-quo-components.sh && \ @sh scripts/lint-re-frame-in-quo-components.sh && \
clj-kondo --config .clj-kondo/config.edn --cache false --lint src && \ clj-kondo --config .clj-kondo/config.edn --cache false --lint src && \
ALL_CLOJURE_FILES=$(call find_all_clojure_files) && \ ALL_CLOJURE_FILES=$(call find_all_clojure_files) && \
zprint '{:search-config? true}' -sfc $$ALL_CLOJURE_FILES zprint '{:search-config? true}' -sfc $$ALL_CLOJURE_FILES && \
yarn prettier
# NOTE: We run the linter twice because of https://github.com/kkinnear/zprint/issues/271 # NOTE: We run the linter twice because of https://github.com/kkinnear/zprint/issues/271
lint-fix: export TARGET := default lint-fix: export TARGET := default
lint-fix: ##@test Run code style checks and fix issues lint-fix: ##@test Run code style checks and fix issues
ALL_CLOJURE_FILES=$(call find_all_clojure_files) && \ ALL_CLOJURE_FILES=$(call find_all_clojure_files) && \
zprint '{:search-config? true}' -sw $$ALL_CLOJURE_FILES && \ zprint '{:search-config? true}' -sw $$ALL_CLOJURE_FILES && \
zprint '{:search-config? true}' -sw $$ALL_CLOJURE_FILES zprint '{:search-config? true}' -sw $$ALL_CLOJURE_FILES && \
yarn prettier
shadow-server: export TARGET := clojure shadow-server: export TARGET := clojure

View File

@ -1,14 +1,9 @@
module.exports = { module.exports = {
presets: ['module:metro-react-native-babel-preset'],
"presets": [ plugins: ['react-native-reanimated/plugin'],
"module:metro-react-native-babel-preset" env: {
], test: {
"plugins": [ presets: [
"react-native-reanimated/plugin"
],
"env": {
"test": {
"presets": [
'@babel/preset-react', '@babel/preset-react',
[ [
'@babel/preset-env', '@babel/preset-env',
@ -19,6 +14,6 @@ module.exports = {
}, },
], ],
], ],
} },
} },
} };

View File

@ -1,2 +1,2 @@
import "node-libs-react-native/globals"; import 'node-libs-react-native/globals';
import "./result/index.js"; import './result/index.js';

View File

@ -1,6 +1,5 @@
var binary = require('@mapbox/node-pre-gyp'); var binary = require('@mapbox/node-pre-gyp');
var path = require('path'); var path = require('path');
var binding_path = binary.find(path.resolve(path.join(__dirname,'./../../../package.json'))); var binding_path = binary.find(path.resolve(path.join(__dirname, './../../../package.json')));
module.exports = require(binding_path); module.exports = require(binding_path);

View File

@ -10,7 +10,8 @@
"app:compile:android": "shadow-cljs compile android", "app:compile:android": "shadow-cljs compile android",
"app:watch": "shadow-cljs watch android", "app:watch": "shadow-cljs watch android",
"app:packager": "react-native start --host 0.0.0.0 --port 8081", "app:packager": "react-native start --host 0.0.0.0 --port 8081",
"app:android": "react-native run-android" "app:android": "react-native run-android",
"prettier": "prettier --write ."
}, },
"dependencies": { "dependencies": {
"@babel/preset-typescript": "^7.17.12", "@babel/preset-typescript": "^7.17.12",
@ -95,6 +96,7 @@
"jest-image-snapshot": "^5.1.0", "jest-image-snapshot": "^5.1.0",
"nodemon": "^2.0.16", "nodemon": "^2.0.16",
"nyc": "^14.1.1", "nyc": "^14.1.1",
"prettier": "^2.8.8",
"process": "0.11.10", "process": "0.11.10",
"react-test-renderer": "18.0.0", "react-test-renderer": "18.0.0",
"rn-snoopy": "git+https://github.com/status-im/rn-snoopy.git#refs/tags/v2.0.2-status", "rn-snoopy": "git+https://github.com/status-im/rn-snoopy.git#refs/tags/v2.0.2-status",

View File

@ -1,11 +1,11 @@
(function () { (function () {
if (typeof EthereumProvider === "undefined") { if (typeof EthereumProvider === 'undefined') {
var callbackId = 0; var callbackId = 0;
var callbacks = {}; var callbacks = {};
var bridgeSend = function (data) { var bridgeSend = function (data) {
ReactNativeWebView.postMessage(JSON.stringify(data)); ReactNativeWebView.postMessage(JSON.stringify(data));
} };
var history = window.history; var history = window.history;
var pushState = history.pushState; var pushState = history.pushState;
@ -13,7 +13,7 @@
setTimeout(function () { setTimeout(function () {
bridgeSend({ bridgeSend({
type: 'history-state-changed', type: 'history-state-changed',
navState: {url: location.href, title: document.title} navState: { url: location.href, title: document.title },
}); });
}, 100); }, 100);
return pushState.apply(history, arguments); return pushState.apply(history, arguments);
@ -27,7 +27,7 @@
type: 'api-request', type: 'api-request',
permission: permission, permission: permission,
messageId: messageId, messageId: messageId,
params: params params: params,
}); });
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
@ -42,7 +42,7 @@
var regex = new RegExp(callback.regex); var regex = new RegExp(callback.regex);
if (!result) { if (!result) {
if (callback.reject) { if (callback.reject) {
callback.reject(new Error("Cancelled")); callback.reject(new Error('Cancelled'));
} }
} else if (regex.test(result)) { } else if (regex.test(result)) {
if (callback.resolve) { if (callback.resolve) {
@ -56,19 +56,19 @@
} }
function Unauthorized() { function Unauthorized() {
this.name = "Unauthorized"; this.name = 'Unauthorized';
this.id = 4100; this.id = 4100;
this.code = 4100; this.code = 4100;
this.message = "The requested method and/or account has not been authorized by the user."; this.message = 'The requested method and/or account has not been authorized by the user.';
} }
Unauthorized.prototype = Object.create(Error.prototype); Unauthorized.prototype = Object.create(Error.prototype);
function UserRejectedRequest() { function UserRejectedRequest() {
this.name = "UserRejectedRequest"; this.name = 'UserRejectedRequest';
this.id = 4001; this.id = 4001;
this.code = 4001; this.code = 4001;
this.message = "The user rejected the request."; this.message = 'The user rejected the request.';
} }
UserRejectedRequest.prototype = Object.create(Error.prototype); UserRejectedRequest.prototype = Object.create(Error.prototype);
@ -78,38 +78,35 @@
var callback = callbacks[id]; var callback = callbacks[id];
if (callback) { if (callback) {
if (data.type === "api-response") { if (data.type === 'api-response') {
if (data.permission == 'qr-code') { if (data.permission == 'qr-code') {
qrCodeResponse(data, callback); qrCodeResponse(data, callback);
} else if (data.isAllowed) { } else if (data.isAllowed) {
if (data.permission == 'web3') { if (data.permission == 'web3') {
var selectedAddress = data.data[0] var selectedAddress = data.data[0];
window.statusAppcurrentAccountAddress = selectedAddress; window.statusAppcurrentAccountAddress = selectedAddress;
// Set deprecated metamask fields // Set deprecated metamask fields
window.ethereum.selectedAddress = selectedAddress; window.ethereum.selectedAddress = selectedAddress;
window.ethereum.emit("accountsChanged", data.data); window.ethereum.emit('accountsChanged', data.data);
} }
callback.resolve(data.data); callback.resolve(data.data);
} else { } else {
callback.reject(new UserRejectedRequest()); callback.reject(new UserRejectedRequest());
} }
} else if (data.type === "web3-send-async-callback") { } else if (data.type === 'web3-send-async-callback') {
if (callback.beta) { if (callback.beta) {
if (data.error) { if (data.error) {
if (data.error.code == 4100) if (data.error.code == 4100) callback.reject(new Unauthorized());
callback.reject(new Unauthorized()); else callback.reject(data.error);
else
callback.reject(data.error);
} else { } else {
if (window.statusAppDebug) { if (window.statusAppDebug) {
console.log("resolve " + callback.method + " :" + JSON.stringify(data.result.result)); console.log('resolve ' + callback.method + ' :' + JSON.stringify(data.result.result));
} }
callback.resolve(data.result.result); callback.resolve(data.result.result);
} }
} else if (callback.results) { } else if (callback.results) {
callback.results.push(data.error || data.result); callback.results.push(data.error || data.result);
if (callback.results.length == callback.num) if (callback.results.length == callback.num) callback.callback(undefined, callback.results);
callback.callback(undefined, callback.results);
} else { } else {
callback.callback(data.error, data.result); callback.callback(data.error, data.result);
} }
@ -120,46 +117,44 @@
function web3SuccessResponse(payload, result) { function web3SuccessResponse(payload, result) {
return { return {
id: payload.id, id: payload.id,
jsonrpc: "2.0", jsonrpc: '2.0',
method: payload.method, method: payload.method,
result: result result: result,
}; };
} }
function web3ErrorResponse(payload, error) { function web3ErrorResponse(payload, error) {
return { return {
id: payload.id, id: payload.id,
jsonrpc: "2.0", jsonrpc: '2.0',
method: payload.method, method: payload.method,
error: error error: error,
}; };
} }
function getSyncResponse(payload) { function getSyncResponse(payload) {
if (payload.method == "eth_accounts" && (typeof window.statusAppcurrentAccountAddress !== "undefined")) { if (payload.method == 'eth_accounts' && typeof window.statusAppcurrentAccountAddress !== 'undefined') {
return web3SuccessResponse(payload, [window.statusAppcurrentAccountAddress]) return web3SuccessResponse(payload, [window.statusAppcurrentAccountAddress]);
} else if (payload.method == "eth_coinbase" && (typeof window.statusAppcurrentAccountAddress !== "undefined")) { } else if (payload.method == 'eth_coinbase' && typeof window.statusAppcurrentAccountAddress !== 'undefined') {
return web3SuccessResponse(payload, window.statusAppcurrentAccountAddress) return web3SuccessResponse(payload, window.statusAppcurrentAccountAddress);
} else if (payload.method == "net_version") { } else if (payload.method == 'net_version') {
return web3SuccessResponse(payload, window.statusAppNetworkId) return web3SuccessResponse(payload, window.statusAppNetworkId);
} else if (payload.method == "eth_chainId") { } else if (payload.method == 'eth_chainId') {
return web3SuccessResponse(payload, "0x" + Number(window.statusAppNetworkId).toString(16)) return web3SuccessResponse(payload, '0x' + Number(window.statusAppNetworkId).toString(16));
} else if (payload.method == "eth_uninstallFilter") { } else if (payload.method == 'eth_uninstallFilter') {
return web3SuccessResponse(payload, true); return web3SuccessResponse(payload, true);
} else { } else {
return null; return null;
} }
} }
var StatusAPI = function () { var StatusAPI = function () {};
};
StatusAPI.prototype.getContactCode = function () { StatusAPI.prototype.getContactCode = function () {
return sendAPIrequest('contact-code'); return sendAPIrequest('contact-code');
}; };
var EthereumProvider = function () { var EthereumProvider = function () {};
};
EthereumProvider.prototype.isStatus = true; EthereumProvider.prototype.isStatus = true;
EthereumProvider.prototype.status = new StatusAPI(); EthereumProvider.prototype.status = new StatusAPI();
@ -168,7 +163,7 @@
}; };
// Set legacy metamask fields https://docs.metamask.io/guide/ethereum-provider.html#legacy-api // Set legacy metamask fields https://docs.metamask.io/guide/ethereum-provider.html#legacy-api
EthereumProvider.prototype.networkVersion = window.statusAppNetworkId; EthereumProvider.prototype.networkVersion = window.statusAppNetworkId;
EthereumProvider.prototype.chainId = "0x" + Number(window.statusAppNetworkId).toString(16); EthereumProvider.prototype.chainId = '0x' + Number(window.statusAppNetworkId).toString(16);
EthereumProvider.prototype._events = {}; EthereumProvider.prototype._events = {};
@ -177,51 +172,51 @@
this._events[name] = []; this._events[name] = [];
} }
this._events[name].push(listener); this._events[name].push(listener);
} };
EthereumProvider.prototype.removeListener = function (name, listenerToRemove) { EthereumProvider.prototype.removeListener = function (name, listenerToRemove) {
if (!this._events[name]) { if (!this._events[name]) {
return return;
} }
const filterListeners = (listener) => listener !== listenerToRemove; const filterListeners = (listener) => listener !== listenerToRemove;
this._events[name] = this._events[name].filter(filterListeners); this._events[name] = this._events[name].filter(filterListeners);
} };
EthereumProvider.prototype.removeAllListeners = function () { EthereumProvider.prototype.removeAllListeners = function () {
this._events = {}; this._events = {};
} };
EthereumProvider.prototype.emit = function (name, data) { EthereumProvider.prototype.emit = function (name, data) {
if (!this._events[name]) { if (!this._events[name]) {
return return;
} }
this._events[name].forEach(cb => { this._events[name].forEach((cb) => {
// Fixes: https://github.com/status-im/status-mobile/issues/13642 // Fixes: https://github.com/status-im/status-mobile/issues/13642
// Metamask also errors on the same issue, but it's using https://github.com/MetaMask/safe-event-emitter and therefore the dapp still works // Metamask also errors on the same issue, but it's using https://github.com/MetaMask/safe-event-emitter and therefore the dapp still works
try { try {
cb(data) cb(data);
} catch (e) { } catch (e) {
setTimeout((() => { setTimeout(() => {
throw e throw e;
}))
}
}); });
} }
});
};
EthereumProvider.prototype.enable = function () { EthereumProvider.prototype.enable = function () {
if (window.statusAppDebug) { if (window.statusAppDebug) {
console.log("enable"); console.log('enable');
} }
return sendAPIrequest('web3'); return sendAPIrequest('web3');
}; };
EthereumProvider.prototype.scanQRCode = function (regex) { EthereumProvider.prototype.scanQRCode = function (regex) {
return sendAPIrequest('qr-code', {regex: regex}); return sendAPIrequest('qr-code', { regex: regex });
}; };
EthereumProvider.prototype.request = function (requestArguments) { EthereumProvider.prototype.request = function (requestArguments) {
if (window.statusAppDebug) { if (window.statusAppDebug) {
console.log("request: " + JSON.stringify(requestArguments)); console.log('request: ' + JSON.stringify(requestArguments));
} }
if (!requestArguments) { if (!requestArguments) {
return Promise.reject(new Error('Request is not valid.')); return Promise.reject(new Error('Request is not valid.'));
@ -235,11 +230,11 @@
return sendAPIrequest('web3'); return sendAPIrequest('web3');
} }
var syncResponse = getSyncResponse({method: method}); var syncResponse = getSyncResponse({ method: method });
if (syncResponse) { if (syncResponse) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
if (window.statusAppDebug) { if (window.statusAppDebug) {
console.log("resolved sync method: " + method + ", result: " + JSON.stringify(syncResponse.result)); console.log('resolved sync method: ' + method + ', result: ' + JSON.stringify(syncResponse.result));
} }
resolve(syncResponse.result); resolve(syncResponse.result);
}); });
@ -248,15 +243,15 @@
var messageId = callbackId++; var messageId = callbackId++;
var payload = { var payload = {
id: messageId, id: messageId,
jsonrpc: "2.0", jsonrpc: '2.0',
method: method, method: method,
params: requestArguments.params params: requestArguments.params,
}; };
bridgeSend({ bridgeSend({
type: 'web3-send-async-read-only', type: 'web3-send-async-read-only',
messageId: messageId, messageId: messageId,
payload: payload payload: payload,
}); });
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
@ -264,7 +259,7 @@
beta: true, beta: true,
method: method, method: method,
resolve: resolve, resolve: resolve,
reject: reject reject: reject,
}; };
}); });
}; };
@ -277,50 +272,51 @@
//1.ethereum.send(payload: JsonRpcRequest, callback: JsonRpcCallback): void; //1.ethereum.send(payload: JsonRpcRequest, callback: JsonRpcCallback): void;
//2.ethereum.send(payload: JsonRpcRequest): unknown; //2.ethereum.send(payload: JsonRpcRequest): unknown;
if (window.statusAppDebug) { if (window.statusAppDebug) {
console.log("send (legacy), payload: " + JSON.stringify(param1) + ", callback: " + param2); console.log('send (legacy), payload: ' + JSON.stringify(param1) + ', callback: ' + param2);
} }
var syncResponse = getSyncResponse(param1); var syncResponse = getSyncResponse(param1);
if(syncResponse){ if (syncResponse) {
if(param2){ if (param2) {
param2(null, syncResponse); param2(null, syncResponse);
return; return;
}else } else return syncResponse;
return syncResponse;
} }
this.request(param1).then(result => { this.request(param1).then(
(result) => {
if (param2) { if (param2) {
param2(null, web3SuccessResponse(param1, result)); param2(null, web3SuccessResponse(param1, result));
} }
}, reason => { },
(reason) => {
if (window.statusAppDebug) { if (window.statusAppDebug) {
console.log("send (legacy) failed. payload: " + JSON.stringify(param1) + ", reason: " + reason) console.log('send (legacy) failed. payload: ' + JSON.stringify(param1) + ', reason: ' + reason);
} }
if (param2) { if (param2) {
param2(reason, web3ErrorResponse(param1, reason)) param2(reason, web3ErrorResponse(param1, reason));
} }
}); },
);
} else if (typeof param1 == 'string') { } else if (typeof param1 == 'string') {
var method = param1; var method = param1;
var params = param2; var params = param2;
if (window.statusAppDebug) { if (window.statusAppDebug) {
console.log("send (legacy), method: " + method + ", params: " + JSON.stringify(params)); console.log('send (legacy), method: ' + method + ', params: ' + JSON.stringify(params));
} }
return this.request({method: method, params: params}); return this.request({ method: method, params: params });
} else { } else {
throw new Error("unsupported call to send, param1: " + param1 + ", param2: " + param2) throw new Error('unsupported call to send, param1: ' + param1 + ', param2: ' + param2);
}
} }
};
// (DEPRECATED) Support for legacy sendSync method // (DEPRECATED) Support for legacy sendSync method
EthereumProvider.prototype.sendSync = function (payload) { EthereumProvider.prototype.sendSync = function (payload) {
if (window.statusAppDebug) { if (window.statusAppDebug) {
console.log("sendSync (legacy)" + JSON.stringify(payload)); console.log('sendSync (legacy)' + JSON.stringify(payload));
} }
if (payload.method == "eth_uninstallFilter") { if (payload.method == 'eth_uninstallFilter') {
this.sendAsync(payload, function (res, err) { this.sendAsync(payload, function (res, err) {});
})
} }
var syncResponse = getSyncResponse(payload); var syncResponse = getSyncResponse(payload);
if (syncResponse) { if (syncResponse) {
@ -333,7 +329,7 @@
// (DEPRECATED) Support for legacy sendAsync method // (DEPRECATED) Support for legacy sendAsync method
EthereumProvider.prototype.sendAsync = function (payload, callback) { EthereumProvider.prototype.sendAsync = function (payload, callback) {
if (window.statusAppDebug) { if (window.statusAppDebug) {
console.log("sendAsync (legacy)" + JSON.stringify(payload)); console.log('sendAsync (legacy)' + JSON.stringify(payload));
} }
if (!payload) { if (!payload) {
return new Error('Request is not valid.'); return new Error('Request is not valid.');
@ -351,21 +347,21 @@
callbacks[messageId] = { callbacks[messageId] = {
num: payload.length, num: payload.length,
results: [], results: [],
callback: callback callback: callback,
}; };
for (var i in payload) { for (var i in payload) {
bridgeSend({ bridgeSend({
type: 'web3-send-async-read-only', type: 'web3-send-async-read-only',
messageId: messageId, messageId: messageId,
payload: payload[i] payload: payload[i],
}); });
} }
} else { } else {
callbacks[messageId] = {callback: callback}; callbacks[messageId] = { callback: callback };
bridgeSend({ bridgeSend({
type: 'web3-send-async-read-only', type: 'web3-send-async-read-only',
messageId: messageId, messageId: messageId,
payload: payload payload: payload,
}); });
} }
} }

View File

@ -1,15 +1,15 @@
import {useDerivedValue, runOnJS as reaRunOnJS, runOnJS} from "react-native-reanimated"; import { useDerivedValue, runOnJS as reaRunOnJS, runOnJS } from 'react-native-reanimated';
export function useTranslateY(initialTranslationY, bottomSheetDy, panY) { export function useTranslateY(initialTranslationY, bottomSheetDy, panY) {
return useDerivedValue(() => { return useDerivedValue(() => {
return initialTranslationY - (bottomSheetDy.value - panY.value) return initialTranslationY - (bottomSheetDy.value - panY.value);
}) });
} }
export function useBackgroundOpacity(translateY, backgroundHeight, windowHeight, opacity) { export function useBackgroundOpacity(translateY, backgroundHeight, windowHeight, opacity) {
return useDerivedValue(() => { return useDerivedValue(() => {
const calculatedOpacity = ((translateY.value - windowHeight) / -backgroundHeight) * opacity const calculatedOpacity = ((translateY.value - windowHeight) / -backgroundHeight) * opacity;
return Math.max(Math.min(calculatedOpacity, opacity), 0) return Math.max(Math.min(calculatedOpacity, opacity), 0);
}) });
} }

View File

@ -7,24 +7,22 @@ import { useDerivedValue, interpolate } from 'react-native-reanimated';
// 2. remove keys with nil value, else useAnimatedStyle will throw an error // 2. remove keys with nil value, else useAnimatedStyle will throw an error
// https://github.com/status-im/status-mobile/issues/14756 // https://github.com/status-im/status-mobile/issues/14756
export function applyAnimationsToStyle(animations, style) { export function applyAnimationsToStyle(animations, style) {
return function() { return function () {
'worklet' 'worklet';
var animatedStyle = {} var animatedStyle = {};
// Normal Style // Normal Style
for (var key in style) { for (var key in style) {
if (key == "transform") { if (key == 'transform') {
var transforms = style[key]; var transforms = style[key];
var filteredTransforms = [] var filteredTransforms = [];
for (var transform of transforms) { for (var transform of transforms) {
var transformKey = Object.keys(transform)[0]; var transformKey = Object.keys(transform)[0];
var transformValue = transform[transformKey]; var transformValue = transform[transformKey];
if(transformValue !== null) { if (transformValue !== null) {
filteredTransforms.push( filteredTransforms.push({ [transformKey.replace(/-./g, (x) => x[1].toUpperCase())]: transformValue });
{[transformKey.replace(/-./g, x=>x[1].toUpperCase())]: transformValue}
);
} }
} }
@ -32,24 +30,22 @@ export function applyAnimationsToStyle(animations, style) {
} else { } else {
var value = style[key]; var value = style[key];
if (value !== null) { if (value !== null) {
animatedStyle[key.replace(/-./g, x=>x[1].toUpperCase())] = value; animatedStyle[key.replace(/-./g, (x) => x[1].toUpperCase())] = value;
} }
} }
} }
// Animations // Animations
for (var key in animations) { for (var key in animations) {
if (key == "transform") { if (key == 'transform') {
var transforms = animations[key]; var transforms = animations[key];
var animatedTransforms = [] var animatedTransforms = [];
for (var transform of transforms) { for (var transform of transforms) {
var transformKey = Object.keys(transform)[0]; var transformKey = Object.keys(transform)[0];
var transformValue = transform[transformKey].value; var transformValue = transform[transformKey].value;
if (transformValue !== null) { if (transformValue !== null) {
animatedTransforms.push( animatedTransforms.push({ [transformKey.replace(/-./g, (x) => x[1].toUpperCase())]: transformValue });
{[transformKey.replace(/-./g, x=>x[1].toUpperCase())]: transformValue}
);
} }
} }
@ -57,20 +53,18 @@ export function applyAnimationsToStyle(animations, style) {
} else { } else {
var animatedValue = animations[key].value; var animatedValue = animations[key].value;
if (animatedValue !== null) { if (animatedValue !== null) {
animatedStyle[key.replace(/-./g, x=>x[1].toUpperCase())] = animatedValue; animatedStyle[key.replace(/-./g, (x) => x[1].toUpperCase())] = animatedValue;
} }
} }
} }
return animatedStyle; return animatedStyle;
}; };
}; }
export function interpolateValue(sharedValue, inputRange, outputRange, extrapolation) { export function interpolateValue(sharedValue, inputRange, outputRange, extrapolation) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
return interpolate(sharedValue.value, inputRange, outputRange, extrapolation); return interpolate(sharedValue.value, inputRange, outputRange, extrapolation);
} });
);
} }

View File

@ -1,10 +1,8 @@
import { useDerivedValue } from 'react-native-reanimated'; import { useDerivedValue } from 'react-native-reanimated';
export function infoLayout(input, isTop) { export function infoLayout(input, isTop) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet' return isTop ? input.value : -input.value;
return isTop ? input.value : -input.value });
}
);
} }

View File

@ -5,43 +5,39 @@ const slideAnimationDuration = 300;
const easeOut = { const easeOut = {
duration: slideAnimationDuration, duration: slideAnimationDuration,
easing: Easing.bezier(0, 0, 0.58, 1), easing: Easing.bezier(0, 0, 0.58, 1),
} };
// Derived Values // Derived Values
export function dynamicProgressBarWidth(staticProgressBarWidth, progress) { export function dynamicProgressBarWidth(staticProgressBarWidth, progress) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet' return (staticProgressBarWidth * (progress.value || 0)) / 100;
return staticProgressBarWidth * (progress.value || 0) / 100; });
}
);
} }
export function carouselLeftPosition(windowWidth, progress) { export function carouselLeftPosition(windowWidth, progress) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
const progressValue = progress.value; const progressValue = progress.value;
switch (true) { switch (true) {
case (progressValue < 25): case progressValue < 25:
return 0; return 0;
case (progressValue === 25): case progressValue === 25:
return withTiming(-windowWidth, easeOut); return withTiming(-windowWidth, easeOut);
case (progressValue < 50): case progressValue < 50:
return -windowWidth; return -windowWidth;
case (progressValue === 50): case progressValue === 50:
return withTiming(-2 * windowWidth, easeOut); return withTiming(-2 * windowWidth, easeOut);
case (progressValue < 75): case progressValue < 75:
return -2 * windowWidth; return -2 * windowWidth;
case (progressValue === 75): case progressValue === 75:
return withTiming(-3 * windowWidth, easeOut); return withTiming(-3 * windowWidth, easeOut);
case (progressValue < 100): case progressValue < 100:
return -3 * windowWidth; return -3 * windowWidth;
case (progressValue === 100): case progressValue === 100:
return withTiming(-4 * windowWidth, easeOut); return withTiming(-4 * windowWidth, easeOut);
default: default:
return 0; return 0;
} }
}); });
} }

View File

@ -1,10 +1,4 @@
import { import { useAnimatedStyle, useAnimatedSensor, withTiming, interpolate, SensorType } from 'react-native-reanimated';
useAnimatedStyle,
useAnimatedSensor,
withTiming,
interpolate,
SensorType
} from 'react-native-reanimated';
import { Platform } from 'react-native'; import { Platform } from 'react-native';
const PI = Math.PI; const PI = Math.PI;
@ -21,34 +15,31 @@ there is a bug with the pitch and roll calculations provided directly from the s
be done using the quaternions directly. be done using the quaternions directly.
*/ */
export function sensorAnimatedImage(zIndex, offset, stretch) { export function sensorAnimatedImage(zIndex, offset, stretch) {
'worklet' 'worklet';
const rotationSensor = useAnimatedSensor(SensorType.ROTATION, { interval: 30 }) const rotationSensor = useAnimatedSensor(SensorType.ROTATION, { interval: 30 });
return useAnimatedStyle(function () { return useAnimatedStyle(function () {
const { qx, qz, qw, qy, pitch } = rotationSensor.sensor.value; const { qx, qz, qw, qy, pitch } = rotationSensor.sensor.value;
const roll = Math.asin(-2.0 * (qx * qz - qw * qy)) const roll = Math.asin(-2.0 * (qx * qz - qw * qy));
const translateY = withTiming( const translateY = withTiming(
interpolate( interpolate(pitch, Platform.OS === 'ios' ? [-PI, PI] : [PI, -PI], [
pitch, (-offset * 3) / zIndex - offset + (offset - stretch),
Platform.OS === 'ios' ? [-PI, PI] : [PI, -PI], (offset * 3) / zIndex - offset + (offset - stretch),
[(-offset * 3) / zIndex - offset + (offset - stretch), (offset * 3) / zIndex - offset + (offset - stretch)]), ]),
{ duration: 10 } { duration: 10 },
); );
const translateX = withTiming( const translateX = withTiming(
interpolate( interpolate(
roll, roll,
[1, -1], [1, -1],
[(-offset * 2) / zIndex - offset + (offset - stretch), (offset * 2) / zIndex - offset + (offset - stretch)]), [(-offset * 2) / zIndex - offset + (offset - stretch), (offset * 2) / zIndex - offset + (offset - stretch)],
{ duration: 10 } ),
{ duration: 10 },
); );
return { return {
transform: [ transform: [{ translateX }, { translateY }],
{ translateX }, };
{ translateY } });
]
}
})
} }

View File

@ -3,16 +3,14 @@ import { useDerivedValue } from 'react-native-reanimated';
const MAX_SCALE = 1.8; const MAX_SCALE = 1.8;
export function ringScale(scale, subtract) { export function ringScale(scale, subtract) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
const value = scale.value; const value = scale.value;
const maxDelta = MAX_SCALE - 1; const maxDelta = MAX_SCALE - 1;
const maxDeltaDiff = 1 - maxDelta; const maxDeltaDiff = 1 - maxDelta;
const maxVirtualScale = MAX_SCALE + maxDelta; const maxVirtualScale = MAX_SCALE + maxDelta;
const decimals = value - Math.floor(value); const decimals = value - Math.floor(value);
const normalizedValue = value >= maxVirtualScale ? (decimals + ((parseInt(value) - 1) * maxDeltaDiff) + 1) : value; const normalizedValue = value >= maxVirtualScale ? decimals + (parseInt(value) - 1) * maxDeltaDiff + 1 : value;
return (((normalizedValue - subtract) > MAX_SCALE ? normalizedValue - maxDelta : normalizedValue) - subtract); return (normalizedValue - subtract > MAX_SCALE ? normalizedValue - maxDelta : normalizedValue) - subtract;
} });
);
} }

View File

@ -1,7 +1,7 @@
import {useAnimatedScrollHandler} from "react-native-reanimated"; import { useAnimatedScrollHandler } from 'react-native-reanimated';
export function useAnimatedScrollHandlerWorklet(scrollY) { export function useAnimatedScrollHandlerWorklet(scrollY) {
return useAnimatedScrollHandler((event) => { return useAnimatedScrollHandler((event) => {
scrollY.value = event.contentOffset.y; scrollY.value = event.contentOffset.y;
}) });
} }

View File

@ -1,32 +1,34 @@
import { useDerivedValue, withTiming } from 'react-native-reanimated'; import { useDerivedValue, withTiming } from 'react-native-reanimated';
import * as constants from './constants'; import * as constants from './constants';
export function bottomTabIconColor(stackId, selectedStackId, homeStackState, export function bottomTabIconColor(
passThrough, selectedTabColor, defaultColor, stackId,
passThroughColor) { selectedStackId,
return useDerivedValue( homeStackState,
function () { passThrough,
'worklet' selectedTabColor,
defaultColor,
passThroughColor,
) {
return useDerivedValue(function () {
'worklet';
var homeStackStateValue = homeStackState.value; var homeStackStateValue = homeStackState.value;
if (selectedStackId.value == stackId && if (
(homeStackStateValue == constants.OPEN_WITH_ANIMATION || selectedStackId.value == stackId &&
homeStackStateValue == constants.OPEN_WITHOUT_ANIMATION)){ (homeStackStateValue == constants.OPEN_WITH_ANIMATION || homeStackStateValue == constants.OPEN_WITHOUT_ANIMATION)
) {
return selectedTabColor; return selectedTabColor;
} } else if (passThrough.value) {
else if (passThrough.value){
return passThroughColor; return passThroughColor;
} } else {
else {
return defaultColor; return defaultColor;
} }
} });
);
} }
export function bottomTabsHeight(homeStackState, height, extendedHeight) { export function bottomTabsHeight(homeStackState, height, extendedHeight) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (homeStackState.value) { switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION: case constants.OPEN_WITH_ANIMATION:
return withTiming(extendedHeight, constants.LINEAR_EASING); return withTiming(extendedHeight, constants.LINEAR_EASING);
@ -41,6 +43,5 @@ export function bottomTabsHeight(homeStackState, height, extendedHeight) {
return height; return height;
break; break;
} }
} });
)
} }

View File

@ -19,9 +19,9 @@ export const SHELL_ANIMATION_TIME = 200;
export const LINEAR_EASING = { export const LINEAR_EASING = {
duration: SHELL_ANIMATION_TIME, duration: SHELL_ANIMATION_TIME,
easing: Easing.bezier(0, 0, 1, 1), easing: Easing.bezier(0, 0, 1, 1),
} };
export const EASE_OUT_EASING = { export const EASE_OUT_EASING = {
duration: SHELL_ANIMATION_TIME, duration: SHELL_ANIMATION_TIME,
easing: Easing.bezier(0, 0, 0.58, 1), easing: Easing.bezier(0, 0, 0.58, 1),
} };

View File

@ -2,10 +2,9 @@ import { useDerivedValue, withTiming, withSequence, withDelay, Easing } from 're
import * as constants from './constants'; import * as constants from './constants';
// Derived Values // Derived Values
export function screenLeft (screenState, screenWidth, switcherCardLeftPosition) { export function screenLeft(screenState, screenWidth, switcherCardLeftPosition) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (screenState.value) { switch (screenState.value) {
case constants.CLOSE_SCREEN_WITH_SLIDE_ANIMATION: case constants.CLOSE_SCREEN_WITH_SLIDE_ANIMATION:
return withTiming(screenWidth, constants.EASE_OUT_EASING); return withTiming(screenWidth, constants.EASE_OUT_EASING);
@ -16,7 +15,7 @@ export function screenLeft (screenState, screenWidth, switcherCardLeftPosition)
case constants.OPEN_SCREEN_WITHOUT_ANIMATION: case constants.OPEN_SCREEN_WITHOUT_ANIMATION:
// Note - don't use return 0; its not working in ios // Note - don't use return 0; its not working in ios
// https://github.com/software-mansion/react-native-reanimated/issues/3296#issuecomment-1573900172 // https://github.com/software-mansion/react-native-reanimated/issues/3296#issuecomment-1573900172
return withSequence(withTiming(-1, {duration: 0}), withTiming(0, {duration: 0})); return withSequence(withTiming(-1, { duration: 0 }), withTiming(0, { duration: 0 }));
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION: case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
return withTiming(switcherCardLeftPosition, constants.EASE_OUT_EASING); return withTiming(switcherCardLeftPosition, constants.EASE_OUT_EASING);
case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION: case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION:
@ -27,10 +26,9 @@ export function screenLeft (screenState, screenWidth, switcherCardLeftPosition)
}); });
} }
export function screenTop (screenState, switcherCardTopPosition) { export function screenTop(screenState, switcherCardTopPosition) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (screenState.value) { switch (screenState.value) {
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION: case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
return withTiming(switcherCardTopPosition, constants.EASE_OUT_EASING); return withTiming(switcherCardTopPosition, constants.EASE_OUT_EASING);
@ -42,44 +40,47 @@ export function screenTop (screenState, switcherCardTopPosition) {
}); });
} }
export function screenWidth (screenState, screenWidth, switcherCardSize) { export function screenWidth(screenState, screenWidth, switcherCardSize) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (screenState.value) { switch (screenState.value) {
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION: case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
return withTiming(switcherCardSize, constants.EASE_OUT_EASING); return withTiming(switcherCardSize, constants.EASE_OUT_EASING);
case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION: case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION:
return withSequence(withTiming(switcherCardSize, {duration: 0}), withTiming(screenWidth, constants.EASE_OUT_EASING)); return withSequence(
withTiming(switcherCardSize, { duration: 0 }),
withTiming(screenWidth, constants.EASE_OUT_EASING),
);
default: default:
return screenWidth; return screenWidth;
} }
}); });
} }
export function screenHeight (screenState, screenHeight, switcherCardSize) { export function screenHeight(screenState, screenHeight, switcherCardSize) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (screenState.value) { switch (screenState.value) {
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION: case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
return withTiming(switcherCardSize, constants.EASE_OUT_EASING); return withTiming(switcherCardSize, constants.EASE_OUT_EASING);
case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION: case constants.OPEN_SCREEN_WITH_SHELL_ANIMATION:
return withSequence(withTiming(switcherCardSize, {duration: 0}), withTiming(screenHeight, constants.EASE_OUT_EASING)); return withSequence(
withTiming(switcherCardSize, { duration: 0 }),
withTiming(screenHeight, constants.EASE_OUT_EASING),
);
default: default:
return screenHeight; return screenHeight;
} }
}); });
} }
export function screenZIndex (screenState) { export function screenZIndex(screenState) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (screenState.value) { switch (screenState.value) {
case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION: case constants.CLOSE_SCREEN_WITH_SHELL_ANIMATION:
case constants.CLOSE_SCREEN_WITH_SLIDE_ANIMATION: case constants.CLOSE_SCREEN_WITH_SLIDE_ANIMATION:
return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(-1, {duration: 0})); return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(-1, { duration: 0 }));
case constants.CLOSE_SCREEN_WITHOUT_ANIMATION: case constants.CLOSE_SCREEN_WITHOUT_ANIMATION:
return -1; return -1;
default: default:

View File

@ -3,28 +3,23 @@ import * as constants from './constants';
// Derived values for each stack (communities, chat, wallet, browser) // Derived values for each stack (communities, chat, wallet, browser)
export function stackOpacity(stackId, selectedStackId) { export function stackOpacity(stackId, selectedStackId) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
return selectedStackId.value == stackId ? 1 : 0; return selectedStackId.value == stackId ? 1 : 0;
} });
);
} }
export function stackZIndex(stackId, selectedStackId) { export function stackZIndex(stackId, selectedStackId) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
return selectedStackId.value == stackId ? 10 : 9; return selectedStackId.value == stackId ? 10 : 9;
} });
);
} }
// Derived values for home stack (container) // Derived values for home stack (container)
export function homeStackOpacity(homeStackState) { export function homeStackOpacity(homeStackState) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (homeStackState.value) { switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION: case constants.OPEN_WITH_ANIMATION:
return withTiming(1, constants.LINEAR_EASING); return withTiming(1, constants.LINEAR_EASING);
@ -35,14 +30,12 @@ export function homeStackOpacity(homeStackState) {
case constants.CLOSE_WITHOUT_ANIMATION: case constants.CLOSE_WITHOUT_ANIMATION:
return 0; return 0;
} }
} });
);
} }
export function homeStackTop(homeStackState, top) { export function homeStackTop(homeStackState, top) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (homeStackState.value) { switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION: case constants.OPEN_WITH_ANIMATION:
return withTiming(0, constants.LINEAR_EASING); return withTiming(0, constants.LINEAR_EASING);
@ -53,19 +46,17 @@ export function homeStackTop(homeStackState, top) {
case constants.CLOSE_WITHOUT_ANIMATION: case constants.CLOSE_WITHOUT_ANIMATION:
return top; return top;
} }
} });
);
} }
export function homeStackLeft(selectedStackId, animateHomeStackLeft, homeStackState, left) { export function homeStackLeft(selectedStackId, animateHomeStackLeft, homeStackState, left) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
if (animateHomeStackLeft.value) { if (animateHomeStackLeft.value) {
var leftValue = left[selectedStackId.value]; var leftValue = left[selectedStackId.value];
switch (homeStackState.value) { switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION: case constants.OPEN_WITH_ANIMATION:
return withSequence(withTiming(leftValue, {duration: 0}), withTiming(0, constants.LINEAR_EASING)) return withSequence(withTiming(leftValue, { duration: 0 }), withTiming(0, constants.LINEAR_EASING));
case constants.CLOSE_WITH_ANIMATION: case constants.CLOSE_WITH_ANIMATION:
return withTiming(leftValue, constants.LINEAR_EASING); return withTiming(leftValue, constants.LINEAR_EASING);
case constants.OPEN_WITHOUT_ANIMATION: case constants.OPEN_WITHOUT_ANIMATION:
@ -76,25 +67,23 @@ export function homeStackLeft(selectedStackId, animateHomeStackLeft, homeStackSt
} else { } else {
return 0; return 0;
} }
} });
);
} }
export function homeStackPointer(homeStackState) { export function homeStackPointer(homeStackState) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
var homeStackStateValue = homeStackState.value; var homeStackStateValue = homeStackState.value;
return (homeStackStateValue == constants.OPEN_WITH_ANIMATION || return homeStackStateValue == constants.OPEN_WITH_ANIMATION ||
homeStackStateValue == constants.OPEN_WITHOUT_ANIMATION) ? "auto" : "none"; homeStackStateValue == constants.OPEN_WITHOUT_ANIMATION
} ? 'auto'
); : 'none';
});
} }
export function homeStackScale(homeStackState, minimizeScale) { export function homeStackScale(homeStackState, minimizeScale) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (homeStackState.value) { switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION: case constants.OPEN_WITH_ANIMATION:
return withTiming(1, constants.LINEAR_EASING); return withTiming(1, constants.LINEAR_EASING);
@ -105,24 +94,20 @@ export function homeStackScale(homeStackState, minimizeScale) {
case constants.CLOSE_WITHOUT_ANIMATION: case constants.CLOSE_WITHOUT_ANIMATION:
return minimizeScale; return minimizeScale;
} }
} });
);
} }
export function homeStackBorderRadius(homeStackState) { export function homeStackBorderRadius(homeStackState) {
return useDerivedValue( return useDerivedValue(function () {
function () { 'worklet';
'worklet'
switch (homeStackState.value) { switch (homeStackState.value) {
case constants.OPEN_WITH_ANIMATION: case constants.OPEN_WITH_ANIMATION:
return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(0, {duration: 0})); return withDelay(constants.SHELL_ANIMATION_TIME, withTiming(0, { duration: 0 }));
case constants.CLOSE_WITH_ANIMATION: case constants.CLOSE_WITH_ANIMATION:
case constants.CLOSE_WITHOUT_ANIMATION: case constants.CLOSE_WITHOUT_ANIMATION:
return 20; return 20;
case constants.OPEN_WITHOUT_ANIMATION: case constants.OPEN_WITHOUT_ANIMATION:
return 0; return 0;
} }
} });
);
} }

View File

@ -1,10 +1,16 @@
const waitToNavigate = duration => new Promise(resolve => setTimeout(() => resolve(), duration)); const waitToNavigate = (duration) => new Promise((resolve) => setTimeout(() => resolve(), duration));
const SUPER_SECRET_PASSWORD = 'password' const SUPER_SECRET_PASSWORD = 'password';
const loginToHomePage = async () => { const loginToHomePage = async () => {
if (device.getPlatform() === 'ios') { if (device.getPlatform() === 'ios') {
await device.setStatusBar({ time: '12:34', dataNetwork: 'wifi', wifiBars: '3', batteryState: 'charging', batteryLevel: '100' }); await device.setStatusBar({
time: '12:34',
dataNetwork: 'wifi',
wifiBars: '3',
batteryState: 'charging',
batteryLevel: '100',
});
} }
await device.reloadReactNative(); await device.reloadReactNative();
await element(by.id('terms-of-service')).tap(); await element(by.id('terms-of-service')).tap();
@ -21,18 +27,17 @@ const loginToHomePage = async () => {
await element(by.id('confirm-password-placeholder')).typeText(SUPER_SECRET_PASSWORD); await element(by.id('confirm-password-placeholder')).typeText(SUPER_SECRET_PASSWORD);
await element(by.text('Next')).tap(); await element(by.text('Next')).tap();
await waitToNavigate(200); await waitToNavigate(200);
await element(by.id("browser-stack")).tap(); await element(by.id('browser-stack')).tap();
await waitToNavigate(400); await waitToNavigate(400);
await element(by.text("Quo2.0 Preview")).tap(); await element(by.text('Quo2.0 Preview')).tap();
await waitToNavigate(400); await waitToNavigate(400);
} };
describe('Default Renders', () => { describe('Default Renders', () => {
beforeAll(async () => loginToHomePage()) beforeAll(async () => loginToHomePage());
beforeEach(async () => { beforeEach(async () => {});
});
afterEach(async () => { afterEach(async () => {
await element(by.id("back-button")).tap(); await element(by.id('back-button')).tap();
await waitToNavigate(200); await waitToNavigate(200);
}); });
@ -40,5 +45,5 @@ describe('Default Renders', () => {
await element(by.id(`quo2-:button`)).tap(); await element(by.id(`quo2-:button`)).tap();
await waitToNavigate(200); await waitToNavigate(200);
const res = await jestExpect(`button`).toMatchImageSnapshot(); const res = await jestExpect(`button`).toMatchImageSnapshot();
}) });
}); });

View File

@ -1,6 +1,6 @@
var Mocks = require('../target/mocks/mocks.js'); var Mocks = require('../target/mocks/mocks.js');
var Module = require('module'); var Module = require('module');
process.env.TZ = 'Etc/UTC' process.env.TZ = 'Etc/UTC';
const originalLoader = Module._load; const originalLoader = Module._load;
@ -18,13 +18,11 @@ Module._load = function hookedLoader(request, parent, isMain) {
var originalRequire = Module.prototype.require; var originalRequire = Module.prototype.require;
Module.prototype.require = function(req){ Module.prototype.require = function (req) {
module = Mocks.mocks(req); module = Mocks.mocks(req);
if (module == null) { if (module == null) {
return originalRequire.apply(this, arguments); return originalRequire.apply(this, arguments);
} } else {
else {
return module; return module;
} }
}; };

View File

@ -1,9 +1,6 @@
module.exports = { module.exports = {
preset: 'react-native', preset: 'react-native',
setupFilesAfterEnv: [ setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect', '../test/jest/jestSetup.js'],
'@testing-library/jest-native/extend-expect',
'../test/jest/jestSetup.js',
],
setupFiles: [], setupFiles: [],
testPathIgnorePatterns: [], testPathIgnorePatterns: [],
moduleNameMapper: { moduleNameMapper: {

View File

@ -1,5 +1,5 @@
const WebSocket = require('ws'); const WebSocket = require('ws');
const {NativeModules} = require('react-native'); const { NativeModules } = require('react-native');
require('@react-native-async-storage/async-storage/jest/async-storage-mock'); require('@react-native-async-storage/async-storage/jest/async-storage-mock');
require('react-native-gesture-handler/jestSetup'); require('react-native-gesture-handler/jestSetup');
@ -8,8 +8,8 @@ require('react-native-reanimated/lib/reanimated2/jestUtils').setUpTests();
jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage); jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage);
jest.mock('react-native-navigation', () => ({ jest.mock('react-native-navigation', () => ({
getNavigationConstants: () => ({constants: []}), getNavigationConstants: () => ({ constants: [] }),
Navigation: {constants: async () => {}}, Navigation: { constants: async () => {} },
})); }));
jest.mock('react-native-background-timer', () => ({})); jest.mock('react-native-background-timer', () => ({}));
@ -25,9 +25,7 @@ jest.mock('react-native-languages', () => ({
}, },
})); }));
jest.mock('react-native-permissions', () => jest.mock('react-native-permissions', () => require('react-native-permissions/mock'));
require('react-native-permissions/mock'),
);
jest.mock('@react-native-community/audio-toolkit', () => ({ jest.mock('@react-native-community/audio-toolkit', () => ({
Recorder: jest.fn().mockImplementation(() => ({ Recorder: jest.fn().mockImplementation(() => ({
@ -61,21 +59,21 @@ jest.mock('@react-native-community/audio-toolkit', () => ({
PlaybackCategories: { PlaybackCategories: {
Playback: 1, Playback: 1,
Ambient: 2, Ambient: 2,
SoloAmbient: 3 SoloAmbient: 3,
}, },
})); }));
jest.mock("i18n-js", () => ({ jest.mock('i18n-js', () => ({
...jest.requireActual("i18n-js"), ...jest.requireActual('i18n-js'),
t: (label) => `tx:${label}` t: (label) => `tx:${label}`,
})); }));
jest.mock("react-native-blob-util", () => ({ jest.mock('react-native-blob-util', () => ({
default: { default: {
config: jest.fn().mockReturnValue({ config: jest.fn().mockReturnValue({
fetch: jest.fn() fetch: jest.fn(),
}) }),
} },
})); }));
NativeModules.ReactLocalization = { NativeModules.ReactLocalization = {

View File

@ -1,10 +1,6 @@
const { const { DetoxCircusEnvironment, SpecReporter, WorkerAssignReporter } = require('detox/runners/jest-circus');
DetoxCircusEnvironment,
SpecReporter,
WorkerAssignReporter,
} = require('detox/runners/jest-circus');
class CustomDetoxEnvironment extends DetoxCircusEnvironment { class CustomDetoxEnvironment extends DetoxCircusEnvironment {
constructor(config, context) { constructor(config, context) {
super(config, context); super(config, context);
@ -18,6 +14,6 @@ const {
WorkerAssignReporter, WorkerAssignReporter,
}); });
} }
} }
module.exports = CustomDetoxEnvironment; module.exports = CustomDetoxEnvironment;

View File

@ -34,7 +34,7 @@ function resolveSelectedConfiguration() {
// TODO eventually, this should be made available by Detox more explicitly // TODO eventually, this should be made available by Detox more explicitly
function isAndroidConfig(config) { function isAndroidConfig(config) {
return [config.type, process.env.DETOX_CONFIGURATION, config.device].some(s => `${s}`.includes('android')); return [config.type, process.env.DETOX_CONFIGURATION, config.device].some((s) => `${s}`.includes('android'));
} }
module.exports = globalSetup; module.exports = globalSetup;

View File

@ -4,12 +4,12 @@ const path = require('path');
const kebabCase = require('lodash/kebabCase'); const kebabCase = require('lodash/kebabCase');
const expect = require('expect'); const expect = require('expect');
const toMatchImage = configureToMatchImageSnapshot({ const toMatchImage = configureToMatchImageSnapshot({
comparisonMethod: 'ssim', failureThreshold: 0.002, failureThresholdType: 'percent' comparisonMethod: 'ssim',
failureThreshold: 0.002,
failureThresholdType: 'percent',
}); });
expect.extend({ toMatchImage }); expect.extend({ toMatchImage });
expect.extend({ expect.extend({
@ -23,18 +23,17 @@ expect.extend({
const { testPath, currentTestName } = this; const { testPath, currentTestName } = this;
const customSnapshotsDir = path.join(path.dirname(testPath), SNAPSHOTS_DIR); const customSnapshotsDir = path.join(path.dirname(testPath), SNAPSHOTS_DIR);
const customSnapshotIdentifier = kebabCase(`${path.basename(testPath)}-${currentTestName}-${screenName}`) const customSnapshotIdentifier = kebabCase(`${path.basename(testPath)}-${currentTestName}-${screenName}`);
const tempPath = await device.takeScreenshot(screenName); const tempPath = await device.takeScreenshot(screenName);
const image = fs.readFileSync(tempPath); const image = fs.readFileSync(tempPath);
expect(image).toMatchImage({ customSnapshotIdentifier, customSnapshotsDir }); expect(image).toMatchImage({ customSnapshotIdentifier, customSnapshotsDir });
return { pass: true } return { pass: true };
}, },
}); });
global.jestExpect = expect global.jestExpect = expect;
beforeAll(async () => { beforeAll(async () => {
await device.launchApp(); await device.launchApp();

View File

@ -8664,6 +8664,11 @@ prepend-http@^2.0.0:
resolved "https://registry.yarnpkg.com/prepend-http/-/prepend-http-2.0.0.tgz#e92434bfa5ea8c19f41cdfd401d741a3c819d897" resolved "https://registry.yarnpkg.com/prepend-http/-/prepend-http-2.0.0.tgz#e92434bfa5ea8c19f41cdfd401d741a3c819d897"
integrity sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc= integrity sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=
prettier@^2.8.8:
version "2.8.8"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.8.tgz#e8c5d7e98a4305ffe3de2e1fc4aca1a71c28b1da"
integrity sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==
pretty-format@^25.5.0: pretty-format@^25.5.0:
version "25.5.0" version "25.5.0"
resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-25.5.0.tgz#7873c1d774f682c34b8d48b6743a2bf2ac55791a" resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-25.5.0.tgz#7873c1d774f682c34b8d48b6743a2bf2ac55791a"