├── .watchmanconfig
├── app
├── features
│ ├── auth
│ │ ├── api.js
│ │ ├── components
│ │ │ ├── PasswordInput.js
│ │ │ ├── EmailInput.js
│ │ │ └── TextInput.js
│ │ ├── routes.js
│ │ ├── index.js
│ │ ├── screens
│ │ │ ├── SignupScreen.js
│ │ │ └── LoginScreen.js
│ │ ├── redux.js
│ │ └── sagas.js
│ ├── quiz
│ │ ├── constants.js
│ │ ├── index.js
│ │ ├── utils.js
│ │ ├── components
│ │ │ ├── QuizLoading.js
│ │ │ ├── QuizResult.js
│ │ │ └── Question.js
│ │ ├── screens
│ │ │ └── QuizScreen.js
│ │ ├── redux.js
│ │ └── sagas.js
│ ├── home
│ │ ├── index.js
│ │ └── routes.js
│ ├── main
│ │ ├── index.js
│ │ ├── screens
│ │ │ └── LoadingScreen.js
│ │ └── routes.js
│ ├── dashboard
│ │ ├── index.js
│ │ ├── components
│ │ │ └── StartButton.js
│ │ └── screens
│ │ │ └── DashboardScreen.js
│ └── user
│ │ ├── api.js
│ │ ├── index.js
│ │ ├── components
│ │ └── ProfileImage.js
│ │ ├── screens
│ │ └── ProfileScreen.js
│ │ ├── redux.js
│ │ └── sagas.js
├── core
│ ├── assets
│ │ ├── check.png
│ │ ├── error.png
│ │ ├── user.png
│ │ ├── check@2x.png
│ │ ├── check@3x.png
│ │ ├── error@2x.png
│ │ ├── error@3x.png
│ │ ├── user@2x.png
│ │ ├── user@3x.png
│ │ └── index.js
│ ├── store
│ │ ├── ActionTypes.js
│ │ ├── createRootReducer.js
│ │ ├── KeyValueStorage.js
│ │ ├── createRootSaga.js
│ │ └── index.js
│ ├── constants
│ │ └── Theme.js
│ ├── components
│ │ ├── Spacer.js
│ │ ├── ImageButton.js
│ │ ├── ErrorMessage.js
│ │ ├── HeaderButton.js
│ │ ├── Container.js
│ │ ├── Text.js
│ │ ├── PrimaryButton.js
│ │ └── SecondaryButton.js
│ ├── services
│ │ ├── createApiMonitor.js
│ │ ├── questionsApi.js
│ │ ├── Navigation.js
│ │ └── userApi.js
│ └── utils.js
└── App.js
├── .gitattributes
├── backend
├── nodemon.json
├── package.json
├── src
│ ├── dbFileUtils.js
│ └── index.js
└── api.rest
├── app.json
├── jsconfig.json
├── prettier.config.js
├── babel.config.js
├── android
├── .settings
│ └── org.eclipse.buildship.core.prefs
├── app
│ ├── src
│ │ ├── main
│ │ │ ├── res
│ │ │ │ ├── values
│ │ │ │ │ ├── strings.xml
│ │ │ │ │ └── styles.xml
│ │ │ │ ├── mipmap-hdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-mdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xhdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xxhdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ └── mipmap-xxxhdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ ├── java
│ │ │ │ └── com
│ │ │ │ │ └── awesomeproject
│ │ │ │ │ ├── MainActivity.java
│ │ │ │ │ └── MainApplication.java
│ │ │ └── AndroidManifest.xml
│ │ └── debug
│ │ │ └── AndroidManifest.xml
│ ├── build_defs.bzl
│ ├── proguard-rules.pro
│ ├── BUCK
│ └── build.gradle
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── keystores
│ ├── debug.keystore.properties
│ └── BUCK
├── settings.gradle
├── gradle.properties
├── build.gradle
├── gradlew.bat
└── gradlew
├── design
└── ui.sketch
├── ios
├── AwesomeProject
│ ├── Images.xcassets
│ │ ├── Contents.json
│ │ └── AppIcon.appiconset
│ │ │ └── Contents.json
│ ├── AppDelegate.h
│ ├── main.m
│ ├── AppDelegate.m
│ ├── Info.plist
│ └── Base.lproj
│ │ └── LaunchScreen.xib
├── AwesomeProjectTests
│ ├── Info.plist
│ └── AwesomeProjectTests.m
├── AwesomeProject-tvOSTests
│ └── Info.plist
├── AwesomeProject-tvOS
│ └── Info.plist
└── AwesomeProject.xcodeproj
│ └── xcshareddata
│ └── xcschemes
│ ├── AwesomeProject.xcscheme
│ └── AwesomeProject-tvOS.xcscheme
├── .buckconfig
├── docs
└── rn-feature-oriented-app-architecture-example.gif
├── index.js
├── __tests__
└── App-test.js
├── metro.config.js
├── .eslintrc.js
├── .gitignore
├── package.json
├── .flowconfig
├── scripts
└── link_folders.js
└── README.md
/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/app/features/auth/api.js:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 |
--------------------------------------------------------------------------------
/backend/nodemon.json:
--------------------------------------------------------------------------------
1 | {
2 | "ignore": ["db.json"]
3 | }
4 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "AwesomeProject",
3 | "displayName": "AwesomeProject"
4 | }
--------------------------------------------------------------------------------
/jsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": "./"
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/prettier.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | trailingComma: 'es5',
3 | singleQuote: true,
4 | };
5 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | };
4 |
--------------------------------------------------------------------------------
/android/.settings/org.eclipse.buildship.core.prefs:
--------------------------------------------------------------------------------
1 | connection.project.dir=
2 | eclipse.preferences.version=1
3 |
--------------------------------------------------------------------------------
/design/ui.sketch:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/design/ui.sketch
--------------------------------------------------------------------------------
/android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AwesomeProject
3 |
4 |
--------------------------------------------------------------------------------
/app/core/assets/check.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/app/core/assets/check.png
--------------------------------------------------------------------------------
/app/core/assets/error.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/app/core/assets/error.png
--------------------------------------------------------------------------------
/app/core/assets/user.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/app/core/assets/user.png
--------------------------------------------------------------------------------
/app/features/quiz/constants.js:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line import/prefer-default-export
2 | export const QUIZ_QUESTIONS_COUNT = 10;
3 |
--------------------------------------------------------------------------------
/ios/AwesomeProject/Images.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/app/core/assets/check@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/app/core/assets/check@2x.png
--------------------------------------------------------------------------------
/app/core/assets/check@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/app/core/assets/check@3x.png
--------------------------------------------------------------------------------
/app/core/assets/error@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/app/core/assets/error@2x.png
--------------------------------------------------------------------------------
/app/core/assets/error@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/app/core/assets/error@3x.png
--------------------------------------------------------------------------------
/app/core/assets/user@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/app/core/assets/user@2x.png
--------------------------------------------------------------------------------
/app/core/assets/user@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/app/core/assets/user@3x.png
--------------------------------------------------------------------------------
/.buckconfig:
--------------------------------------------------------------------------------
1 |
2 | [android]
3 | target = Google Inc.:Google APIs:23
4 |
5 | [maven_repositories]
6 | central = https://repo1.maven.org/maven2
7 |
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/android/keystores/debug.keystore.properties:
--------------------------------------------------------------------------------
1 | key.store=debug.keystore
2 | key.alias=androiddebugkey
3 | key.store.password=android
4 | key.alias.password=android
5 |
--------------------------------------------------------------------------------
/app/core/store/ActionTypes.js:
--------------------------------------------------------------------------------
1 | export default {
2 | SAVE_DATA: 'STORE/GLOBAL/SAVE_DATA',
3 | RESET: 'STORE/GLOBAL/RESET',
4 | LOGOUT: 'STORE/GLOBAL/LOGOUT',
5 | };
6 |
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/docs/rn-feature-oriented-app-architecture-example.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/docs/rn-feature-oriented-app-architecture-example.gif
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zubko/rn-feature-oriented-app-architecture-example/HEAD/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/android/keystores/BUCK:
--------------------------------------------------------------------------------
1 | keystore(
2 | name = "debug",
3 | properties = "debug.keystore.properties",
4 | store = "debug.keystore",
5 | visibility = [
6 | "PUBLIC",
7 | ],
8 | )
9 |
--------------------------------------------------------------------------------
/app/features/home/index.js:
--------------------------------------------------------------------------------
1 | import Navigator from './routes';
2 |
3 | export const key = 'home';
4 |
5 | export const screens = {
6 | main: Navigator,
7 | };
8 |
9 | export default { screens, key };
10 |
--------------------------------------------------------------------------------
/app/features/main/index.js:
--------------------------------------------------------------------------------
1 | import Navigator from './routes';
2 |
3 | export const key = 'main';
4 |
5 | export const screens = {
6 | main: Navigator,
7 | };
8 |
9 | export default { key, screens };
10 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @format
3 | */
4 |
5 | import { AppRegistry } from 'react-native';
6 | import App from './app/App';
7 | import { name as appName } from './app.json';
8 |
9 | AppRegistry.registerComponent(appName, () => App);
10 |
--------------------------------------------------------------------------------
/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/app/features/dashboard/index.js:
--------------------------------------------------------------------------------
1 | import DashboardScreen from './screens/DashboardScreen';
2 |
3 | export const key = 'dashboard';
4 |
5 | export const screens = {
6 | main: DashboardScreen,
7 | };
8 |
9 | export default {
10 | key,
11 | screens,
12 | };
13 |
--------------------------------------------------------------------------------
/app/features/user/api.js:
--------------------------------------------------------------------------------
1 | import { get, patch } from '@app/core/services/userApi';
2 |
3 | export async function getUser(api, id) {
4 | return get(api, 'users', id);
5 | }
6 |
7 | export async function patchUser(api, id, data) {
8 | return patch(api, 'users', id, data);
9 | }
10 |
--------------------------------------------------------------------------------
/app/features/auth/components/PasswordInput.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TextInput from './TextInput';
3 |
4 | const Input = props => (
5 |
11 | );
12 |
13 | export default Input;
14 |
--------------------------------------------------------------------------------
/app/features/auth/components/EmailInput.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import TextInput from './TextInput';
3 |
4 | const Input = props => (
5 |
11 | );
12 |
13 | export default Input;
14 |
--------------------------------------------------------------------------------
/__tests__/App-test.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @format
3 | */
4 |
5 | import 'react-native';
6 | import React from 'react';
7 | import App from '../App';
8 |
9 | // Note: test renderer must be required after react-native.
10 | import renderer from 'react-test-renderer';
11 |
12 | it('renders correctly', () => {
13 | renderer.create();
14 | });
15 |
--------------------------------------------------------------------------------
/app/features/quiz/index.js:
--------------------------------------------------------------------------------
1 | import QuizScreen from './screens/QuizScreen';
2 | import createSagas from './sagas';
3 | import redux from './redux';
4 |
5 | export const key = 'quiz';
6 |
7 | export const screens = {
8 | main: QuizScreen,
9 | };
10 |
11 | export default {
12 | key,
13 | screens,
14 | createSagas,
15 | redux,
16 | };
17 |
--------------------------------------------------------------------------------
/app/features/user/index.js:
--------------------------------------------------------------------------------
1 | import ProfileScreen from './screens/ProfileScreen';
2 | import createSagas from './sagas';
3 | import redux from './redux';
4 |
5 | export const key = 'user';
6 |
7 | export const screens = {
8 | profile: ProfileScreen,
9 | };
10 |
11 | export default {
12 | key,
13 | screens,
14 | createSagas,
15 | redux,
16 | };
17 |
--------------------------------------------------------------------------------
/app/core/constants/Theme.js:
--------------------------------------------------------------------------------
1 | export const Colors = {
2 | main: '#583384',
3 | text: '#000',
4 | textSubtle: '#666',
5 | textSecondary: '#333',
6 | };
7 |
8 | export const Fonts = {
9 | h1: '24px',
10 | h2: '20px',
11 | normal: '16px',
12 | secondary: '14px',
13 | button: '18px',
14 | };
15 |
16 | export default { colors: Colors, fonts: Fonts };
17 |
--------------------------------------------------------------------------------
/app/features/main/screens/LoadingScreen.js:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { ActivityIndicator } from 'react-native';
3 |
4 | import Container from '@app/core/components/Container';
5 |
6 | export default () => {
7 | return (
8 |
9 |
10 |
11 | );
12 | };
13 |
--------------------------------------------------------------------------------
/app/core/store/createRootReducer.js:
--------------------------------------------------------------------------------
1 | import { combineReducers } from 'redux';
2 |
3 | function createRootReducer(modules) {
4 | const mapObject = modules.reduce((object, module) => {
5 | return module.redux
6 | ? { ...object, [module.key]: module.redux.reducer }
7 | : object;
8 | }, {});
9 | return combineReducers(mapObject);
10 | }
11 |
12 | export default createRootReducer;
13 |
--------------------------------------------------------------------------------
/app/core/assets/index.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable global-require */
2 |
3 | export function getAsset(id) {
4 | switch (id) {
5 | case 'check':
6 | return require('./check.png');
7 | case 'error':
8 | return require('./error.png');
9 | case 'user':
10 | return require('./user.png');
11 | default:
12 | return null;
13 | }
14 | }
15 |
16 | export default { getAsset };
17 |
--------------------------------------------------------------------------------
/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/core/components/Spacer.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { View } from 'react-native';
3 |
4 | export default ({ ratioOfFreeSpaceAtTop, children, ...otherProps }) => (
5 |
9 |
10 | {children}
11 |
12 |
13 | );
14 |
--------------------------------------------------------------------------------
/backend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "node-sandbox",
3 | "version": "1.0.0",
4 | "description": "Simple Node Sandbox",
5 | "main": "src/index.js",
6 | "scripts": {
7 | "start": "node src/index.js",
8 | "watch": "nodemon src/index.js"
9 | },
10 | "dependencies": {
11 | "json-server": "0.15.0",
12 | "json-server-auth": "1.2.1"
13 | },
14 | "devDependencies": {
15 | "nodemon": "1.18.4"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/features/auth/routes.js:
--------------------------------------------------------------------------------
1 | import createAnimatedSwitchNavigator from 'react-navigation-animated-switch';
2 |
3 | import LoginScreen from './screens/LoginScreen';
4 | import SignupScreen from './screens/SignupScreen';
5 |
6 | export default createAnimatedSwitchNavigator(
7 | {
8 | login: {
9 | screen: LoginScreen,
10 | },
11 | signup: {
12 | screen: SignupScreen,
13 | },
14 | },
15 | {
16 | initialRouteName: 'login',
17 | }
18 | );
19 |
--------------------------------------------------------------------------------
/ios/AwesomeProject/AppDelegate.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import
9 | #import
10 |
11 | @interface AppDelegate : UIResponder
12 |
13 | @property (nonatomic, strong) UIWindow *window;
14 |
15 | @end
16 |
--------------------------------------------------------------------------------
/ios/AwesomeProject/main.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import
9 |
10 | #import "AppDelegate.h"
11 |
12 | int main(int argc, char * argv[]) {
13 | @autoreleasepool {
14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/app/features/auth/components/TextInput.js:
--------------------------------------------------------------------------------
1 | import styled from '@emotion/native';
2 | import { TextInput } from 'react-native';
3 |
4 | const Input = styled(TextInput)`
5 | height: 44;
6 | align-self: stretch;
7 | background-color: #eee;
8 | border-radius: 8px;
9 | padding: 0 8px;
10 | margin: 8px 16px 0;
11 | `;
12 | Input.defaultProps = {
13 | placeholderTextColor: '#666',
14 | autoCorrect: false,
15 | autoCapitalize: 'none',
16 | };
17 |
18 | export default Input;
19 |
--------------------------------------------------------------------------------
/app/core/components/ImageButton.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import styled from '@emotion/native';
3 | import { TouchableOpacity, Image } from 'react-native';
4 |
5 | const Container = styled(TouchableOpacity)`
6 | justify-content: center;
7 | align-items: center;
8 | `;
9 |
10 | export default ({ source, imageStyle, onPress, ...otherProps }) => (
11 |
12 |
13 |
14 | );
15 |
--------------------------------------------------------------------------------
/app/features/auth/index.js:
--------------------------------------------------------------------------------
1 | import LoginScreen from './screens/LoginScreen';
2 | import SignupScreen from './screens/SignupScreen';
3 | import Navigator from './routes';
4 | import createSagas from './sagas';
5 | import redux from './redux';
6 |
7 | export const key = 'auth';
8 |
9 | export const screens = {
10 | main: Navigator,
11 | login: LoginScreen,
12 | signup: SignupScreen,
13 | };
14 |
15 | export default {
16 | redux,
17 | key,
18 | screens,
19 | createSagas,
20 | };
21 |
--------------------------------------------------------------------------------
/backend/src/dbFileUtils.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const fs = require('fs');
3 |
4 | const DEFAULT_DB = {
5 | users: [],
6 | };
7 |
8 | function getPathToDb() {
9 | return path.resolve(__dirname, '../db.json');
10 | }
11 |
12 | function checkCreateDbFile() {
13 | const pathToDb = getPathToDb();
14 | if (!fs.existsSync(pathToDb)) {
15 | fs.writeFileSync(pathToDb, JSON.stringify(DEFAULT_DB));
16 | }
17 | }
18 |
19 | module.exports = { getPathToDb, checkCreateDbFile };
20 |
--------------------------------------------------------------------------------
/app/core/components/ErrorMessage.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Text } from 'react-native';
3 | import styled from '@emotion/native';
4 |
5 | import { Fonts } from '@app/core/constants/Theme';
6 |
7 | const StyledText = styled(Text)`
8 | font-size: ${Fonts.normal};
9 | color: red;
10 | `;
11 |
12 | export default ({ error, ...otherProps }) =>
13 | error ? (
14 |
15 | {typeof error === 'string' ? error : error.message}
16 |
17 | ) : null;
18 |
--------------------------------------------------------------------------------
/app/core/store/KeyValueStorage.js:
--------------------------------------------------------------------------------
1 | import AsyncStorage from '@react-native-community/async-storage';
2 |
3 | export function get(key) {
4 | return AsyncStorage.getItem(key).then(value => {
5 | const jsonValue = JSON.parse(value);
6 | return jsonValue;
7 | });
8 | }
9 |
10 | export function set(key, value) {
11 | return AsyncStorage.setItem(key, JSON.stringify(value));
12 | }
13 |
14 | export function remove(key) {
15 | return AsyncStorage.removeItem(key);
16 | }
17 |
18 | export default { get, set, remove };
19 |
--------------------------------------------------------------------------------
/app/core/services/createApiMonitor.js:
--------------------------------------------------------------------------------
1 | function urlWithoutBase(response) {
2 | const {
3 | config: { url, baseURL },
4 | } = response;
5 | return url.substr(baseURL.length);
6 | }
7 |
8 | export default name => response => {
9 | // eslint-disable-next-line no-console
10 | console.log(
11 | `${name.toUpperCase()}: ${response.config.method.toUpperCase()} ${urlWithoutBase(
12 | response
13 | )}`,
14 | {
15 | config: response.config,
16 | data: response.data,
17 | response,
18 | }
19 | );
20 | };
21 |
--------------------------------------------------------------------------------
/backend/api.rest:
--------------------------------------------------------------------------------
1 | @host = http://localhost:3001
2 | GET {{host}}/users
3 |
4 | ### Login
5 | # @name login
6 | POST {{host}}/login
7 | Content-Type: application/json
8 |
9 | {
10 | "email": "1@1.com",
11 | "password": "test"
12 | }
13 |
14 | @authToken = {{login.response.body.accessToken}}
15 |
16 | ### Get user info
17 | GET {{host}}/users/1
18 | Authorization: Bearer {{authToken}}
19 |
20 |
21 | ### Send score
22 | PATCH {{host}}/users/1
23 | Authorization: Bearer {{authToken}}
24 | Content-Type: application/json
25 |
26 | {
27 | "score": 100
28 | }
29 |
--------------------------------------------------------------------------------
/app/features/quiz/utils.js:
--------------------------------------------------------------------------------
1 | import R from 'ramda';
2 |
3 | import { shuffled, randomRange } from '@app/core/utils';
4 |
5 | export const randomizedAnswers = question => {
6 | let answers = shuffled(question.incorrect_answers);
7 | const correctAnswerIndex = randomRange(0, answers.length + 1);
8 | answers = R.insert(correctAnswerIndex, question.correct_answer, answers);
9 | return { answers, correctAnswerIndex };
10 | };
11 |
12 | export const scoreForQuestion = question =>
13 | question.difficulty === 'hard' ? 3 : question.difficulty === 'medium' ? 2 : 1;
14 |
--------------------------------------------------------------------------------
/app/core/services/questionsApi.js:
--------------------------------------------------------------------------------
1 | import apisauce from 'apisauce';
2 |
3 | import createApiMonitor from './createApiMonitor';
4 |
5 | export default function createQuestionsApi() {
6 | const api = apisauce.create({
7 | baseURL: 'https://opentdb.com/',
8 | timeout: 10000,
9 | });
10 | if (__DEV__) {
11 | api.addMonitor(createApiMonitor('questions api'));
12 | }
13 | return api;
14 | }
15 |
16 | export async function getQuestions(api, number) {
17 | const res = await api.get('api.php', {
18 | amount: number,
19 | });
20 | return res;
21 | }
22 |
--------------------------------------------------------------------------------
/app/core/components/HeaderButton.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import styled, { css } from '@emotion/native';
3 |
4 | import { Colors } from '@app/core/constants/Theme';
5 |
6 | import ImageButton from './ImageButton';
7 |
8 | const imageDefaultStyle = css`
9 | tint-color: ${Colors.main};
10 | `;
11 |
12 | const StyledButton = styled(ImageButton)`
13 | width: 32px;
14 | height: 32px;
15 | margin-right: 4px;
16 | `;
17 |
18 | export default ({ imageStyle, ...props }) => (
19 |
20 | );
21 |
--------------------------------------------------------------------------------
/app/core/components/Container.js:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { SafeAreaView, View } from 'react-native';
3 | import { css } from '@emotion/native';
4 |
5 | const defaultStyle = ({ isCentered }) => css`
6 | flex: 1;
7 | background-color: white;
8 | align-items: center;
9 | justify-content: ${isCentered ? 'center' : 'flex-start'};
10 | `;
11 |
12 | export default props => {
13 | const { isSafeArea, style, ...otherProps } = props;
14 | const Component = isSafeArea ? SafeAreaView : View;
15 | return ;
16 | };
17 |
--------------------------------------------------------------------------------
/app/core/store/createRootSaga.js:
--------------------------------------------------------------------------------
1 | import { spawn, call } from 'redux-saga/effects';
2 |
3 | function createRootSaga(features, modules, onDataLoaded) {
4 | const featuresWithSagas = features.filter(f => f.createSagas);
5 | const sagasRegistry = [];
6 | function* rootSaga() {
7 | for (const feature of featuresWithSagas) {
8 | const sagas = yield call(feature.createSagas, modules);
9 | sagasRegistry[feature.key] = sagas;
10 | yield spawn(sagas.main);
11 | }
12 | onDataLoaded(sagasRegistry);
13 | }
14 | return rootSaga;
15 | }
16 |
17 | export default createRootSaga;
18 |
--------------------------------------------------------------------------------
/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'AwesomeProject'
2 | include ':react-native-reanimated'
3 | project(':react-native-reanimated').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-reanimated/android')
4 | include ':react-native-gesture-handler'
5 | project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android')
6 | include ':@react-native-community_async-storage'
7 | project(':@react-native-community_async-storage').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/async-storage/android')
8 |
9 | include ':app'
10 |
--------------------------------------------------------------------------------
/app/core/components/Text.js:
--------------------------------------------------------------------------------
1 | import styled from '@emotion/native';
2 | import { Text } from 'react-native';
3 |
4 | import { Fonts, Colors } from '@app/core/constants/Theme';
5 |
6 | export const H1 = styled(Text)`
7 | font-size: ${Fonts.h1};
8 | font-weight: 500;
9 | color: ${Colors.text};
10 | `;
11 |
12 | export const H2 = styled(Text)`
13 | font-size: ${Fonts.h2};
14 | color: ${Colors.text};
15 | `;
16 |
17 | export const NormalText = styled(Text)`
18 | font-size: ${Fonts.normal};
19 | color: ${Colors.text};
20 | `;
21 |
22 | export const SecondaryText = styled(Text)`
23 | font-size: ${Fonts.secondary};
24 | color: ${Colors.textSubtle};
25 | `;
26 |
--------------------------------------------------------------------------------
/metro.config.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Metro configuration for React Native
3 | * https://github.com/facebook/react-native
4 | *
5 | * @format
6 | */
7 |
8 | const path = require('path');
9 |
10 | const rootDir = __dirname;
11 |
12 | module.exports = {
13 | resolver: {
14 | extraNodeModules: {
15 | '@app/core': path.join(rootDir, 'app', 'core'),
16 | '@app/features': path.join(rootDir, 'app', 'features'),
17 | },
18 | blacklistRE: /^backend\//,
19 | },
20 | transformer: {
21 | getTransformOptions: async () => ({
22 | transform: {
23 | experimentalImportSupport: false,
24 | inlineRequires: false,
25 | },
26 | }),
27 | },
28 | };
29 |
--------------------------------------------------------------------------------
/app/core/utils.js:
--------------------------------------------------------------------------------
1 | import R from 'ramda';
2 |
3 | export function mapAllToUndefined(object) {
4 | return R.map(() => undefined, object);
5 | }
6 |
7 | export function randomRange(from, to) {
8 | return from + Math.floor(Math.random() * (to - from));
9 | }
10 |
11 | export function shuffled(array) {
12 | const result = [...array];
13 | const last = array.length - 1;
14 | for (let index = 0; index < array.length; index += 1) {
15 | const rand = randomRange(index, last);
16 | const temp = result[index];
17 | result[index] = result[rand];
18 | result[rand] = temp;
19 | }
20 | return result;
21 | }
22 |
23 | export default { mapAllToUndefined, shuffled, randomRange };
24 |
--------------------------------------------------------------------------------
/android/app/build_defs.bzl:
--------------------------------------------------------------------------------
1 | """Helper definitions to glob .aar and .jar targets"""
2 |
3 | def create_aar_targets(aarfiles):
4 | for aarfile in aarfiles:
5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")]
6 | lib_deps.append(":" + name)
7 | android_prebuilt_aar(
8 | name = name,
9 | aar = aarfile,
10 | )
11 |
12 | def create_jar_targets(jarfiles):
13 | for jarfile in jarfiles:
14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")]
15 | lib_deps.append(":" + name)
16 | prebuilt_jar(
17 | name = name,
18 | binary_jar = jarfile,
19 | )
20 |
--------------------------------------------------------------------------------
/app/features/main/routes.js:
--------------------------------------------------------------------------------
1 | import { createAppContainer } from 'react-navigation';
2 | import createAnimatedSwitchNavigator from 'react-navigation-animated-switch';
3 |
4 | import auth from '@app/features/auth';
5 | import home from '@app/features/home';
6 |
7 | import LoadingScreen from './screens/LoadingScreen';
8 |
9 | const AppNavigator = createAnimatedSwitchNavigator(
10 | {
11 | loading: {
12 | screen: LoadingScreen,
13 | },
14 | auth: {
15 | screen: auth.screens.main,
16 | },
17 | home: {
18 | screen: home.screens.main,
19 | },
20 | },
21 | {
22 | initialRouteName: 'loading',
23 | }
24 | );
25 |
26 | export default createAppContainer(AppNavigator);
27 |
--------------------------------------------------------------------------------
/app/features/dashboard/components/StartButton.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import styled from '@emotion/native';
3 |
4 | import { TouchableOpacity, Text } from 'react-native';
5 |
6 | import { Colors } from '@app/core/constants/Theme';
7 |
8 | const Container = styled(TouchableOpacity)`
9 | background-color: ${Colors.main};
10 | width: 96px;
11 | height: 96px;
12 | border-radius: 48px;
13 | justify-content: center;
14 | align-items: center;
15 | `;
16 |
17 | const Label = styled(Text)`
18 | color: white;
19 | font-size: 20px;
20 | `;
21 |
22 | export default ({ onPress, title, ...otherProps }) => (
23 |
24 |
25 |
26 | );
27 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: ['airbnb', 'prettier', 'prettier/react'],
3 | parser: 'babel-eslint',
4 | env: {
5 | jest: true,
6 | },
7 | rules: {
8 | 'prettier/prettier': [
9 | 'error',
10 | {
11 | trailingComma: 'es5',
12 | singleQuote: true,
13 | },
14 | ],
15 | 'no-use-before-define': 'off',
16 | 'react/jsx-filename-extension': 'off',
17 | 'react/prop-types': 'off',
18 | 'comma-dangle': 'off',
19 | 'no-restricted-syntax': 'off',
20 | 'import/no-extraneous-dependencies': 0,
21 | 'no-nested-ternary': 'off',
22 | },
23 | globals: {
24 | __DEV__: true,
25 | window: true,
26 | fetch: true,
27 | },
28 | plugins: ['prettier'],
29 | };
30 |
--------------------------------------------------------------------------------
/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/ios/AwesomeProject/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | }
33 | ],
34 | "info" : {
35 | "version" : 1,
36 | "author" : "xcode"
37 | }
38 | }
--------------------------------------------------------------------------------
/ios/AwesomeProjectTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/features/user/components/ProfileImage.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import styled from '@emotion/native';
3 | import { View, Image, PixelRatio } from 'react-native';
4 |
5 | import { Colors } from '@app/core/constants/Theme';
6 |
7 | const WIDTH = 200;
8 | const PX = PixelRatio.getPixelSizeForLayoutSize(WIDTH);
9 |
10 | export default props => (
11 |
12 |
13 |
14 | );
15 |
16 | const ProfileImage = styled(Image)`
17 | width: ${WIDTH.toString()};
18 | height: ${WIDTH.toString()};
19 | `;
20 |
21 | const Container = styled(View)`
22 | width: ${WIDTH.toString()};
23 | height: ${WIDTH.toString()};
24 | border-radius: ${(WIDTH / 2).toString()}px;
25 | border-width: 10px;
26 | border-color: ${Colors.main};
27 | overflow: hidden;
28 | `;
29 |
--------------------------------------------------------------------------------
/ios/AwesomeProject-tvOSTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/backend/src/index.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-console */
2 |
3 | const jsonServer = require('json-server');
4 | const auth = require('json-server-auth');
5 |
6 | const { getPathToDb, checkCreateDbFile } = require('./dbFileUtils');
7 |
8 | checkCreateDbFile();
9 |
10 | const app = jsonServer.create();
11 | const router = jsonServer.router(getPathToDb());
12 | app.db = router.db;
13 |
14 | const middlewares = jsonServer.defaults();
15 |
16 | const rules = auth.rewriter({
17 | // Permission rules
18 | users: 600,
19 | // Routes
20 | });
21 |
22 | app.use(jsonServer.bodyParser);
23 |
24 | // Order is important
25 | app.use(rules);
26 | app.use(auth);
27 | app.use(middlewares);
28 | app.use(router);
29 |
30 | // eslint-disable-next-line prefer-destructuring
31 | const PORT = process.env.PORT || 3001;
32 | app.listen(PORT, () => {
33 | console.log(`JSON Server is running on port ${PORT}`);
34 | });
35 |
--------------------------------------------------------------------------------
/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
--------------------------------------------------------------------------------
/app/core/services/Navigation.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import {
4 | NavigationActions,
5 | createAppContainer as originalCreateAppContainer,
6 | } from 'react-navigation';
7 |
8 | let navigator;
9 |
10 | function setTopLevelNavigator(navigatorRef) {
11 | navigator = navigatorRef;
12 | }
13 |
14 | function navigate(routeName, params) {
15 | navigator.dispatch(
16 | NavigationActions.navigate({
17 | routeName,
18 | params,
19 | })
20 | );
21 | }
22 |
23 | function goBack() {
24 | navigator.dispatch(NavigationActions.back());
25 | }
26 |
27 | function createAppContainer(screen) {
28 | const AppContainer = originalCreateAppContainer(screen);
29 | return () => (
30 | {
32 | setTopLevelNavigator(navigatorRef);
33 | }}
34 | />
35 | );
36 | }
37 |
38 | export default {
39 | createAppContainer,
40 | goBack,
41 | navigate,
42 | setTopLevelNavigator,
43 | };
44 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext {
5 | buildToolsVersion = "28.0.3"
6 | minSdkVersion = 16
7 | compileSdkVersion = 28
8 | targetSdkVersion = 28
9 | supportLibVersion = "28.0.0"
10 | }
11 | repositories {
12 | google()
13 | jcenter()
14 | }
15 | dependencies {
16 | classpath("com.android.tools.build:gradle:3.4.0")
17 |
18 | // NOTE: Do not place your application dependencies here; they belong
19 | // in the individual module build.gradle files
20 | }
21 | }
22 |
23 | allprojects {
24 | repositories {
25 | mavenLocal()
26 | google()
27 | jcenter()
28 | maven {
29 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
30 | url "$rootDir/../node_modules/react-native/android"
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/android/app/src/main/java/com/awesomeproject/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.awesomeproject;
2 |
3 | import com.facebook.react.ReactActivity;
4 | import com.facebook.react.ReactActivityDelegate;
5 | import com.facebook.react.ReactRootView;
6 | import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
7 |
8 | public class MainActivity extends ReactActivity {
9 |
10 | /**
11 | * Returns the name of the main component registered from JavaScript.
12 | * This is used to schedule rendering of the component.
13 | */
14 | @Override
15 | protected String getMainComponentName() {
16 | return "AwesomeProject";
17 | }
18 |
19 | @Override
20 | protected ReactActivityDelegate createReactActivityDelegate() {
21 | return new ReactActivityDelegate(this, getMainComponentName()) {
22 | @Override
23 | protected ReactRootView createRootView() {
24 | return new RNGestureHandlerEnabledRootView(MainActivity.this);
25 | }
26 | };
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/app/features/home/routes.js:
--------------------------------------------------------------------------------
1 | import { createStackNavigator } from 'react-navigation';
2 |
3 | import dashboard from '@app/features/dashboard';
4 | import user from '@app/features/user';
5 | import quiz from '@app/features/quiz';
6 |
7 | import { Colors } from '@app/core/constants/Theme';
8 |
9 | const StackNavigator = createStackNavigator(
10 | {
11 | dashboard: {
12 | screen: dashboard.screens.main,
13 | },
14 | profile: {
15 | screen: user.screens.profile,
16 | },
17 | },
18 | {
19 | initialRouteName: 'dashboard',
20 | defaultNavigationOptions: {
21 | headerTintColor: Colors.main,
22 | headerTitleStyle: { color: 'black' },
23 | },
24 | }
25 | );
26 |
27 | const ModalNavigator = createStackNavigator(
28 | {
29 | main: {
30 | screen: StackNavigator,
31 | },
32 | quiz: {
33 | screen: quiz.screens.main,
34 | },
35 | },
36 | {
37 | mode: 'modal',
38 | headerMode: 'none',
39 | initialRouteName: 'main',
40 | }
41 | );
42 |
43 | export default ModalNavigator;
44 |
--------------------------------------------------------------------------------
/app/core/components/PrimaryButton.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { TouchableOpacity, Text, ActivityIndicator } from 'react-native';
3 | import styled from '@emotion/native';
4 |
5 | import { Colors, Fonts } from '@app/core/constants/Theme';
6 |
7 | const Container = styled(TouchableOpacity)`
8 | flex-direction: row;
9 | align-items: center;
10 | justify-content: center;
11 | background-color: ${Colors.main};
12 | border-radius: 8px;
13 | padding: 12px 16px;
14 | opacity: ${({ disabled }) => (disabled ? '0.5' : '1')};
15 | `;
16 |
17 | const Label = styled(Text)`
18 | color: white;
19 | font-size: ${Fonts.button};
20 | `;
21 |
22 | const StyledActivityIndicator = styled(ActivityIndicator)`
23 | margin-right: 8px;
24 | `;
25 | StyledActivityIndicator.defaultProps = {
26 | color: 'white',
27 | };
28 |
29 | export default ({ isInProgress, type, title, onPress, ...otherProps }) => (
30 |
31 | {isInProgress ? : null}
32 |
33 |
34 | );
35 |
--------------------------------------------------------------------------------
/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
13 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/features/dashboard/screens/DashboardScreen.js:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 |
3 | import Container from '@app/core/components/Container';
4 | import Navigation from '@app/core/services/Navigation';
5 | import { getAsset } from '@app/core/assets';
6 | import Spacer from '@app/core/components/Spacer';
7 | import HeaderButton from '@app/core/components/HeaderButton';
8 |
9 | import StartButton from '../components/StartButton';
10 |
11 | const DashboardScreen = () => {
12 | const handleStartQuiz = () => {
13 | Navigation.navigate('quiz');
14 | };
15 | return (
16 |
17 |
18 |
19 |
20 |
21 | );
22 | };
23 |
24 | const handleShowProfile = () => {
25 | Navigation.navigate('profile');
26 | };
27 |
28 | DashboardScreen.navigationOptions = {
29 | title: 'Welcome',
30 | headerRight: (
31 |
36 | ),
37 | };
38 |
39 | export default DashboardScreen;
40 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Backend
2 | backend/db.json
3 |
4 | # VS Code
5 | .vscode/
6 |
7 | # OSX
8 | #
9 | .DS_Store
10 |
11 | # Xcode
12 | #
13 | build/
14 | *.pbxuser
15 | !default.pbxuser
16 | *.mode1v3
17 | !default.mode1v3
18 | *.mode2v3
19 | !default.mode2v3
20 | *.perspectivev3
21 | !default.perspectivev3
22 | xcuserdata
23 | *.xccheckout
24 | *.moved-aside
25 | DerivedData
26 | *.hmap
27 | *.ipa
28 | *.xcuserstate
29 | project.xcworkspace
30 |
31 | # Android/IntelliJ
32 | #
33 | build/
34 | .idea
35 | .gradle
36 | local.properties
37 | *.iml
38 | .classpath
39 | /android/app/.project
40 | android/app/.settings/
41 |
42 | # node.js
43 | #
44 | node_modules/
45 | npm-debug.log
46 | yarn-error.log
47 | # BUCK
48 | buck-out/
49 | \.buckd/
50 | *.keystore
51 |
52 | # fastlane
53 | #
54 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
55 | # screenshots whenever they are needed.
56 | # For more information about the recommended setup visit:
57 | # https://docs.fastlane.tools/best-practices/source-control/
58 | */fastlane/report.xml
59 | */fastlane/Preview.html
60 | */fastlane/screenshots
61 |
62 | # Bundle artifact
63 | *.jsbundle
--------------------------------------------------------------------------------
/app/core/components/SecondaryButton.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { TouchableOpacity, Text, ActivityIndicator, Image } from 'react-native';
3 | import styled from '@emotion/native';
4 |
5 | import { Colors, Fonts } from '@app/core/constants/Theme';
6 |
7 | const Label = styled(Text)`
8 | color: ${Colors.main};
9 | font-size: ${Fonts.button};
10 | `;
11 |
12 | const Touchable = styled(TouchableOpacity)`
13 | flex-direction: row;
14 | align-items: center;
15 | justify-content: center;
16 | padding: 8px;
17 | `;
18 |
19 | const StyledActivityIndicator = styled(ActivityIndicator)`
20 | margin-right: 4px;
21 | `;
22 |
23 | export default ({
24 | isInProgress,
25 | type,
26 | title,
27 | onPress,
28 | labelStyle,
29 | disabled,
30 | icon,
31 | iconStyle,
32 | style,
33 | ...otherProps
34 | }) => (
35 |
42 | {isInProgress ? : null}
43 | {icon ? : null}
44 |
47 |
48 | );
49 |
--------------------------------------------------------------------------------
/android/app/BUCK:
--------------------------------------------------------------------------------
1 | # To learn about Buck see [Docs](https://buckbuild.com/).
2 | # To run your application with Buck:
3 | # - install Buck
4 | # - `npm start` - to start the packager
5 | # - `cd android`
6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
8 | # - `buck install -r android/app` - compile, install and run application
9 | #
10 |
11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets")
12 |
13 | lib_deps = []
14 |
15 | create_aar_targets(glob(["libs/*.aar"]))
16 |
17 | create_jar_targets(glob(["libs/*.jar"]))
18 |
19 | android_library(
20 | name = "all-libs",
21 | exported_deps = lib_deps,
22 | )
23 |
24 | android_library(
25 | name = "app-code",
26 | srcs = glob([
27 | "src/main/java/**/*.java",
28 | ]),
29 | deps = [
30 | ":all-libs",
31 | ":build_config",
32 | ":res",
33 | ],
34 | )
35 |
36 | android_build_config(
37 | name = "build_config",
38 | package = "com.awesomeproject",
39 | )
40 |
41 | android_resource(
42 | name = "res",
43 | package = "com.awesomeproject",
44 | res = "src/main/res",
45 | )
46 |
47 | android_binary(
48 | name = "app",
49 | keystore = "//android/keystores:debug",
50 | manifest = "src/main/AndroidManifest.xml",
51 | package_type = "debug",
52 | deps = [
53 | ":app-code",
54 | ],
55 | )
56 |
--------------------------------------------------------------------------------
/ios/AwesomeProject/AppDelegate.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import "AppDelegate.h"
9 |
10 | #import
11 | #import
12 | #import
13 |
14 | @implementation AppDelegate
15 |
16 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
17 | {
18 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
19 | RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
20 | moduleName:@"AwesomeProject"
21 | initialProperties:nil];
22 |
23 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
24 |
25 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
26 | UIViewController *rootViewController = [UIViewController new];
27 | rootViewController.view = rootView;
28 | self.window.rootViewController = rootViewController;
29 | [self.window makeKeyAndVisible];
30 | return YES;
31 | }
32 |
33 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
34 | {
35 | #if DEBUG
36 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
37 | #else
38 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
39 | #endif
40 | }
41 |
42 | @end
43 |
--------------------------------------------------------------------------------
/android/app/src/main/java/com/awesomeproject/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.awesomeproject;
2 |
3 | import android.app.Application;
4 |
5 | import com.facebook.react.ReactApplication;
6 | import com.swmansion.reanimated.ReanimatedPackage;
7 | import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
8 | import com.reactnativecommunity.asyncstorage.AsyncStoragePackage;
9 | import com.facebook.react.ReactNativeHost;
10 | import com.facebook.react.ReactPackage;
11 | import com.facebook.react.shell.MainReactPackage;
12 | import com.facebook.soloader.SoLoader;
13 |
14 | import java.util.Arrays;
15 | import java.util.List;
16 |
17 | public class MainApplication extends Application implements ReactApplication {
18 |
19 | private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
20 | @Override
21 | public boolean getUseDeveloperSupport() {
22 | return BuildConfig.DEBUG;
23 | }
24 |
25 | @Override
26 | protected List getPackages() {
27 | return Arrays.asList(
28 | new MainReactPackage(),
29 | new ReanimatedPackage(),
30 | new RNGestureHandlerPackage(),
31 | new AsyncStoragePackage()
32 | );
33 | }
34 |
35 | @Override
36 | protected String getJSMainModuleName() {
37 | return "index";
38 | }
39 | };
40 |
41 | @Override
42 | public ReactNativeHost getReactNativeHost() {
43 | return mReactNativeHost;
44 | }
45 |
46 | @Override
47 | public void onCreate() {
48 | super.onCreate();
49 | SoLoader.init(this, /* native exopackage */ false);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/app/features/quiz/components/QuizLoading.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { connect } from 'react-redux';
3 | import { View, ActivityIndicator } from 'react-native';
4 | import styled from '@emotion/native';
5 |
6 | import { NormalText } from '@app/core/components/Text';
7 | import Spacer from '@app/core/components/Spacer';
8 | import SecondaryButton from '@app/core/components/SecondaryButton';
9 | import ErrorMessage from '@app/core/components/ErrorMessage';
10 |
11 | import { actionCreators } from '../redux';
12 |
13 | const QuizLoading = ({ questionsError, questionsRequest }) => (
14 |
15 |
16 | {questionsError ? (
17 | <>
18 | Error while downloading questions:
19 |
20 |
21 | >
22 | ) : (
23 | <>
24 |
25 | Loading questions...
26 | >
27 | )}
28 |
29 |
30 | );
31 |
32 | export default connect(
33 | state => ({
34 | ...state.quiz,
35 | }),
36 | {
37 | questionsRequest: actionCreators.questionsRequest,
38 | }
39 | )(QuizLoading);
40 |
41 | const Container = styled(View)`
42 | flex: 1;
43 | `;
44 | const StyledSpacer = styled(Spacer)`
45 | align-items: center;
46 | justify-content: center;
47 | `;
48 | StyledSpacer.defaultProps = {
49 | ratioOfFreeSpaceAtTop: 0.66,
50 | };
51 | const StyledText = styled(NormalText)`
52 | margin-top: 8px;
53 | `;
54 |
--------------------------------------------------------------------------------
/app/core/services/userApi.js:
--------------------------------------------------------------------------------
1 | import apisauce from 'apisauce';
2 | import jwtDecode from 'jwt-decode';
3 |
4 | import createApiMonitor from './createApiMonitor';
5 |
6 | export function parseToken(token) {
7 | const data = jwtDecode(token);
8 | return {
9 | email: data.email || '',
10 | userId: data.sub || '',
11 | };
12 | }
13 |
14 | export function createApi(onTokenExpired) {
15 | const api = apisauce.create({
16 | baseURL: 'http://localhost:3001/',
17 | timeout: 10000,
18 | });
19 | if (__DEV__) {
20 | api.addMonitor(createApiMonitor('user api'));
21 | }
22 | api.addMonitor(response => {
23 | if (
24 | !response.ok &&
25 | response.status === 401 &&
26 | response.data === 'jwt expired' &&
27 | onTokenExpired
28 | ) {
29 | onTokenExpired();
30 | }
31 | });
32 | return api;
33 | }
34 |
35 | export async function setToken(api, token) {
36 | if (token) {
37 | api.setHeader('Authorization', `Bearer ${token}`);
38 | } else {
39 | api.deleteHeader('Authorization');
40 | }
41 | }
42 |
43 | function cleanup(api) {
44 | api.deleteHeader('Authorization');
45 | }
46 |
47 | export async function login(api, email, password) {
48 | cleanup(api);
49 | const res = await api.post('login', { email, password });
50 | return res;
51 | }
52 |
53 | export async function signup(api, email, password) {
54 | cleanup(api);
55 | const res = await api.post('signup', { email, password });
56 | return res;
57 | }
58 |
59 | export function get(api, entity, id) {
60 | return api.get(`${entity}/${id}`);
61 | }
62 |
63 | export function patch(api, entity, id, data) {
64 | return api.patch(`${entity}/${id}`, data);
65 | }
66 |
67 | export default createApi;
68 |
--------------------------------------------------------------------------------
/app/features/user/screens/ProfileScreen.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect } from 'react';
2 | import { connect } from 'react-redux';
3 | import styled from '@emotion/native';
4 |
5 | import auth from '@app/features/auth';
6 |
7 | import Container from '@app/core/components/Container';
8 | import SecondaryButton from '@app/core/components/SecondaryButton';
9 | import Spacer from '@app/core/components/Spacer';
10 | import { H2 } from '@app/core/components/Text';
11 | import { Colors } from '@app/core/constants/Theme';
12 |
13 | import ProfileImage from '../components/ProfileImage';
14 | import { actionCreators } from '../redux';
15 |
16 | const ProfileScreen = ({
17 | logout,
18 | score,
19 | quizCount,
20 | email,
21 | userDataRequest,
22 | }) => {
23 | useEffect(() => {
24 | userDataRequest();
25 | }, []);
26 | return (
27 |
28 |
29 |
30 | {email}
31 | Quizzes finished: {quizCount}
32 | Total score: {score}
33 |
34 |
35 |
36 | );
37 | };
38 |
39 | ProfileScreen.navigationOptions = {
40 | title: 'Profile',
41 | };
42 |
43 | export default connect(
44 | state => ({
45 | ...state.user,
46 | }),
47 | {
48 | logout: auth.redux.actionCreators.logout,
49 | userDataRequest: actionCreators.userDataRequest,
50 | }
51 | )(ProfileScreen);
52 |
53 | const FirstLine = styled(H2)`
54 | color: ${Colors.textSecondary};
55 | margin-top: 16px;
56 | `;
57 | const NextLine = styled(FirstLine)`
58 | margin-top: 8px;
59 | `;
60 | const LogoutButton = styled(SecondaryButton)`
61 | margin-top: 16px;
62 | `;
63 |
--------------------------------------------------------------------------------
/ios/AwesomeProject-tvOS/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | UILaunchStoryboardName
26 | LaunchScreen
27 | UIRequiredDeviceCapabilities
28 |
29 | armv7
30 |
31 | UISupportedInterfaceOrientations
32 |
33 | UIInterfaceOrientationPortrait
34 | UIInterfaceOrientationLandscapeLeft
35 | UIInterfaceOrientationLandscapeRight
36 |
37 | UIViewControllerBasedStatusBarAppearance
38 |
39 | NSLocationWhenInUseUsageDescription
40 |
41 | NSAppTransportSecurity
42 |
43 |
44 | NSExceptionDomains
45 |
46 | localhost
47 |
48 | NSExceptionAllowsInsecureHTTPLoads
49 |
50 |
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/app/core/store/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {
3 | createStore as createReduxStore,
4 | applyMiddleware,
5 | compose as reduxCompose,
6 | } from 'redux';
7 | import { Provider as ReduxProvider } from 'react-redux';
8 | import createSagaMiddleware from 'redux-saga';
9 | import { createLogger } from 'redux-logger';
10 |
11 | import createRootSaga from './createRootSaga';
12 | import createRootReducer from './createRootReducer';
13 | import ActionTypes from './ActionTypes';
14 |
15 | export const GlobalActionTypes = ActionTypes;
16 |
17 | export function createStore(features, modules) {
18 | const middlewares = [];
19 | if (__DEV__ && window) {
20 | const logger = createLogger({ collapsed: true });
21 | middlewares.push(logger);
22 | }
23 |
24 | const reducer = createRootReducer(features);
25 |
26 | const sagaMiddleware = createSagaMiddleware();
27 | middlewares.push(sagaMiddleware);
28 |
29 | // eslint-disable-next-line no-underscore-dangle
30 | const compose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || reduxCompose;
31 |
32 | const reduxStore = createReduxStore(
33 | reducer,
34 | {},
35 | compose(applyMiddleware(...middlewares))
36 | );
37 |
38 | return {
39 | modules,
40 | reduxStore,
41 | runSagas: onDataLoaded => {
42 | const rootSaga = createRootSaga(features, modules, onDataLoaded);
43 | sagaMiddleware.run(rootSaga);
44 | },
45 | };
46 | }
47 |
48 | export function loadStoreData(store, handler) {
49 | store.runSagas(handler);
50 | }
51 |
52 | export function createProviderComponent(store) {
53 | return ({ children }) => {
54 | return {children};
55 | };
56 | }
57 |
58 | export function saveStoreData(store) {
59 | store.reduxStore.dispatch({ type: ActionTypes.SAVE_DATA });
60 | }
61 |
62 | export default {
63 | GlobalActionTypes,
64 | createStore,
65 | createProviderComponent,
66 | loadStoreData,
67 | saveStoreData,
68 | };
69 |
--------------------------------------------------------------------------------
/ios/AwesomeProject/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleDisplayName
8 | AwesomeProject
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | 1.0
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | 1
25 | LSRequiresIPhoneOS
26 |
27 | NSLocationWhenInUseUsageDescription
28 |
29 | UILaunchStoryboardName
30 | LaunchScreen
31 | UIRequiredDeviceCapabilities
32 |
33 | armv7
34 |
35 | UISupportedInterfaceOrientations
36 |
37 | UIInterfaceOrientationPortrait
38 | UIInterfaceOrientationLandscapeLeft
39 | UIInterfaceOrientationLandscapeRight
40 |
41 | UIViewControllerBasedStatusBarAppearance
42 |
43 | NSLocationWhenInUseUsageDescription
44 |
45 | NSAppTransportSecurity
46 |
47 |
48 | NSAllowsArbitraryLoads
49 |
50 | NSExceptionDomains
51 |
52 | localhost
53 |
54 | NSExceptionAllowsInsecureHTTPLoads
55 |
56 |
57 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/app/features/user/redux.js:
--------------------------------------------------------------------------------
1 | import { createReducer, createActions } from 'reduxsauce';
2 | import { mapAllToUndefined } from '@app/core/utils';
3 | import { GlobalActionTypes } from '@app/core/store';
4 |
5 | const { Types, Creators } = createActions(
6 | {
7 | rehydration: ['payload'],
8 |
9 | userDataRequest: ['payload'],
10 | userDataSuccess: ['payload'],
11 | userDataFailure: ['payload'],
12 | },
13 | { prefix: 'APP/USER/' }
14 | );
15 |
16 | export const actionTypes = Types;
17 | export const actionCreators = Creators;
18 |
19 | const INITIAL_STATE_PERSISTENT = {
20 | score: 0,
21 | quizCount: 0,
22 | email: '',
23 | };
24 |
25 | const INITIAL_STATE_TRANSIENT = {
26 | isUserDataActive: false,
27 | userDataError: null,
28 | };
29 |
30 | const INITIAL_STATE = {
31 | ...INITIAL_STATE_PERSISTENT,
32 | ...INITIAL_STATE_TRANSIENT,
33 | };
34 |
35 | export const selectors = {
36 | rehydration: state => ({
37 | ...state.user,
38 | ...mapAllToUndefined(INITIAL_STATE_TRANSIENT),
39 | }),
40 | };
41 |
42 | const rehydration = (state = INITIAL_STATE, { payload: { data } }) => ({
43 | ...state,
44 | ...data,
45 | });
46 |
47 | // const questionsRequest = (state = INITIAL_STATE) => {
48 | // return {
49 | // ...state,
50 | // mode: MODES.load,
51 | // questions: [],
52 | // questionsError: null,
53 | // isQuestionsRequestActive: true,
54 | // };
55 | // };
56 |
57 | const userDataSuccess = (state = INITIAL_STATE, { payload: { data } }) => {
58 | return {
59 | ...state,
60 | score: data.score || 0,
61 | quizCount: data.quizCount || 0,
62 | email: data.email || '',
63 | userDataError: null,
64 | isUserDataActive: false,
65 | };
66 | };
67 |
68 | const reset = () => {
69 | return INITIAL_STATE;
70 | };
71 |
72 | const HANDLERS = {
73 | [Types.REHYDRATION]: rehydration,
74 | [Types.USER_DATA_SUCCESS]: userDataSuccess,
75 | [GlobalActionTypes.RESET]: reset,
76 | };
77 |
78 | export const reducer = createReducer(INITIAL_STATE, HANDLERS);
79 |
80 | export default { actionTypes, actionCreators, reducer, selectors };
81 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "AwesomeProject",
3 | "version": "0.0.1",
4 | "private": true,
5 | "scripts": {
6 | "preinstall": "node ./scripts/link_folders.js",
7 | "postinstall": "node ./scripts/link_folders.js",
8 | "start": "node node_modules/react-native/local-cli/cli.js start",
9 | "backend": "cd backend && yarn watch",
10 | "backend:android": "adb reverse tcp:3001 tcp:3001",
11 | "backend:deploy": "git subtree push --prefix backend heroku master",
12 | "backend:logs": "heroku logs -t",
13 | "test": "jest"
14 | },
15 | "dependencies": {
16 | "@emotion/core": "^10.0.14",
17 | "@emotion/native": "^10.0.14",
18 | "@react-native-community/async-storage": "^1.5.0",
19 | "apisauce": "^1.0.3",
20 | "html-entities": "^1.2.1",
21 | "jwt-decode": "^2.2.0",
22 | "luxon": "^1.16.0",
23 | "ramda": "^0.26.1",
24 | "ramdasauce": "^2.1.3",
25 | "react": "16.8.3",
26 | "react-native": "0.59.9",
27 | "react-native-alert-async": "^1.0.3",
28 | "react-native-gesture-handler": "^1.3.0",
29 | "react-native-reanimated": "^1.1.0",
30 | "react-navigation": "^3.11.0",
31 | "react-navigation-animated-switch": "^0.2.1",
32 | "react-redux": "^7.1.0",
33 | "redux": "^4.0.1",
34 | "redux-logger": "^3.0.6",
35 | "redux-saga": "^1.0.3",
36 | "reduxsauce": "^1.1.0"
37 | },
38 | "devDependencies": {
39 | "@babel/core": "^7.4.5",
40 | "@babel/runtime": "^7.4.5",
41 | "babel-eslint": "^10.0.2",
42 | "babel-jest": "^24.8.0",
43 | "eslint": "^6.0.1",
44 | "eslint-config-airbnb": "^17.1.0",
45 | "eslint-config-prettier": "^5.1.0",
46 | "eslint-plugin-import": "^2.18.0",
47 | "eslint-plugin-jsx-a11y": "^6.2.1",
48 | "eslint-plugin-prettier": "^3.1.0",
49 | "eslint-plugin-react": "^7.14.2",
50 | "flow-bin": "^0.101.1",
51 | "get-dev-paths": "^0.1.1",
52 | "jest": "^24.8.0",
53 | "json-server": "^0.15.0",
54 | "metro-react-native-babel-preset": "^0.54.1",
55 | "prettier": "^1.18.2",
56 | "react-test-renderer": "16.8.3"
57 | },
58 | "jest": {
59 | "preset": "react-native"
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/app/App.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect } from 'react';
2 |
3 | import Navigation from '@app/core/services/Navigation';
4 | import {
5 | createStore,
6 | loadStoreData,
7 | createProviderComponent,
8 | GlobalActionTypes,
9 | } from '@app/core/store';
10 |
11 | import KeyValueStorage from '@app/core/store/KeyValueStorage';
12 | import createUserApi from '@app/core/services/userApi';
13 | import createQuestionsApi from '@app/core/services/questionsApi';
14 |
15 | import auth from '@app/features/auth';
16 | import dashboard from '@app/features/dashboard';
17 | import main from '@app/features/main';
18 | import home from '@app/features/home';
19 | import user from '@app/features/user';
20 | import quiz from '@app/features/quiz';
21 | import AlertAsync from 'react-native-alert-async';
22 |
23 | const allFeatures = [auth, dashboard, main, home, user, quiz];
24 |
25 | const AppContainer = Navigation.createAppContainer(main.screens.main);
26 |
27 | const moduleRegistry = {
28 | navigation: Navigation,
29 | keyValueStorage: KeyValueStorage,
30 | userApi: createUserApi(handleTokenExpired),
31 | questionsApi: createQuestionsApi(),
32 | };
33 |
34 | const store = createStore(allFeatures, moduleRegistry);
35 | moduleRegistry.store = store;
36 | const Provider = createProviderComponent(store);
37 |
38 | function handleTokenExpired() {
39 | AlertAsync('Auth token expired', 'Sorry, login again please');
40 | moduleRegistry.store.reduxStore.dispatch({ type: GlobalActionTypes.LOGOUT });
41 | }
42 |
43 | export default () => {
44 | useEffect(() => {
45 | loadStoreData(store, sagasRegistry => {
46 | const state = store.reduxStore.getState();
47 | if (state.auth.token) {
48 | if (state.quiz.isActive) {
49 | Navigation.navigate('quiz');
50 | } else {
51 | Navigation.navigate('home');
52 | }
53 | } else if (state.auth.lastEmail) {
54 | Navigation.navigate('login');
55 | } else {
56 | Navigation.navigate('signup');
57 | }
58 | moduleRegistry.sagas = sagasRegistry;
59 | });
60 | }, []);
61 | return (
62 |
63 |
64 |
65 | );
66 | };
67 |
--------------------------------------------------------------------------------
/ios/AwesomeProjectTests/AwesomeProjectTests.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import
9 | #import
10 |
11 | #import
12 | #import
13 |
14 | #define TIMEOUT_SECONDS 600
15 | #define TEXT_TO_LOOK_FOR @"Welcome to React Native!"
16 |
17 | @interface AwesomeProjectTests : XCTestCase
18 |
19 | @end
20 |
21 | @implementation AwesomeProjectTests
22 |
23 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test
24 | {
25 | if (test(view)) {
26 | return YES;
27 | }
28 | for (UIView *subview in [view subviews]) {
29 | if ([self findSubviewInView:subview matching:test]) {
30 | return YES;
31 | }
32 | }
33 | return NO;
34 | }
35 |
36 | - (void)testRendersWelcomeScreen
37 | {
38 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
39 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
40 | BOOL foundElement = NO;
41 |
42 | __block NSString *redboxError = nil;
43 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
44 | if (level >= RCTLogLevelError) {
45 | redboxError = message;
46 | }
47 | });
48 |
49 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
50 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
51 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
52 |
53 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) {
54 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
55 | return YES;
56 | }
57 | return NO;
58 | }];
59 | }
60 |
61 | RCTSetLogFunction(RCTDefaultLogFunction);
62 |
63 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
64 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
65 | }
66 |
67 |
68 | @end
69 |
--------------------------------------------------------------------------------
/.flowconfig:
--------------------------------------------------------------------------------
1 | [ignore]
2 | ; We fork some components by platform
3 | .*/*[.]android.js
4 |
5 | ; Ignore "BUCK" generated dirs
6 | /\.buckd/
7 |
8 | ; Ignore unexpected extra "@providesModule"
9 | .*/node_modules/.*/node_modules/fbjs/.*
10 |
11 | ; Ignore duplicate module providers
12 | ; For RN Apps installed via npm, "Libraries" folder is inside
13 | ; "node_modules/react-native" but in the source repo it is in the root
14 | .*/Libraries/react-native/React.js
15 |
16 | ; Ignore polyfills
17 | .*/Libraries/polyfills/.*
18 |
19 | ; Ignore metro
20 | .*/node_modules/metro/.*
21 |
22 | [include]
23 |
24 | [libs]
25 | node_modules/react-native/Libraries/react-native/react-native-interface.js
26 | node_modules/react-native/flow/
27 |
28 | [options]
29 | emoji=true
30 |
31 | esproposal.optional_chaining=enable
32 | esproposal.nullish_coalescing=enable
33 |
34 | module.system=haste
35 | module.system.haste.use_name_reducers=true
36 | # get basename
37 | module.system.haste.name_reducers='^.*/\([a-zA-Z0-9$_.-]+\.js\(\.flow\)?\)$' -> '\1'
38 | # strip .js or .js.flow suffix
39 | module.system.haste.name_reducers='^\(.*\)\.js\(\.flow\)?$' -> '\1'
40 | # strip .ios suffix
41 | module.system.haste.name_reducers='^\(.*\)\.ios$' -> '\1'
42 | module.system.haste.name_reducers='^\(.*\)\.android$' -> '\1'
43 | module.system.haste.name_reducers='^\(.*\)\.native$' -> '\1'
44 | module.system.haste.paths.blacklist=.*/__tests__/.*
45 | module.system.haste.paths.blacklist=.*/__mocks__/.*
46 | module.system.haste.paths.blacklist=/node_modules/react-native/Libraries/Animated/src/polyfills/.*
47 | module.system.haste.paths.whitelist=/node_modules/react-native/Libraries/.*
48 |
49 | munge_underscores=true
50 |
51 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub'
52 |
53 | module.file_ext=.js
54 | module.file_ext=.jsx
55 | module.file_ext=.json
56 | module.file_ext=.native.js
57 |
58 | suppress_type=$FlowIssue
59 | suppress_type=$FlowFixMe
60 | suppress_type=$FlowFixMeProps
61 | suppress_type=$FlowFixMeState
62 |
63 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)
64 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+
65 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
66 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError
67 |
68 | [version]
69 | ^0.101.1
70 |
--------------------------------------------------------------------------------
/app/features/auth/screens/SignupScreen.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import { connect } from 'react-redux';
3 | import styled from '@emotion/native';
4 |
5 | import Container from '@app/core/components/Container';
6 | import Spacer from '@app/core/components/Spacer';
7 | import PrimaryButton from '@app/core/components/PrimaryButton';
8 | import SecondaryButton from '@app/core/components/SecondaryButton';
9 | import Navigation from '@app/core/services/Navigation';
10 | import { H1 } from '@app/core/components/Text';
11 | import ErrorMessage from '@app/core/components/ErrorMessage';
12 |
13 | import EmailInput from '../components/EmailInput';
14 | import PasswordInput from '../components/PasswordInput';
15 | import { actionCreators } from '../redux';
16 |
17 | const SignupScreen = ({ signupRequest, error, isActive }) => {
18 | const [email, setEmail] = useState('');
19 | const [password, setPassword] = useState('');
20 |
21 | const handleEmailChange = text => {
22 | setEmail(text);
23 | };
24 | const handlePasswordChange = text => {
25 | setPassword(text);
26 | };
27 | const handleSignupPress = () => {
28 | signupRequest({ email, password });
29 | };
30 | const handleSwitchToLogin = () => {
31 | Navigation.navigate('login');
32 | };
33 |
34 | return (
35 |
36 |
37 | Registration
38 |
39 |
40 |
41 |
45 |
51 |
52 |
53 | );
54 | };
55 |
56 | export default connect(
57 | state => ({
58 | error: state.auth.signupError || '',
59 | isActive: state.auth.isSignupActive || false,
60 | }),
61 | {
62 | signupRequest: actionCreators.signupRequest,
63 | }
64 | )(SignupScreen);
65 |
66 | const Title = styled(H1)`
67 | margin-bottom: 32px;
68 | `;
69 | const StyledErrorMessage = styled(ErrorMessage)`
70 | margin-bottom: 4px;
71 | `;
72 | const SwitchScreenButton = styled(SecondaryButton)`
73 | margin-top: 16px;
74 | `;
75 | const SignupButton = styled(PrimaryButton)`
76 | margin-top: 16px;
77 | `;
78 |
--------------------------------------------------------------------------------
/app/features/auth/screens/LoginScreen.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import { connect } from 'react-redux';
3 | import styled from '@emotion/native';
4 |
5 | import Container from '@app/core/components/Container';
6 | import Spacer from '@app/core/components/Spacer';
7 | import Navigation from '@app/core/services/Navigation';
8 | import PrimaryButton from '@app/core/components/PrimaryButton';
9 | import SecondaryButton from '@app/core/components/SecondaryButton';
10 | import { H1 } from '@app/core/components/Text';
11 | import ErrorMessage from '@app/core/components/ErrorMessage';
12 |
13 | import EmailInput from '../components/EmailInput';
14 | import PasswordInput from '../components/PasswordInput';
15 | import { actionCreators } from '../redux';
16 |
17 | const LoginScreen = ({ lastEmail, loginRequest, isActive, error }) => {
18 | const [email, setEmail] = useState(lastEmail);
19 | const [password, setPassword] = useState('');
20 |
21 | const handleSwitchToSignupPress = () => {
22 | Navigation.navigate('signup');
23 | };
24 | const handleLoginPress = () => {
25 | loginRequest({ email, password });
26 | };
27 | const handleEmailChange = text => {
28 | setEmail(text);
29 | };
30 | const handlePasswordChange = text => {
31 | setPassword(text);
32 | };
33 |
34 | return (
35 |
36 |
37 | Existing user
38 |
39 |
40 |
41 |
45 |
51 |
52 |
53 | );
54 | };
55 |
56 | export default connect(
57 | state => ({
58 | lastEmail: state.auth.lastEmail || '',
59 | error: state.auth.loginError || '',
60 | isActive: state.auth.isLoginActive || false,
61 | }),
62 | {
63 | loginRequest: actionCreators.loginRequest,
64 | }
65 | )(LoginScreen);
66 |
67 | const Title = styled(H1)`
68 | margin-bottom: 32px;
69 | `;
70 | const StyledErrorMessage = styled(ErrorMessage)`
71 | margin-bottom: 4px;
72 | `;
73 | const SwitchScreenButton = styled(SecondaryButton)`
74 | margin-top: 16px;
75 | `;
76 | const LoginButton = styled(PrimaryButton)`
77 | margin-top: 16px;
78 | `;
79 |
--------------------------------------------------------------------------------
/scripts/link_folders.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-console */
2 |
3 | /**
4 | * The script which is able to link and unlink the folders.
5 | * It is used mainly to add absolute imports
6 | */
7 |
8 | /**
9 | * Add or change folders here
10 | */
11 |
12 | const namespace = '@app';
13 | const namespaceDir = `./node_modules/${namespace}`;
14 | const folders = [
15 | {
16 | target: '../../app/core',
17 | destination: `${namespaceDir}/core`,
18 | },
19 | {
20 | target: '../../app/features',
21 | destination: `${namespaceDir}/features`,
22 | },
23 | ];
24 |
25 | /**
26 | * Main script
27 | */
28 |
29 | const fs = require('fs');
30 |
31 | if (
32 | process.argv[2] === 'link' ||
33 | process.env.npm_lifecycle_event === 'postinstall'
34 | ) {
35 | console.log('=========================================');
36 | checkCreateDir(namespaceDir);
37 | console.log('Linking folders:');
38 | for (const { target, destination } of folders) {
39 | resetLink(target, destination);
40 | }
41 | console.log('=========================================');
42 | } else if (
43 | process.argv[2] === 'unlink' ||
44 | process.env.npm_lifecycle_event === 'preinstall'
45 | ) {
46 | console.log('=========================================');
47 | console.log('Unlinking folders:');
48 | for (const { destination } of folders) {
49 | removeLink(destination);
50 | }
51 | checkRemoveDir(namespaceDir);
52 | console.log('=========================================');
53 | }
54 |
55 | /**
56 | * Utils
57 | */
58 |
59 | function checkCreateDir(dir) {
60 | if (!fs.existsSync(dir)) {
61 | console.log(`📁 Making dir: ${dir}`);
62 | fs.mkdirSync(dir);
63 | }
64 | }
65 |
66 | function checkRemoveDir(dir) {
67 | if (fs.existsSync(dir)) {
68 | console.log(`❌ Removing dir: ${dir}`);
69 | fs.rmdirSync(dir);
70 | }
71 | }
72 |
73 | function checkLinkSync(destination) {
74 | try {
75 | return Boolean(fs.readlinkSync(destination));
76 | } catch (e) {
77 | if (e.code === 'ENOENT') {
78 | return false;
79 | }
80 | throw e;
81 | }
82 | }
83 |
84 | function resetLink(target, destination) {
85 | console.log(`🔗 ${target} ==> ${destination}`);
86 | try {
87 | if (!checkLinkSync(destination)) {
88 | fs.symlinkSync(target, destination, 'junction');
89 | } else {
90 | console.log(`File ${destination} already exists.`);
91 | }
92 | } catch (e) {
93 | throw e;
94 | }
95 | }
96 |
97 | function removeLink(destination) {
98 | console.log(`❌ Removing link: ${destination}`);
99 | try {
100 | if (fs.readlinkSync(destination)) {
101 | fs.unlinkSync(destination);
102 | }
103 | } catch (e) {
104 | if (e.code === 'ENOENT') {
105 | console.log('No link yet');
106 | return;
107 | }
108 | throw e;
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/app/features/quiz/components/QuizResult.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { connect } from 'react-redux';
3 | import { View, ActivityIndicator } from 'react-native';
4 | import styled from '@emotion/native';
5 |
6 | import { NormalText, H1 } from '@app/core/components/Text';
7 | import Spacer from '@app/core/components/Spacer';
8 | import SecondaryButton from '@app/core/components/SecondaryButton';
9 | import PrimaryButton from '@app/core/components/PrimaryButton';
10 | import ErrorMessage from '@app/core/components/ErrorMessage';
11 |
12 | import { Colors } from '@app/core/constants/Theme';
13 | import { actionCreators } from '../redux';
14 |
15 | const QuizResult = ({
16 | isSendResultsActive,
17 | quizCount,
18 | score,
19 | sendResultsError,
20 | sendResultsRequest,
21 | stopQuiz,
22 | totalScore,
23 | }) => (
24 |
25 |
26 |
48 |
49 |
50 | );
51 |
52 | export default connect(
53 | state => ({
54 | ...state.quiz,
55 | totalScore: state.user.score,
56 | quizCount: state.user.quizCount,
57 | }),
58 | {
59 | sendResultsRequest: actionCreators.sendResultsRequest,
60 | stopQuiz: actionCreators.stopQuiz,
61 | }
62 | )(QuizResult);
63 |
64 | const Container = styled(View)`
65 | flex: 1;
66 | `;
67 | const StyledSpacer = styled(Spacer)`
68 | align-items: center;
69 | justify-content: center;
70 | `;
71 | StyledSpacer.defaultProps = {
72 | ratioOfFreeSpaceAtTop: 0.66,
73 | };
74 | const Title = styled(H1)``;
75 | const StyledIndicator = styled(ActivityIndicator)`
76 | margin-top: 16px;
77 | `;
78 | StyledIndicator.defaultProps = {
79 | size: 'large',
80 | };
81 | const StyledText = styled(NormalText)`
82 | margin-top: 8px;
83 | color: ${Colors.textSecondary};
84 | `;
85 | const StyledFirstLine = styled(StyledText)`
86 | margin-top: 16px;
87 | `;
88 | const StyledErrorMessage = styled(ErrorMessage)`
89 | margin-top: 8px;
90 | `;
91 | const Dialog = styled(View)`
92 | padding: 24px;
93 | border-radius: 8px;
94 | align-items: center;
95 | `;
96 | const StyledPrimaryButton = styled(PrimaryButton)`
97 | margin-top: 16px;
98 | `;
99 |
--------------------------------------------------------------------------------
/app/features/user/sagas.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-console */
2 | import { takeLatest, call, select, put } from 'redux-saga/effects';
3 | import { GlobalActionTypes } from '@app/core/store';
4 | import { getUser, patchUser } from './api';
5 |
6 | import { actionTypes, selectors, actionCreators } from './redux';
7 |
8 | const STORAGE_KEY = 'app/user';
9 |
10 | function* createSagas(modules) {
11 | function* userDataRequest({ userId } = {}) {
12 | try {
13 | const id = userId || (yield select(store => store.auth)).userId;
14 | const response = yield call(getUser, modules.userApi, id);
15 | if (!response.ok) {
16 | throw Error(response.problem || 'UNKNOWN_ERROR');
17 | }
18 | yield put(actionCreators.userDataSuccess({ data: response.data }));
19 | return response.data;
20 | } catch (error) {
21 | yield put(actionCreators.userDataFailure({ error }));
22 | console.warn(`User data error: ${error}`);
23 | return null;
24 | }
25 | }
26 |
27 | function* fetchUserData({ userId } = {}) {
28 | let id = userId;
29 | if (!id) {
30 | const authState = yield select(store => store.auth);
31 | id = authState.userId;
32 | }
33 | const response = yield call(getUser, modules.userApi, id);
34 | if (!response.ok) {
35 | throw Error(response.problem || 'UNKNOWN_ERROR');
36 | }
37 | return response.data;
38 | }
39 |
40 | function* increaseQuizStats({ score, quizCount }) {
41 | const recent = yield call(fetchUserData);
42 | const update = {
43 | score: (recent.score || 0) + score,
44 | quizCount: (recent.quizCount || 0) + quizCount,
45 | };
46 | const response = yield call(patchUser, modules.userApi, recent.id, update);
47 | if (!response.ok) {
48 | throw Error(response.problem || 'UNKNOWN_ERROR');
49 | }
50 | yield put(actionCreators.userDataSuccess({ data: response.data }));
51 | return update;
52 | }
53 |
54 | function* saveData() {
55 | try {
56 | const data = yield select(selectors.rehydration);
57 | yield call(modules.keyValueStorage.set, STORAGE_KEY, data);
58 | } catch (e) {
59 | console.warn(`Can't save user: ${e}`);
60 | }
61 | }
62 |
63 | function* loadData() {
64 | try {
65 | const data = yield call(modules.keyValueStorage.get, STORAGE_KEY) || {};
66 | yield put(actionCreators.rehydration({ data }));
67 | } catch (e) {
68 | console.warn(`Can't load user: ${e}`);
69 | }
70 | }
71 |
72 | function* reset() {
73 | try {
74 | yield call(modules.keyValueStorage.remove, STORAGE_KEY);
75 | } catch (e) {
76 | console.warn(`Can't reset user: ${e}`);
77 | }
78 | }
79 |
80 | yield call(loadData);
81 | function* main() {
82 | yield takeLatest(actionTypes.USER_DATA_REQUEST, userDataRequest);
83 | yield takeLatest(GlobalActionTypes.SAVE_DATA, saveData);
84 | yield takeLatest(GlobalActionTypes.RESET, reset);
85 | }
86 | return { main, userDataRequest, increaseQuizStats };
87 | }
88 |
89 | export default createSagas;
90 |
--------------------------------------------------------------------------------
/app/features/auth/redux.js:
--------------------------------------------------------------------------------
1 | import { createReducer, createActions } from 'reduxsauce';
2 | import { GlobalActionTypes } from '@app/core/store';
3 |
4 | const { Types, Creators } = createActions(
5 | {
6 | rehydration: ['payload'],
7 |
8 | loginRequest: ['payload'],
9 | loginSuccess: ['payload'],
10 | loginFailure: ['payload'],
11 |
12 | signupRequest: ['payload'],
13 | signupSuccess: ['payload'],
14 | signupFailure: ['payload'],
15 |
16 | logout: [],
17 | },
18 | { prefix: 'APP/AUTH/' }
19 | );
20 |
21 | export const actionTypes = Types;
22 | export const actionCreators = Creators;
23 |
24 | const INITIAL_STATE = {
25 | token: '',
26 | userId: '',
27 | lastEmail: '',
28 | isLoginActive: false,
29 | isSignupActive: false,
30 | loginError: null,
31 | signupError: null,
32 | };
33 |
34 | export const selectors = {
35 | rehydration: state => ({
36 | ...state.auth,
37 | loginError: null,
38 | signupError: null,
39 | isLoginActive: false,
40 | isSignupActive: false,
41 | }),
42 | };
43 |
44 | const rehydration = (state = INITIAL_STATE, { payload: { data } }) => ({
45 | ...state,
46 | ...data,
47 | });
48 |
49 | const loginRequest = (state = INITIAL_STATE, { payload: { email } }) => {
50 | return { ...state, lastEmail: email, loginError: null, isLoginActive: true };
51 | };
52 |
53 | const loginSuccess = (
54 | state = INITIAL_STATE,
55 | { payload: { token, userId } }
56 | ) => {
57 | return {
58 | ...state,
59 | token,
60 | userId,
61 | loginError: null,
62 | isLoginActive: false,
63 | };
64 | };
65 |
66 | const loginFailure = (state = INITIAL_STATE, { payload: { error } }) => {
67 | return { ...state, loginError: error, isLoginActive: false };
68 | };
69 |
70 | const signupRequest = (state = INITIAL_STATE, { payload: { email } }) => {
71 | return {
72 | ...state,
73 | lastEmail: email,
74 | signupError: null,
75 | isSignupActive: true,
76 | };
77 | };
78 |
79 | const signupSuccess = (
80 | state = INITIAL_STATE,
81 | { payload: { token, userId } }
82 | ) => {
83 | return {
84 | ...state,
85 | token,
86 | userId,
87 | signupError: null,
88 | isSignupActive: false,
89 | };
90 | };
91 |
92 | const signupFailure = (state = INITIAL_STATE, { payload: { error } }) => {
93 | return { ...state, signupError: error, isSignupActive: false };
94 | };
95 |
96 | const logout = (state = INITIAL_STATE) => {
97 | return { ...INITIAL_STATE, lastEmail: state.lastEmail };
98 | };
99 |
100 | const reset = (state = INITIAL_STATE) => {
101 | return {
102 | ...INITIAL_STATE,
103 | lastEmail: state.lastEmail,
104 | };
105 | };
106 |
107 | const HANDLERS = {
108 | [Types.REHYDRATION]: rehydration,
109 | [Types.LOGIN_REQUEST]: loginRequest,
110 | [Types.LOGIN_SUCCESS]: loginSuccess,
111 | [Types.LOGIN_FAILURE]: loginFailure,
112 | [Types.SIGNUP_REQUEST]: signupRequest,
113 | [Types.SIGNUP_SUCCESS]: signupSuccess,
114 | [Types.SIGNUP_FAILURE]: signupFailure,
115 | [Types.LOGOUT]: logout,
116 | [GlobalActionTypes.LOGOUT]: logout,
117 | [GlobalActionTypes.RESET]: reset,
118 | };
119 |
120 | export const reducer = createReducer(INITIAL_STATE, HANDLERS);
121 |
122 | export default { actionTypes, actionCreators, reducer, selectors };
123 |
--------------------------------------------------------------------------------
/app/features/quiz/components/Question.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import { AllHtmlEntities } from 'html-entities';
3 | import { View, Dimensions } from 'react-native';
4 | import styled, { css } from '@emotion/native';
5 |
6 | import { Colors } from '@app/core/constants/Theme';
7 | import SecondaryButton from '@app/core/components/SecondaryButton';
8 | import { H1, H2, SecondaryText } from '@app/core/components/Text';
9 | import { getAsset } from '@app/core/assets';
10 |
11 | const entities = new AllHtmlEntities();
12 |
13 | export default ({ data, onAnswerPress }) => {
14 | const [errorAnswer, setErrorAnswers] = useState([]);
15 | const [correctAnswer, setCorrectAnswer] = useState(-1);
16 | const handleAnswerPress = index => {
17 | if (index !== data.correctAnswerIndex) {
18 | setErrorAnswers(errorAnswer.concat(index));
19 | } else {
20 | setCorrectAnswer(data.correctAnswerIndex);
21 | }
22 | onAnswerPress(index);
23 | };
24 | return (
25 |
26 | {data.category}
27 | ({data.difficulty})
28 |
29 | {entities.decode(data.text)}
30 | {data.answers.map((a, i) => {
31 | const answer = entities.decode(a);
32 | const title = `${String.fromCharCode(
33 | 'A'.charCodeAt(0) + i
34 | )}. ${answer}`;
35 | const isError = errorAnswer.includes(i);
36 | const isCorrect = correctAnswer === i;
37 | return isError ? (
38 |
39 | ) : isCorrect ? (
40 |
41 | ) : (
42 | handleAnswerPress(i)}
46 | />
47 | );
48 | })}
49 |
50 | );
51 | };
52 |
53 | const Container = styled(View)`
54 | flex: 1;
55 | align-self: stretch;
56 | align-items: center;
57 | padding: 16px 20px 0;
58 | `;
59 | const Category = styled(H1)`
60 | text-align: center;
61 | `;
62 | const Difficulty = styled(SecondaryText)`
63 | margin-top: 4px;
64 | `;
65 | const { width: screenWidth } = Dimensions.get('window');
66 | const Line = styled(View)`
67 | width: ${Math.round(screenWidth * 0.6).toString()};
68 | height: 2;
69 | background-color: ${Colors.main};
70 | margin: 24px 0;
71 | `;
72 |
73 | const QuestionText = styled(H2)`
74 | color: ${Colors.textSecondary};
75 | align-self: stretch;
76 | margin-bottom: 24px;
77 | `;
78 | const AnswerButton = styled(SecondaryButton)`
79 | align-self: flex-start;
80 | min-height: 46;
81 | `;
82 | const ErrorAnswerButton = styled(AnswerButton)``;
83 | ErrorAnswerButton.defaultProps = {
84 | icon: getAsset('error'),
85 | iconStyle: css`
86 | tint-color: red;
87 | margin-right: 8px;
88 | width: 30;
89 | height: 30;
90 | `,
91 | labelStyle: css`
92 | color: red;
93 | `,
94 | };
95 | const CorrectAnswerButton = styled(AnswerButton)``;
96 | CorrectAnswerButton.defaultProps = {
97 | icon: getAsset('check'),
98 | iconStyle: css`
99 | tint-color: green;
100 | margin-right: 8px;
101 | width: 30;
102 | height: 30;
103 | `,
104 | labelStyle: css`
105 | color: green;
106 | `,
107 | };
108 |
--------------------------------------------------------------------------------
/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem http://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
34 |
35 | @rem Find java.exe
36 | if defined JAVA_HOME goto findJavaFromJavaHome
37 |
38 | set JAVA_EXE=java.exe
39 | %JAVA_EXE% -version >NUL 2>&1
40 | if "%ERRORLEVEL%" == "0" goto init
41 |
42 | echo.
43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
44 | echo.
45 | echo Please set the JAVA_HOME variable in your environment to match the
46 | echo location of your Java installation.
47 |
48 | goto fail
49 |
50 | :findJavaFromJavaHome
51 | set JAVA_HOME=%JAVA_HOME:"=%
52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
53 |
54 | if exist "%JAVA_EXE%" goto init
55 |
56 | echo.
57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
58 | echo.
59 | echo Please set the JAVA_HOME variable in your environment to match the
60 | echo location of your Java installation.
61 |
62 | goto fail
63 |
64 | :init
65 | @rem Get command-line arguments, handling Windows variants
66 |
67 | if not "%OS%" == "Windows_NT" goto win9xME_args
68 |
69 | :win9xME_args
70 | @rem Slurp the command line arguments.
71 | set CMD_LINE_ARGS=
72 | set _SKIP=2
73 |
74 | :win9xME_args_slurp
75 | if "x%~1" == "x" goto execute
76 |
77 | set CMD_LINE_ARGS=%*
78 |
79 | :execute
80 | @rem Setup the command line
81 |
82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
83 |
84 | @rem Execute Gradle
85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
86 |
87 | :end
88 | @rem End local scope for the variables with windows NT shell
89 | if "%ERRORLEVEL%"=="0" goto mainEnd
90 |
91 | :fail
92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
93 | rem the _cmd.exe /c_ return code!
94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
95 | exit /b 1
96 |
97 | :mainEnd
98 | if "%OS%"=="Windows_NT" endlocal
99 |
100 | :omega
101 |
--------------------------------------------------------------------------------
/app/features/quiz/screens/QuizScreen.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react';
2 | import { connect } from 'react-redux';
3 | import { View, Linking } from 'react-native';
4 | import styled from '@emotion/native';
5 |
6 | import Container from '@app/core/components/Container';
7 | import { SecondaryText, NormalText } from '@app/core/components/Text';
8 | import SecondaryButton from '@app/core/components/SecondaryButton';
9 |
10 | import { actionCreators, MODES } from '../redux';
11 | import Question from '../components/Question';
12 | import QuizLoading from '../components/QuizLoading';
13 | import QuizResult from '../components/QuizResult';
14 |
15 | const QuizScreen = ({
16 | mode,
17 | isQuestionsRequestActive,
18 | isSendResultsActive,
19 | isSendResultsSuccess,
20 | questionsRequest,
21 | questionIndex,
22 | questions,
23 | questionAnswered,
24 | score,
25 | sendResultsRequest,
26 | stopQuiz,
27 | }) => {
28 | useEffect(() => {
29 | if (mode === MODES.load && !isQuestionsRequestActive) {
30 | questionsRequest();
31 | } else if (
32 | mode === MODES.result &&
33 | !isSendResultsSuccess &&
34 | !isSendResultsActive
35 | ) {
36 | sendResultsRequest();
37 | }
38 | }, []);
39 |
40 | const [firstTry, setFirstTry] = useState(true);
41 | useEffect(() => {
42 | setFirstTry(true);
43 | }, [questionIndex]);
44 |
45 | const handleAnswerPress = index => {
46 | const question = questions[questionIndex];
47 | if (question.correctAnswerIndex === index) {
48 | setTimeout(() => {
49 | questionAnswered({ firstTry });
50 | }, 1000);
51 | } else {
52 | setFirstTry(false);
53 | }
54 | };
55 |
56 | const handleSourceLinkPress = () => {
57 | const url = 'https://opentdb.com';
58 | if (Linking.canOpenURL(url)) Linking.openURL(url);
59 | };
60 |
61 | return (
62 |
63 |
64 | {mode === MODES.quiz ? `Score: ${score}` : ''}
65 |
66 |
67 | {mode === MODES.load ? : null}
68 | {mode === MODES.quiz ? (
69 | <>
70 |
75 |
76 | {questionIndex + 1} of {questions.length}
77 |
78 | >
79 | ) : null}
80 | {mode === MODES.result ? : null}
81 |
82 | Questions from: https://opentdb.com
83 |
84 |
85 | );
86 | };
87 |
88 | export default connect(
89 | state => ({
90 | ...state.quiz,
91 | }),
92 | {
93 | questionsRequest: actionCreators.questionsRequest,
94 | questionAnswered: actionCreators.questionAnswered,
95 | stopQuiz: actionCreators.stopQuiz,
96 | sendResultsRequest: actionCreators.sendResultsRequest,
97 | }
98 | )(QuizScreen);
99 |
100 | const TopBar = styled(View)`
101 | padding: 8px 8px 0 16px;
102 | align-self: stretch;
103 | flex-direction: row;
104 | justify-content: space-between;
105 | `;
106 | const QuestionNumber = styled(NormalText)`
107 | margin-bottom: 12px;
108 | `;
109 | const Score = styled(NormalText)`
110 | margin-top: 8px;
111 | `;
112 | const StyledQuestionSource = styled(SecondaryText)`
113 | margin-bottom: 4px;
114 | `;
115 |
--------------------------------------------------------------------------------
/ios/AwesomeProject/Base.lproj/LaunchScreen.xib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
21 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/app/features/auth/sagas.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-console */
2 | import { takeLatest, call, select, put, spawn } from 'redux-saga/effects';
3 | import { saveStoreData, GlobalActionTypes } from '@app/core/store';
4 | import {
5 | login,
6 | signup,
7 | setToken,
8 | parseToken,
9 | } from '@app/core/services/userApi';
10 |
11 | import { actionTypes, selectors, actionCreators } from './redux';
12 |
13 | const STORAGE_KEY = 'app/auth';
14 |
15 | function* createSagas(modules) {
16 | function* loginRequest({ payload: { email, password } }) {
17 | try {
18 | const response = yield call(login, modules.userApi, email, password);
19 | if (response.ok) {
20 | yield call(commonSignupOrLogin, {
21 | response,
22 | successActionCreator: actionCreators.loginSuccess,
23 | });
24 | } else {
25 | yield put(
26 | actionCreators.loginFailure({
27 | error: response.data || response.problem || 'UNKNOWN_ERROR',
28 | })
29 | );
30 | }
31 | } catch (error) {
32 | yield put(actionCreators.loginFailure({ error }));
33 | console.warn(`Login error: ${error}`);
34 | }
35 | }
36 |
37 | function* signupRequest({ payload: { email, password } }) {
38 | try {
39 | const response = yield call(signup, modules.userApi, email, password);
40 | if (response.ok) {
41 | yield call(commonSignupOrLogin, {
42 | response,
43 | successActionCreator: actionCreators.signupSuccess,
44 | });
45 | } else {
46 | yield put(
47 | actionCreators.signupFailure({
48 | error: response.data || response.problem || 'UNKNOWN_ERROR',
49 | })
50 | );
51 | }
52 | } catch (error) {
53 | yield put(actionCreators.signupFailure({ error }));
54 | console.warn(`Signup error: ${error}`);
55 | }
56 | }
57 |
58 | function* commonSignupOrLogin({ response, successActionCreator }) {
59 | const token = response.data.accessToken;
60 | yield call(setToken, modules.userApi, token);
61 | const tokenData = yield call(parseToken, token);
62 | const userData = yield call(modules.sagas.user.userDataRequest, {
63 | userId: tokenData.userId,
64 | });
65 | if (userData) {
66 | yield put(successActionCreator({ token, ...tokenData }));
67 | modules.navigation.navigate('home');
68 | yield spawn(saveStoreData, modules.store);
69 | } else {
70 | throw Error('CANT_GET_USER_DATA');
71 | }
72 | }
73 |
74 | function* logout() {
75 | modules.navigation.navigate('auth');
76 | yield put({ type: GlobalActionTypes.RESET });
77 | yield spawn(saveStoreData, modules.store);
78 | }
79 |
80 | function* saveData() {
81 | try {
82 | const data = yield select(selectors.rehydration);
83 | yield call(modules.keyValueStorage.set, STORAGE_KEY, data);
84 | } catch (e) {
85 | console.warn(`Can't save auth: ${e}`);
86 | }
87 | }
88 |
89 | function* loadData() {
90 | try {
91 | const data = yield call(modules.keyValueStorage.get, STORAGE_KEY) || {};
92 | yield put(actionCreators.rehydration({ data }));
93 | if (data.token) {
94 | yield call(setToken, modules.userApi, data.token);
95 | }
96 | } catch (e) {
97 | console.warn(`Can't load auth: ${e}`);
98 | }
99 | }
100 |
101 | function* reset() {
102 | try {
103 | yield call(modules.keyValueStorage.remove, STORAGE_KEY);
104 | } catch (e) {
105 | console.warn(`Can't reset auth: ${e}`);
106 | }
107 | }
108 |
109 | yield call(loadData);
110 | function* main() {
111 | yield takeLatest(actionTypes.LOGIN_REQUEST, loginRequest);
112 | yield takeLatest(actionTypes.SIGNUP_REQUEST, signupRequest);
113 | yield takeLatest(actionTypes.LOGOUT, logout);
114 | yield takeLatest(GlobalActionTypes.LOGOUT, logout);
115 | yield takeLatest(GlobalActionTypes.SAVE_DATA, saveData);
116 | yield takeLatest(GlobalActionTypes.RESET, reset);
117 | }
118 | return { main };
119 | }
120 |
121 | export default createSagas;
122 |
--------------------------------------------------------------------------------
/app/features/quiz/redux.js:
--------------------------------------------------------------------------------
1 | import { createReducer, createActions } from 'reduxsauce';
2 | import { mapAllToUndefined } from '@app/core/utils';
3 | import { GlobalActionTypes } from '@app/core/store';
4 |
5 | import { randomizedAnswers, scoreForQuestion } from './utils';
6 |
7 | const { Types, Creators } = createActions(
8 | {
9 | rehydration: ['payload'],
10 |
11 | questionsRequest: ['payload'],
12 | questionsSuccess: ['payload'],
13 | questionsFailure: ['payload'],
14 |
15 | questionAnswered: ['payload'],
16 |
17 | sendResultsRequest: ['payload'],
18 | sendResultsSuccess: [],
19 | sendResultsFailure: ['payload'],
20 |
21 | stopQuiz: [],
22 | reset: [],
23 | },
24 | { prefix: 'APP/QUIZ/' }
25 | );
26 |
27 | export const actionTypes = Types;
28 | export const actionCreators = Creators;
29 |
30 | export const MODES = {
31 | load: 'MODE_LOAD',
32 | quiz: 'MODE_QUIZ',
33 | result: 'MODE_RESULT',
34 | };
35 |
36 | const INITIAL_STATE_PERSISTENT = {
37 | isActive: false,
38 | mode: MODES.load,
39 | questions: [],
40 | questionIndex: 0,
41 | score: 0,
42 | isSendResultsSuccess: false,
43 | };
44 |
45 | const INITIAL_STATE_TRANSIENT = {
46 | isQuestionsRequestActive: false,
47 | isSendResultsActive: false,
48 | questionsError: null,
49 | sendResultsError: null,
50 | };
51 |
52 | const INITIAL_STATE = {
53 | ...INITIAL_STATE_PERSISTENT,
54 | ...INITIAL_STATE_TRANSIENT,
55 | };
56 |
57 | export const selectors = {
58 | rehydration: state => ({
59 | ...state.quiz,
60 | ...mapAllToUndefined(INITIAL_STATE_TRANSIENT),
61 | }),
62 | };
63 |
64 | const rehydration = (state = INITIAL_STATE, { payload: { data } }) => ({
65 | ...state,
66 | ...data,
67 | });
68 |
69 | const questionsRequest = (state = INITIAL_STATE) => {
70 | return {
71 | ...state,
72 | isActive: true,
73 | mode: MODES.load,
74 | questions: [],
75 | questionsError: null,
76 | isQuestionsRequestActive: true,
77 | };
78 | };
79 |
80 | const questionsSuccess = (
81 | state = INITIAL_STATE,
82 | { payload: { questions } }
83 | ) => {
84 | return {
85 | ...state,
86 | questions: questions.map(q => ({
87 | category: q.category,
88 | difficulty: q.difficulty,
89 | text: q.question,
90 | ...randomizedAnswers(q),
91 | })),
92 | mode: MODES.quiz,
93 | questionsError: null,
94 | isQuestionsRequestActive: false,
95 | };
96 | };
97 |
98 | const questionsFailure = (state = INITIAL_STATE, { payload: { error } }) => {
99 | return { ...state, questionsError: error, isQuestionsRequestActive: false };
100 | };
101 |
102 | const questionAnswered = (
103 | state = INITIAL_STATE,
104 | { payload: { firstTry } }
105 | ) => ({
106 | ...state,
107 | score:
108 | state.score +
109 | (firstTry ? scoreForQuestion(state.questions[state.questionIndex]) : 0),
110 | questionIndex: state.questionIndex + 1,
111 | mode:
112 | state.questionIndex < state.questions.length - 1
113 | ? MODES.quiz
114 | : MODES.result,
115 | });
116 |
117 | const sendResultsRequest = (state = INITIAL_STATE) => {
118 | return {
119 | ...state,
120 | sendResultsError: null,
121 | isSendResultsActive: true,
122 | };
123 | };
124 |
125 | const sendResultsSuccess = (state = INITIAL_STATE) => {
126 | return {
127 | ...state,
128 | sendResultsError: null,
129 | isSendResultsActive: false,
130 | isSendResultsSuccess: true,
131 | };
132 | };
133 |
134 | const sendResultsFailure = (state = INITIAL_STATE, { payload: { error } }) => {
135 | return { ...state, sendResultsError: error, isSendResultsActive: false };
136 | };
137 |
138 | const reset = () => {
139 | return INITIAL_STATE;
140 | };
141 |
142 | const HANDLERS = {
143 | [Types.REHYDRATION]: rehydration,
144 | [Types.QUESTIONS_REQUEST]: questionsRequest,
145 | [Types.QUESTIONS_SUCCESS]: questionsSuccess,
146 | [Types.QUESTIONS_FAILURE]: questionsFailure,
147 | [Types.QUESTION_ANSWERED]: questionAnswered,
148 | [Types.SEND_RESULTS_REQUEST]: sendResultsRequest,
149 | [Types.SEND_RESULTS_SUCCESS]: sendResultsSuccess,
150 | [Types.SEND_RESULTS_FAILURE]: sendResultsFailure,
151 | [Types.RESET]: reset,
152 | [GlobalActionTypes.RESET]: reset,
153 | };
154 |
155 | export const reducer = createReducer(INITIAL_STATE, HANDLERS);
156 |
157 | export default { actionTypes, actionCreators, reducer, selectors, MODES };
158 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Intro
2 |
3 | This is an example app showing how to structure React Native application in a 'feature-oriented' way.
4 |
5 | # Basic idea
6 |
7 | The idea of the architecture is to separate the core of the application from its features. So in a way it's possible to see what the app can do by looking at the file structure of the app.
8 |
9 | In this example we have:
10 |
11 | - app: // so this is some app, good start
12 | - core: // ok, it has some core, let's skip it for a while
13 | - features: // alright, it can do smth, let's see what it is
14 | - auth: // so there is some authentication in the app
15 | - dashboard: // and there is some dashboard, cool
16 | - ...
17 | - quiz: // ok, so there is a quiz
18 | - user: // and there are users in the app
19 |
20 | So it's possible to see from this structure that basically this is the app where users can authenticate and do some quizzes.
21 |
22 | Other benefits of this modularity over splitting only by the module type (Components/Screens/Routes/Actions etc in the root folder):
23 |
24 | - better code discoverability - it's easier to locate things, what is located where
25 | - better encapsulation - no need for the code used only for one feature to pile in the common place, no need for other modules to know too much about each other or too easily include code from each other
26 | - better testability - the more separate the components are, the easier to test them independently from each other
27 | - easier to work for a team - different people can work on different features without interfering much with each other's work
28 | - better reusability, the core can be reused for other apps, also features can be detached more or less freely, considering that the core will stay the same or similar
29 |
30 | Each feature has a common interface by which it shares itself with the app:
31 |
32 | - key - a unique key by which it will be identified (only 1 required export)
33 | - screens - an object of name->screen to share the screens (if there are any)
34 | - redux - action types / feature reducer / action creators (Redux stuff)
35 | - createSagas - a function to initialize sagas of the feature (for the logic)
36 |
37 | Inside of the feature it can have its own components, screens, routes, etc etc, the structure can depend on requirements and complexity of the feature.
38 |
39 | # This is not a complete boilerplate
40 |
41 | While this app can be used as a starting point for a new, this example isn't a complete example of what could be called app's boilerplate. Obvious missing parts are localization and tests. Also theming can be improved.
42 |
43 | # Tech stack
44 |
45 | Frontend:
46 |
47 | - [React Native](https://facebook.github.io/react-native/)
48 | - [Redux](https://redux.js.org)
49 | - [Redux Sagas](https://redux-saga.js.org)
50 | - [Axios](https://github.com/axios/axios)
51 |
52 | Backend:
53 |
54 | - a simple [json-server](https://github.com/typicode/json-server) + [json-server-auth](https://github.com/jeremyben/json-server-auth)
55 |
56 | # How to run
57 |
58 | Run backend from another terminal:
59 |
60 | ```sh
61 | cd backend && yarn install && yarn watch
62 | ```
63 |
64 | React Native packager:
65 |
66 | ```sh
67 | yarn install
68 | yarn start
69 | ```
70 |
71 | Run the app:
72 |
73 | ```sh
74 | react-native run-ios
75 | react-native run-android
76 | ```
77 |
78 | There is a test user:
79 |
80 | ```
81 | email: 1@1.com
82 | password: test
83 | ```
84 |
85 | Or you can use Signup screen to create the user.
86 |
87 | # App demo
88 |
89 | 
90 |
91 | # Known issues
92 |
93 | - The auth token is valid for 1 hr, without a way to renew, so the user will be logged out when a request will be made after the token will expire on the server.
94 |
95 | # What could be improved
96 |
97 | - In the current implementation using of Redux / Redux Saga is leaking in the number of places. Ideally a feature could use any state management it would find appropriate and it could provide some of its data / behavior on request through a common interface. This is a tradeoff of having less complexity vs having a cleaner solution.
98 |
99 | # Attribution
100 |
101 | Icon images derived from the Font Awesome:
102 | https://fontawesome.com/license
103 |
104 | Questions are fetched from:
105 | https://opentdb.com
106 |
107 | The idea "to be able to look at the folder structure and understand what this app can do" came from watching [one of Dr. Martin's talks](https://www.youtube.com/results?search_query=uncle+bob+martin+clean+code+talk)
108 |
--------------------------------------------------------------------------------
/app/features/quiz/sagas.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-console */
2 | import {
3 | takeLatest,
4 | call,
5 | select,
6 | put,
7 | spawn,
8 | delay,
9 | } from 'redux-saga/effects';
10 | import AlertAsync from 'react-native-alert-async';
11 |
12 | import { saveStoreData, GlobalActionTypes } from '@app/core/store';
13 | import { getQuestions } from '@app/core/services/questionsApi';
14 |
15 | import { actionTypes, selectors, actionCreators, MODES } from './redux';
16 | import { QUIZ_QUESTIONS_COUNT } from './constants';
17 |
18 | const STORAGE_KEY = 'app/quiz';
19 |
20 | function* createSagas(modules) {
21 | function* questionsRequest() {
22 | try {
23 | const response = yield call(
24 | getQuestions,
25 | modules.questionsApi,
26 | QUIZ_QUESTIONS_COUNT
27 | );
28 | const isQuizActive = yield select(store => store.quiz.isActive);
29 | if (!isQuizActive) {
30 | return;
31 | }
32 | if (response.ok && response.data) {
33 | const code = response.data.response_code;
34 | if (code === 0) {
35 | yield put(
36 | actionCreators.questionsSuccess({
37 | questions: response.data.results,
38 | })
39 | );
40 | } else {
41 | throw Error(`Unhandled API response code: ${code}`);
42 | }
43 | yield spawn(saveStoreData, modules.store);
44 | } else {
45 | throw Error(response.problem || 'UNKNOWN_ERROR');
46 | }
47 | } catch (error) {
48 | yield put(actionCreators.questionsFailure({ error }));
49 | console.warn(`Questions error: ${error}`);
50 | }
51 | }
52 |
53 | function* questionAnswered() {
54 | yield spawn(saveStoreData, modules.store);
55 | const state = yield select(store => store.quiz);
56 | if (state.questionIndex === state.questions.length) {
57 | yield put(actionCreators.sendResultsRequest());
58 | }
59 | }
60 |
61 | function* sendResultsRequest() {
62 | try {
63 | const state = yield select(store => store.quiz);
64 | yield call(modules.sagas.user.increaseQuizStats, {
65 | score: state.score,
66 | quizCount: 1,
67 | });
68 | const isQuizActive = yield select(store => store.quiz.isActive);
69 | if (!isQuizActive) {
70 | return;
71 | }
72 | yield put(actionCreators.sendResultsSuccess());
73 | yield spawn(saveStoreData, modules.store);
74 | } catch (error) {
75 | yield put(actionCreators.sendResultsFailure({ error }));
76 | console.warn('Send results error:', error);
77 | }
78 | }
79 |
80 | function* stopQuiz() {
81 | const state = yield select(store => store.quiz);
82 | let doStop = state.isSendResultsSuccess || state.mode === MODES.load;
83 | if (!doStop) {
84 | doStop = yield call(
85 | AlertAsync,
86 | 'Are you sure?',
87 | 'Your scores will be lost',
88 | [
89 | { text: 'Yes', onPress: () => true },
90 | { text: 'No', onPress: () => false },
91 | ],
92 | {
93 | cancelable: true,
94 | onDismiss: () => false,
95 | }
96 | );
97 | }
98 | if (doStop) {
99 | yield call(modules.navigation.goBack);
100 | yield delay(500); // to wait navigation animation
101 | yield put(actionCreators.reset());
102 | yield spawn(saveStoreData, modules.store);
103 | }
104 | }
105 |
106 | function* saveData() {
107 | try {
108 | const data = yield select(selectors.rehydration);
109 | yield call(modules.keyValueStorage.set, STORAGE_KEY, data);
110 | } catch (e) {
111 | console.warn(`Can't save quiz: ${e}`);
112 | }
113 | }
114 |
115 | function* loadData() {
116 | try {
117 | const data = yield call(modules.keyValueStorage.get, STORAGE_KEY) || {};
118 | yield put(actionCreators.rehydration({ data }));
119 | } catch (e) {
120 | console.warn(`Can't load quiz: ${e}`);
121 | }
122 | }
123 |
124 | function* reset() {
125 | try {
126 | yield call(modules.keyValueStorage.remove, STORAGE_KEY);
127 | } catch (e) {
128 | console.warn(`Can't reset quiz: ${e}`);
129 | }
130 | }
131 |
132 | yield call(loadData);
133 | function* main() {
134 | yield takeLatest(actionTypes.QUESTIONS_REQUEST, questionsRequest);
135 | yield takeLatest(actionTypes.QUESTION_ANSWERED, questionAnswered);
136 | yield takeLatest(actionTypes.SEND_RESULTS_REQUEST, sendResultsRequest);
137 | yield takeLatest(actionTypes.STOP_QUIZ, stopQuiz);
138 | yield takeLatest(GlobalActionTypes.SAVE_DATA, saveData);
139 | yield takeLatest(GlobalActionTypes.RESET, reset);
140 | }
141 | return { main };
142 | }
143 |
144 | export default createSagas;
145 |
--------------------------------------------------------------------------------
/ios/AwesomeProject.xcodeproj/xcshareddata/xcschemes/AwesomeProject.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
29 |
35 |
36 |
37 |
43 |
49 |
50 |
51 |
52 |
53 |
58 |
59 |
61 |
67 |
68 |
69 |
70 |
71 |
77 |
78 |
79 |
80 |
81 |
82 |
92 |
94 |
100 |
101 |
102 |
103 |
104 |
105 |
111 |
113 |
119 |
120 |
121 |
122 |
124 |
125 |
128 |
129 |
130 |
--------------------------------------------------------------------------------
/ios/AwesomeProject.xcodeproj/xcshareddata/xcschemes/AwesomeProject-tvOS.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
29 |
35 |
36 |
37 |
43 |
49 |
50 |
51 |
52 |
53 |
58 |
59 |
61 |
67 |
68 |
69 |
70 |
71 |
77 |
78 |
79 |
80 |
81 |
82 |
92 |
94 |
100 |
101 |
102 |
103 |
104 |
105 |
111 |
113 |
119 |
120 |
121 |
122 |
124 |
125 |
128 |
129 |
130 |
--------------------------------------------------------------------------------
/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 | # Determine the Java command to use to start the JVM.
86 | if [ -n "$JAVA_HOME" ] ; then
87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
88 | # IBM's JDK on AIX uses strange locations for the executables
89 | JAVACMD="$JAVA_HOME/jre/sh/java"
90 | else
91 | JAVACMD="$JAVA_HOME/bin/java"
92 | fi
93 | if [ ! -x "$JAVACMD" ] ; then
94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
95 |
96 | Please set the JAVA_HOME variable in your environment to match the
97 | location of your Java installation."
98 | fi
99 | else
100 | JAVACMD="java"
101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
102 |
103 | Please set the JAVA_HOME variable in your environment to match the
104 | location of your Java installation."
105 | fi
106 |
107 | # Increase the maximum file descriptors if we can.
108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
109 | MAX_FD_LIMIT=`ulimit -H -n`
110 | if [ $? -eq 0 ] ; then
111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
112 | MAX_FD="$MAX_FD_LIMIT"
113 | fi
114 | ulimit -n $MAX_FD
115 | if [ $? -ne 0 ] ; then
116 | warn "Could not set maximum file descriptor limit: $MAX_FD"
117 | fi
118 | else
119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
120 | fi
121 | fi
122 |
123 | # For Darwin, add options to specify how the application appears in the dock
124 | if $darwin; then
125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
126 | fi
127 |
128 | # For Cygwin, switch paths to Windows format before running java
129 | if $cygwin ; then
130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
132 | JAVACMD=`cygpath --unix "$JAVACMD"`
133 |
134 | # We build the pattern for arguments to be converted via cygpath
135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
136 | SEP=""
137 | for dir in $ROOTDIRSRAW ; do
138 | ROOTDIRS="$ROOTDIRS$SEP$dir"
139 | SEP="|"
140 | done
141 | OURCYGPATTERN="(^($ROOTDIRS))"
142 | # Add a user-defined pattern to the cygpath arguments
143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
145 | fi
146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
147 | i=0
148 | for arg in "$@" ; do
149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
151 |
152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
154 | else
155 | eval `echo args$i`="\"$arg\""
156 | fi
157 | i=$((i+1))
158 | done
159 | case $i in
160 | (0) set -- ;;
161 | (1) set -- "$args0" ;;
162 | (2) set -- "$args0" "$args1" ;;
163 | (3) set -- "$args0" "$args1" "$args2" ;;
164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
170 | esac
171 | fi
172 |
173 | # Escape application args
174 | save () {
175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
176 | echo " "
177 | }
178 | APP_ARGS=$(save "$@")
179 |
180 | # Collect all arguments for the java command, following the shell quoting and substitution rules
181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
182 |
183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
185 | cd "$(dirname "$0")"
186 | fi
187 |
188 | exec "$JAVACMD" "$@"
189 |
--------------------------------------------------------------------------------
/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | import com.android.build.OutputFile
4 |
5 | /**
6 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
7 | * and bundleReleaseJsAndAssets).
8 | * These basically call `react-native bundle` with the correct arguments during the Android build
9 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
10 | * bundle directly from the development server. Below you can see all the possible configurations
11 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
12 | * `apply from: "../../node_modules/react-native/react.gradle"` line.
13 | *
14 | * project.ext.react = [
15 | * // the name of the generated asset file containing your JS bundle
16 | * bundleAssetName: "index.android.bundle",
17 | *
18 | * // the entry file for bundle generation
19 | * entryFile: "index.android.js",
20 | *
21 | * // whether to bundle JS and assets in debug mode
22 | * bundleInDebug: false,
23 | *
24 | * // whether to bundle JS and assets in release mode
25 | * bundleInRelease: true,
26 | *
27 | * // whether to bundle JS and assets in another build variant (if configured).
28 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
29 | * // The configuration property can be in the following formats
30 | * // 'bundleIn${productFlavor}${buildType}'
31 | * // 'bundleIn${buildType}'
32 | * // bundleInFreeDebug: true,
33 | * // bundleInPaidRelease: true,
34 | * // bundleInBeta: true,
35 | *
36 | * // whether to disable dev mode in custom build variants (by default only disabled in release)
37 | * // for example: to disable dev mode in the staging build type (if configured)
38 | * devDisabledInStaging: true,
39 | * // The configuration property can be in the following formats
40 | * // 'devDisabledIn${productFlavor}${buildType}'
41 | * // 'devDisabledIn${buildType}'
42 | *
43 | * // the root of your project, i.e. where "package.json" lives
44 | * root: "../../",
45 | *
46 | * // where to put the JS bundle asset in debug mode
47 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
48 | *
49 | * // where to put the JS bundle asset in release mode
50 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
51 | *
52 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
53 | * // require('./image.png')), in debug mode
54 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
55 | *
56 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
57 | * // require('./image.png')), in release mode
58 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
59 | *
60 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
61 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
62 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
63 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
64 | * // for example, you might want to remove it from here.
65 | * inputExcludes: ["android/**", "ios/**"],
66 | *
67 | * // override which node gets called and with what additional arguments
68 | * nodeExecutableAndArgs: ["node"],
69 | *
70 | * // supply additional arguments to the packager
71 | * extraPackagerArgs: []
72 | * ]
73 | */
74 |
75 | project.ext.react = [
76 | entryFile: "index.js"
77 | ]
78 |
79 | apply from: "../../node_modules/react-native/react.gradle"
80 |
81 | /**
82 | * Set this to true to create two separate APKs instead of one:
83 | * - An APK that only works on ARM devices
84 | * - An APK that only works on x86 devices
85 | * The advantage is the size of the APK is reduced by about 4MB.
86 | * Upload all the APKs to the Play Store and people will download
87 | * the correct one based on the CPU architecture of their device.
88 | */
89 | def enableSeparateBuildPerCPUArchitecture = false
90 |
91 | /**
92 | * Run Proguard to shrink the Java bytecode in release builds.
93 | */
94 | def enableProguardInReleaseBuilds = false
95 |
96 | android {
97 | compileSdkVersion rootProject.ext.compileSdkVersion
98 |
99 | compileOptions {
100 | sourceCompatibility JavaVersion.VERSION_1_8
101 | targetCompatibility JavaVersion.VERSION_1_8
102 | }
103 |
104 | defaultConfig {
105 | applicationId "com.awesomeproject"
106 | minSdkVersion rootProject.ext.minSdkVersion
107 | targetSdkVersion rootProject.ext.targetSdkVersion
108 | versionCode 1
109 | versionName "1.0"
110 | }
111 | splits {
112 | abi {
113 | reset()
114 | enable enableSeparateBuildPerCPUArchitecture
115 | universalApk false // If true, also generate a universal APK
116 | include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
117 | }
118 | }
119 | buildTypes {
120 | release {
121 | minifyEnabled enableProguardInReleaseBuilds
122 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
123 | }
124 | }
125 | // applicationVariants are e.g. debug, release
126 | applicationVariants.all { variant ->
127 | variant.outputs.each { output ->
128 | // For each separate APK per architecture, set a unique version code as described here:
129 | // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
130 | def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4]
131 | def abi = output.getFilter(OutputFile.ABI)
132 | if (abi != null) { // null for the universal-debug, universal-release variants
133 | output.versionCodeOverride =
134 | versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
135 | }
136 | }
137 | }
138 | }
139 |
140 | dependencies {
141 | implementation project(':react-native-reanimated')
142 | implementation project(':react-native-gesture-handler')
143 | implementation project(':@react-native-community_async-storage')
144 | implementation fileTree(dir: "libs", include: ["*.jar"])
145 | implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
146 | implementation "com.facebook.react:react-native:+" // From node_modules
147 | }
148 |
149 | // Run this once to be able to run the application with BUCK
150 | // puts all compile dependencies into folder libs for BUCK to use
151 | task copyDownloadableDepsToLibs(type: Copy) {
152 | from configurations.compile
153 | into 'libs'
154 | }
155 |
--------------------------------------------------------------------------------