Repository: Mindinventory/react-native-boilerplate
Branch: master
Commit: 5c96f4ee0966
Files: 275
Total size: 303.6 KB
Directory structure:
gitextract_5m3lqord/
├── .gitignore
├── .husky/
│ ├── commit-msg
│ └── pre-commit
├── .npmignore
├── .vscode/
│ └── settings.json
├── LICENSE
├── README.md
├── bin/
│ └── index.js
├── commitlint.config.js
├── package.json
├── script.js
├── src/
│ ├── dependencyHandler.js
│ ├── gitHandler.js
│ ├── helper.js
│ ├── projectSetup.js
│ └── prompts.js
├── template.config.js
└── templates/
├── CliTemplate/
│ ├── .bundle/
│ │ └── config
│ ├── .eslintrc.js
│ ├── .gitignore
│ ├── .husky/
│ │ ├── commit-msg
│ │ └── pre-commit
│ ├── .node-version
│ ├── .prettierrc.js
│ ├── .svgrrc
│ ├── .vscode/
│ │ └── settings.json
│ ├── .watchmanconfig
│ ├── .yarnrc.yml
│ ├── App.tsx
│ ├── Gemfile
│ ├── README.md
│ ├── __tests__/
│ │ └── App.test.tsx
│ ├── android/
│ │ ├── app/
│ │ │ ├── build.gradle
│ │ │ ├── debug.keystore
│ │ │ ├── proguard-rules.pro
│ │ │ └── src/
│ │ │ ├── debug/
│ │ │ │ └── AndroidManifest.xml
│ │ │ └── main/
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── java/
│ │ │ │ └── com/
│ │ │ │ └── miboilerplate/
│ │ │ │ ├── MainActivity.kt
│ │ │ │ └── MainApplication.kt
│ │ │ └── res/
│ │ │ ├── drawable/
│ │ │ │ └── rn_edit_text_material.xml
│ │ │ └── values/
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ ├── build.gradle
│ │ ├── gradle/
│ │ │ └── wrapper/
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ │ ├── gradle.properties
│ │ ├── gradlew
│ │ ├── gradlew.bat
│ │ └── settings.gradle
│ ├── app.json
│ ├── babel.config.js
│ ├── blueprints/
│ │ ├── Button/
│ │ │ └── Button.tsx
│ │ ├── Image/
│ │ │ └── Image.tsx
│ │ ├── Indicator/
│ │ │ └── Indicator.tsx
│ │ ├── Text/
│ │ │ └── Text.tsx
│ │ ├── TextInput/
│ │ │ ├── Input.tsx
│ │ │ ├── TextInput.tsx
│ │ │ ├── TextInputProps.ts
│ │ │ └── index.tsx
│ │ └── index.ts
│ ├── commitlint.config.js
│ ├── declarations.d.ts
│ ├── env.d.ts
│ ├── index.js
│ ├── ios/
│ │ ├── .xcode.env
│ │ ├── MIBoilerplate/
│ │ │ ├── AppDelegate.h
│ │ │ ├── AppDelegate.mm
│ │ │ ├── Images.xcassets/
│ │ │ │ ├── AppIcon.appiconset/
│ │ │ │ │ └── Contents.json
│ │ │ │ └── Contents.json
│ │ │ ├── Info.plist
│ │ │ ├── LaunchScreen.storyboard
│ │ │ ├── PrivacyInfo.xcprivacy
│ │ │ └── main.m
│ │ ├── MIBoilerplate.xcodeproj/
│ │ │ ├── project.pbxproj
│ │ │ ├── project.xcworkspace/
│ │ │ │ └── xcshareddata/
│ │ │ │ └── IDEWorkspaceChecks.plist
│ │ │ └── xcshareddata/
│ │ │ └── xcschemes/
│ │ │ └── MIBoilerplate.xcscheme
│ │ ├── MIBoilerplate.xcworkspace/
│ │ │ ├── contents.xcworkspacedata
│ │ │ └── xcshareddata/
│ │ │ └── IDEWorkspaceChecks.plist
│ │ ├── MIBoilerplateTests/
│ │ │ ├── Info.plist
│ │ │ └── MIBoilerplateTests.m
│ │ └── Podfile
│ ├── jest.config.js
│ ├── metro.config.js
│ ├── package.json
│ ├── react-native.config.js
│ ├── scripts/
│ │ ├── generateScreenFile.js
│ │ ├── icons.js
│ │ ├── images.js
│ │ ├── refresh.sh
│ │ └── svgIcons.js
│ ├── src/
│ │ ├── MainApp.tsx
│ │ ├── assets/
│ │ │ ├── icons/
│ │ │ │ └── index.ts
│ │ │ ├── images/
│ │ │ │ └── index.ts
│ │ │ ├── index.ts
│ │ │ └── svgIcons/
│ │ │ └── index.ts
│ │ ├── components/
│ │ │ ├── AppIcon/
│ │ │ │ └── AppIcon.tsx
│ │ │ ├── AppImage/
│ │ │ │ └── AppImage.tsx
│ │ │ ├── BaseLayout/
│ │ │ │ └── BaseLayout.tsx
│ │ │ └── index.ts
│ │ ├── constants/
│ │ │ ├── config.ts
│ │ │ ├── index.ts
│ │ │ ├── platform.ts
│ │ │ └── storageKeys.ts
│ │ ├── context/
│ │ │ ├── LocalizationContext.tsx
│ │ │ ├── ThemeContext.tsx
│ │ │ ├── content.ts
│ │ │ ├── context.ts
│ │ │ ├── index.ts
│ │ │ └── storage.ts
│ │ ├── hooks/
│ │ │ ├── index.ts
│ │ │ ├── useBackHandler.ts
│ │ │ ├── useDebounce.ts
│ │ │ ├── useIsFirstRender.ts
│ │ │ ├── useIsMounted.ts
│ │ │ └── useTimer.ts
│ │ ├── i18n/
│ │ │ ├── index.ts
│ │ │ └── locales/
│ │ │ ├── en.json
│ │ │ └── hi.json
│ │ ├── navigation/
│ │ │ ├── AppNavigation.tsx
│ │ │ ├── ForceupdateStack.tsx
│ │ │ ├── appNavigation.type.ts
│ │ │ └── withNavigation.ts
│ │ ├── screens/
│ │ │ ├── ErrorBoundary/
│ │ │ │ └── ErrorBoundary.tsx
│ │ │ ├── ForceUpdate/
│ │ │ │ ├── ForceUpdate.style.ts
│ │ │ │ ├── ForceUpdateScreen.tsx
│ │ │ │ └── useForceUpdate.ts
│ │ │ ├── Login/
│ │ │ │ ├── Login.style.ts
│ │ │ │ ├── LoginScreen.tsx
│ │ │ │ └── useLogin.ts
│ │ │ ├── NetworkLogger/
│ │ │ │ └── NetworkLoggerScreen.tsx
│ │ │ ├── NewsDetail/
│ │ │ │ ├── NewsDetail.style.ts
│ │ │ │ ├── NewsDetailScreen.tsx
│ │ │ │ └── useNewsDetail.ts
│ │ │ ├── NewsList/
│ │ │ │ ├── NewsList.style.ts
│ │ │ │ ├── NewsListScreen.tsx
│ │ │ │ └── useNewsList.ts
│ │ │ ├── Setting/
│ │ │ │ ├── Setting.style.ts
│ │ │ │ ├── SettingScreen.tsx
│ │ │ │ └── useSetting.ts
│ │ │ └── index.ts
│ │ ├── services/
│ │ │ ├── apiHandler.ts
│ │ │ ├── appServices.ts
│ │ │ ├── appServices.type.ts
│ │ │ ├── appServicesEndPoints.ts
│ │ │ ├── commercial/
│ │ │ │ ├── adapters/
│ │ │ │ │ └── response/
│ │ │ │ │ ├── getNewsCommercialResponseAdapter.ts
│ │ │ │ │ ├── getUserCommercialResponseAdapter.ts
│ │ │ │ │ └── postLoginCommercialResponseAdapter.ts
│ │ │ │ └── dtos/
│ │ │ │ ├── NewsResponseDTO.ts
│ │ │ │ └── UserResponseDTO.ts
│ │ │ ├── index.ts
│ │ │ ├── models/
│ │ │ │ ├── index.ts
│ │ │ │ ├── login.ts
│ │ │ │ ├── news.ts
│ │ │ │ ├── unknown.ts
│ │ │ │ └── user.ts
│ │ │ └── serviceAdapter.ts
│ │ ├── store/
│ │ │ ├── index.ts
│ │ │ ├── observers/
│ │ │ │ ├── index.ts
│ │ │ │ ├── news.ts
│ │ │ │ └── users.ts
│ │ │ └── reducers/
│ │ │ ├── index.ts
│ │ │ ├── newsData.ts
│ │ │ └── usersData.ts
│ │ └── utils/
│ │ ├── color.ts
│ │ ├── dimensions.ts
│ │ ├── helper.ts
│ │ └── index.ts
│ └── tsconfig.json
└── ExpoTemplate/
├── .eslintrc.js
├── .gitignore
├── .husky/
│ ├── commit-msg
│ └── pre-commit
├── .prettierrc.js
├── .vscode/
│ └── settings.json
├── .yarnrc.yml
├── App.tsx
├── app.json
├── babel.config.js
├── blueprints/
│ ├── Button/
│ │ └── Button.tsx
│ ├── Image/
│ │ └── Image.tsx
│ ├── Indicator/
│ │ └── Indicator.tsx
│ ├── Text/
│ │ └── Text.tsx
│ ├── TextInput/
│ │ ├── Input.tsx
│ │ ├── TextInput.tsx
│ │ ├── TextInputProps.ts
│ │ └── index.tsx
│ └── index.ts
├── commitlint.config.js
├── env.d.ts
├── jest.config.js
├── metro.config.js
├── package.json
├── scripts/
│ ├── generateScreenFile.js
│ ├── icons.js
│ ├── images.js
│ ├── refresh.sh
│ └── svgIcons.js
├── src/
│ ├── MainApp.tsx
│ ├── assets/
│ │ ├── icons/
│ │ │ └── index.ts
│ │ ├── images/
│ │ │ └── index.ts
│ │ ├── index.ts
│ │ └── svgIcons/
│ │ └── index.ts
│ ├── components/
│ │ ├── AppIcon/
│ │ │ └── AppIcon.tsx
│ │ ├── AppImage/
│ │ │ └── AppImage.tsx
│ │ ├── BaseLayout/
│ │ │ └── BaseLayout.tsx
│ │ └── index.ts
│ ├── constants/
│ │ ├── config.ts
│ │ ├── index.ts
│ │ ├── platform.ts
│ │ └── storageKeys.ts
│ ├── context/
│ │ ├── LocalizationContext.tsx
│ │ ├── ThemeContext.tsx
│ │ ├── content.ts
│ │ ├── context.ts
│ │ ├── index.ts
│ │ └── storage.ts
│ ├── hooks/
│ │ ├── index.ts
│ │ ├── useBackHandler.ts
│ │ ├── useDebounce.ts
│ │ ├── useIsFirstRender.ts
│ │ ├── useIsMounted.ts
│ │ └── useTimer.ts
│ ├── i18n/
│ │ ├── index.ts
│ │ └── locales/
│ │ ├── en.json
│ │ └── hi.json
│ ├── navigation/
│ │ ├── AppNavigation.tsx
│ │ ├── ForceupdateStack.tsx
│ │ ├── appNavigation.type.ts
│ │ └── withNavigation.ts
│ ├── screens/
│ │ ├── ErrorBoundary/
│ │ │ └── ErrorBoundary.tsx
│ │ ├── ForceUpdate/
│ │ │ ├── ForceUpdate.style.ts
│ │ │ ├── ForceUpdateScreen.tsx
│ │ │ └── useForceUpdate.ts
│ │ ├── Login/
│ │ │ ├── Login.style.ts
│ │ │ ├── LoginScreen.tsx
│ │ │ └── useLogin.ts
│ │ ├── NetworkLogger/
│ │ │ └── NetworkLoggerScreen.tsx
│ │ ├── NewsDetail/
│ │ │ ├── NewsDetail.style.ts
│ │ │ ├── NewsDetailScreen.tsx
│ │ │ └── useNewsDetail.ts
│ │ ├── NewsList/
│ │ │ ├── NewsList.style.ts
│ │ │ ├── NewsListScreen.tsx
│ │ │ └── useNewsList.ts
│ │ ├── Setting/
│ │ │ ├── Setting.style.ts
│ │ │ ├── SettingScreen.tsx
│ │ │ └── useSetting.ts
│ │ └── index.ts
│ ├── services/
│ │ ├── apiHandler.ts
│ │ ├── appServices.ts
│ │ ├── appServices.type.ts
│ │ ├── appServicesEndPoints.ts
│ │ ├── commercial/
│ │ │ ├── adapters/
│ │ │ │ └── response/
│ │ │ │ ├── getNewsCommercialResponseAdapter.ts
│ │ │ │ ├── getUserCommercialResponseAdapter.ts
│ │ │ │ └── postLoginCommercialResponseAdapter.ts
│ │ │ └── dtos/
│ │ │ ├── NewsResponseDTO.ts
│ │ │ └── UserResponseDTO.ts
│ │ ├── index.ts
│ │ ├── models/
│ │ │ ├── index.ts
│ │ │ ├── login.ts
│ │ │ ├── news.ts
│ │ │ ├── unknown.ts
│ │ │ └── user.ts
│ │ └── serviceAdapter.ts
│ ├── store/
│ │ ├── index.ts
│ │ ├── observers/
│ │ │ ├── index.ts
│ │ │ ├── news.ts
│ │ │ └── users.ts
│ │ └── reducers/
│ │ ├── index.ts
│ │ ├── newsData.ts
│ │ └── usersData.ts
│ └── utils/
│ ├── color.ts
│ ├── dimensions.ts
│ ├── helper.ts
│ └── index.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# node.js
#
npm-debug.log
yarn-error.log
yarn-lock.json
package-lock.json
yarn.lock
node_modules
.yarn/
templates/CliTemplate/android/app/build
templates/CliTemplate/ios/build
templates/ExpoTemplate/.env.production
templates/ExpoTemplate/.env.staging
templates/ExpoTemplate/.env.development
templates/CliTemplate/.env.development
templates/CliTemplate/.env.production
templates/CliTemplate/.env.staging
================================================
FILE: .husky/commit-msg
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no -- commitlint --edit
================================================
FILE: .husky/pre-commit
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
================================================
FILE: .npmignore
================================================
.github
!.env
media/
.yarn/
#
# node.js
#
npm-debug.log
yarn-error.log
yarn-lock.json
package-lock.json
node_modules/
.husky/
templates/CliTemplate/android/app/build
templates/CliTemplate/ios/build
documentation/
.yarn/
================================================
FILE: .vscode/settings.json
================================================
{
"eslint.options": {},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.run": "onSave",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"cSpell.words": ["dtos", "Formik", "gradlew", "MMKV", "persistor"],
"conventionalCommits.scopes": ["contents"]
}
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2023 MindInventory
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# React Native Boilerplate!🚀
[](<[https://www.npmjs.org/package/@mindinventory/react-native-boilerplate](https://www.npmjs.com/package/@mindinventory/react-native-boilerplate)>)



The Boilerplate contains all the basic packages, common components and, prebuilt code architecture. It will save developer's project setup time.
## Introduction
This repository serves as a boilerplate for React Native projects, providing a solid foundation to kickstart your development process. It includes a collection of scripts to generate images and icons, making it easier to customize your app's visual assets.
Create a new project using the boilerplate :
**For React Native Cli**
```
npx @react-native-community/cli@latest init APP_NAME --template @mindinventory/react-native-boilerplate
```
**For Expo**
```
npx @mindinventory/react-native-boilerplate
```
## [Comprehensive documentation](https://mindinventory.github.io/react-native-boilerplate)
Unlock the power of our boilerplate with our comprehensive [documentation here](https://mindinventory.github.io/react-native-boilerplate)! Learn the rationale behind design decisions and get clear instructions on using features.
## Tech Stack
| Library | Category | Version | Description |
| ---------------------------------- | -------------------- | ------- | ---------------------------------------------- |
| React Native | Mobile Framework | v0.74 | The best cross-platform mobile framework |
| React | UI Framework | v18 | The most popular UI framework in the world |
| TypeScript | Language | v5 | Static typechecking |
| React Navigation | Navigation | v6 | Performant and consistent navigation framework |
| React Native Localization(for CLI) | Internationalization | v3 | i18n support (including RTL!) |
| Redux | State Management | v5 | Observable state tree |
| Redux-toolkit | Redux integration | v2 | New redux library with some function helpers |
| RN Reanimated | Animations | v3 | Beautiful and performant animations |
| MMKV(for CLI) | Persistence | v2 | State persistence |
| axios | REST client | v1 | Communicate with back-end |
| Hermes | JS engine | | Fine-tuned JS engine for RN |
| Async storage(for Expo) | Persistence | v1 | State persistence |
| expo-localization(for Expo) | Internationalization | v15 | localization support |
## Contribution
Contributions to this boilerplate are welcome! If you encounter any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request on the repository.
# LICENSE
react-native-boilerplate is [MIT-licensed](https://github.com/Mindinventory/react-native-boilerplate/blob/master/LICENSE).
# Let us know
If you use our open-source libraries in your project, please make sure to credit us and Give a star to www.mindinventory.com
Please feel free to use this component and Let us know if you are interested to building Apps or Designing Products.
================================================
FILE: bin/index.js
================================================
#!/usr/bin/env node
const path = require("path");
const { fileURLToPath, URL } = require("node:url");
const kleur = require("kleur");
const {
getProjectName,
getBoilerplateType,
getPackageId,
getConfirmationForGitInit,
} = require("../src/prompts.js");
const { expoProjectSetup } = require("../src/projectSetup.js");
const { setupInitialdependency } = require("../src/dependencyHandler.js");
const { gitInitialize } = require("../src/gitHandler.js");
const { textBanners, boilerplateBanner } = require("../src/helper.js");
const { green } = kleur;
// const __filename = fileURLToPath(import.meta.url)
// const __filenameNew = fileURLToPath(new URL('.', './index.js'));
// const __dirnameNew = path.dirname(__filenameNew)
const __filenameNew = path.resolve(__dirname, "index.js"); // Resolves index.js in the current directory
const __dirnameNew = path.dirname(__filenameNew);
console.log("__dirnameNew: ", __dirnameNew);
const boilerplates = "ExpoTemplate";
async function main() {
const { projectName } = await getProjectName();
if (!projectName) {
return;
}
const destPath = path.resolve(process.cwd(), projectName);
const packageJsonPath = path.join(destPath, "package.json");
const appJsonPath = path.join(destPath, "app.json");
const { boilerplate } = await getBoilerplateType();
let packageId = null;
if (boilerplate === "bare react native") {
const response = await getPackageId(projectName);
packageId = response.packageId;
}
const { gitInit } = await getConfirmationForGitInit();
const srcPath = path.resolve(__dirnameNew, "../templates", boilerplates);
try {
await textBanners();
await boilerplateBanner();
if (boilerplate === "expo") {
await expoProjectSetup({
srcPath,
destPath,
packageJsonPath,
appJsonPath,
projectName,
packageId,
makePreBuildConfig: false,
});
await setupInitialdependency({ makePreBuildConfig: false });
if (gitInit) {
await gitInitialize();
}
console.log("\n");
console.log(green().bold("🚀\u00A0Project created successfully."));
} else {
if (projectName && packageId) {
await expoProjectSetup({
srcPath,
destPath,
packageJsonPath,
appJsonPath,
projectName,
packageId,
makePreBuildConfig: true,
});
await setupInitialdependency({ makePreBuildConfig: true });
if (gitInit) {
await gitInitialize();
}
console.log("\n");
console.log(green().bold("🚀\u00A0Project created successfully."));
} else {
return;
}
}
} catch (err) {
console.error("❌ Error setting up boilerplate:", err);
}
}
main();
================================================
FILE: commitlint.config.js
================================================
module.exports = {extends: ['@commitlint/config-conventional']};
================================================
FILE: package.json
================================================
{
"name": "@mindinventory/react-native-boilerplate",
"version": "3.0.0",
"description": "React Native Template",
"repository": "https://github.com/Mindinventory/react-native-boilerplate.git",
"author": "Mindinventory",
"license": "MIT",
"main": "./bin/index.js",
"private": false,
"scripts": {
"android": "cd MIBoilerplate/ && npx react-native run-android",
"ios": "cd MIBoilerplate/ && npx react-native run-ios",
"prepare": "husky"
},
"bin": {
"@mindinventory/react-native-boilerplate": "./bin/index.js"
},
"bugs": {
"url": "https://github.com/Mindinventory/react-native-boilerplate/issues"
},
"homepage": "https://github.com/Mindinventory/react-native-boilerplate/blob/master/README.md",
"keywords": [
"react-native",
"mindinventory",
"boilerplate",
"starter-kit",
"react-native-template",
"react",
"native",
"template",
"expo"
],
"licenses": [
{
"type": "MIT",
"url": "https://github.com/Mindinventory/react-native-boilerplate/blob/master/LICENSE"
}
],
"devDependencies": {
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0",
"husky": "^9.1.6"
},
"dependencies": {
"chalk": "^5.3.0",
"execa": "^9.4.0",
"figlet": "^1.7.0",
"fs-extra": "^11.2.0",
"inquirer": "^11.0.2",
"kleur": "^4.1.5",
"ora": "^8.1.0",
"path": "^0.12.7",
"replace-in-file": "^8.2.0"
},
"type": "commonjs"
}
================================================
FILE: script.js
================================================
#!/usr/bin/env node
console.log("Welcome to Mindinventory React native boilerplate");
const { execSync } = require("child_process");
const installDependencies = () => {
console.log("\n\n");
console.log(
"@mindinventory/react-native-boilerplate initialized with success! 🚀\n"
);
console.log("Installing dependencies... 🛠️\n");
execSync(`yarn`, { stdio: "inherit" });
console.log("Dependencies installed successfully. 🚀\n");
console.log("bundle Installing 🛠️\n");
execSync(`bundle`, { stdio: "inherit" });
console.log("bundle installed successfully.🚀\n");
console.log("pod-install Installing 🛠️\n");
execSync(`npx pod-install`, { stdio: "inherit" });
console.log("pod-install installed successfully.🚀\n");
};
const fs = require("fs");
const initializeGit = () => {
const gitignoreContent = `
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
`;
fs.writeFileSync(".gitignore", gitignoreContent);
console.log(".gitignore file created successfully. 🚀\n");
try {
execSync("git add .", { stdio: "inherit", shell: true });
execSync(`git commit -m 'Initial commit'`, {
stdio: "inherit",
shell: true,
});
} catch (error) {
console.error(`🚨 An error occurred while initializing git: ${error}`);
}
};
const main = async () => {
execSync("git init", { stdio: "inherit" });
installDependencies();
initializeGit();
};
new Promise((resolve) => {
main();
resolve();
})
.then(() => {
console.log(
"- 🎉 Congrats! Your project is ready with @mindinventory/react-native-boilerplate! 🎉\n"
);
console.log(
"- 📚 If you need to read more about this boilerplate : https://github.com/Mindinventory/react-native-boilerplate/blob/master/README.md\n"
);
console.log(
"- 🤕 If you have some troubles : https://github.com/Mindinventory/react-native-boilerplate/issues\n"
);
console.log(
"- ⭐ If you love this boilerplate, give us a star, you will be a ray of sunshine in our lives :) https://github.com/Mindinventory/react-native-boilerplate\n"
);
})
.catch((error) => {
console.error(`🚨 An error occurred with post init script: ${error}`);
throw new Error();
});
================================================
FILE: src/dependencyHandler.js
================================================
const { exec } = require('child_process');
var util = require('util')
const { loading, logger } = require("./helper.js");
const execAsync = util.promisify(exec)
async function setupInitialdependency({makePreBuildConfig}) {
let installDepenLoading = await loading('🛠️\u00A0dependency installing...')
installDepenLoading.start()
await execAsync("yarn",{stdio: 'inherit'});
await execAsync("npx expo install --fix ",{stdio: 'inherit'});
if (makePreBuildConfig) {
await execAsync(`npx expo install expo-dev-client`)
}
installDepenLoading.succeed('dependency install successfully...')
if (makePreBuildConfig) {
logger('⚙️' + ' ' + 'Configuring project...')
logger('⏱️' + ' ' + 'Please wait. May this process will take minutes...')
console.log("\n")
let preBuildLoading = await loading('⚙️' + ' ' + 'Configuring project...')
preBuildLoading.start()
await execAsync(`npx expo prebuild --clean`)
preBuildLoading.succeed('Configured project successfully!! ...')
}
}
module.exports = {
setupInitialdependency
};
================================================
FILE: src/gitHandler.js
================================================
const { exec } = require('child_process');
var util = require('util')
const execAsync = util.promisify(exec)
async function gitInitialize() {
await execAsync("git init", { stdio: "inherit" });
await execAsync("git add .");
await execAsync(`git commit -m 'Initial commit'`);
}
module.exports = {
gitInitialize
};
================================================
FILE: src/helper.js
================================================
const kleur = require("kleur");
var figlet = require("figlet");
const { red, green, yellow } = kleur;
function logError(message) {
console.error(red().bold(`[ERROR] ${message}`));
process.exit(1); // Exit the process after logging error
}
function logWarning(message) {
console.warn(yellow().bold(`[WARNING] ${message}`));
}
function logSuccess(message) {
console.log(green().bold(`[SUCCESS] ${message}`));
}
function logger(message) {
console.log(`${message}`);
}
async function loading(text) {
const ora = (await import("ora")).default;
return ora(`${text}`);
}
async function textBanners() {
const chalk = (await import("chalk")).default;
return figlet.text(
"MINDINVENTORY",
{
font: "Big Money-nw",
horizontalLayout: "full",
verticalLayout: "default",
whitespaceBreak: true,
width: 200,
},
function (err, data) {
if (err) {
console.log("Something went wrong...");
console.dir(err);
return;
}
console.log(chalk.hex("#ED184F")(data));
}
);
}
async function boilerplateBanner() {
const chalk = (await import("chalk")).default;
return figlet.text(
"BOILERPLATE",
{
font: "Big Money-nw",
horizontalLayout: "full",
verticalLayout: "default",
whitespaceBreak: true,
width: 200,
},
function (err, data) {
if (err) {
console.log("Something went wrong...");
console.dir(err);
return;
}
console.log(chalk.hex("#FFFFFF")(data));
}
);
}
module.exports = {
logError,
logWarning,
logSuccess,
loading,
textBanners,
logger,
boilerplateBanner,
};
================================================
FILE: src/projectSetup.js
================================================
const fs = require('fs-extra')
const {loading} = require('./helper.js')
async function expoProjectSetup({srcPath, destPath, packageJsonPath, appJsonPath, projectName, packageId, makePreBuildConfig}) {
let initLoading = await loading('🧰\u00A0Setting up environment...')
initLoading.start()
await fs.copy(srcPath, destPath)
if (await fs.pathExists(packageJsonPath)) {
const packageJson = await fs.readJson(packageJsonPath)
packageJson.name = projectName
await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 })
}
if (await fs.pathExists(appJsonPath)) {
const appJson = await fs.readJson(appJsonPath)
appJson.expo.name = projectName
appJson.expo.slug = projectName
if (makePreBuildConfig) {
appJson.expo.ios.bundleIdentifier = packageId
appJson.expo.android.package = packageId
}
await fs.writeJson(appJsonPath, appJson, { spaces: 2 })
}
process.chdir(destPath)
initLoading.info()
}
module.exports = {
expoProjectSetup
};
================================================
FILE: src/prompts.js
================================================
const path = require('path')
const fs = require('fs-extra')
const {logError} = require('./helper.js')
async function getProjectName() {
const inquirer = (await import('inquirer')).default;
const { projectName } = await inquirer.prompt([
{
type: "input",
name: "projectName",
message: "Enter the project name:",
validate: (input) => (input ? true : "Project name cannot be empty"),
},
])
const destPath = path.resolve(process.cwd(), projectName)
if (await fs.pathExists(destPath)) {
logError(`The directory "${projectName}" already exists`)
return {
projectName : ''
}
}
return {
projectName
}
}
async function getBoilerplateType() {
const inquirer = (await import('inquirer')).default;
return await inquirer.prompt([
{
type: "list",
name: "boilerplate",
message: "Select the boilerplate to use:",
choices: ["expo", "bare react native"],
},
]);
}
async function getPackageId(projectName) {
const inquirer = (await import('inquirer')).default;
return await inquirer.prompt([
{
type: "input",
name: "packageId",
message: "Enter the package ID (e.g., com.myapp):",
validate: (input) =>
/^[a-zA-Z]+\.[a-zA-Z]+/.test(input) ? true : "Package ID is not valid",
default: `com.${projectName.toLowerCase()}`,
},
]);
}
async function getConfirmationForGitInit() {
const inquirer = (await import('inquirer')).default;
return await inquirer.prompt([
{
type: "confirm",
name: "gitInit",
message: "Initialize git repository?",
default: true
},
]);
}
module.exports = {
getProjectName,
getBoilerplateType,
getPackageId,
getConfirmationForGitInit
};
================================================
FILE: template.config.js
================================================
module.exports = {
// Placeholder used to rename and replace in files
// package.json, index.json, android/, ios/
placeholderName: "MIBoilerplate",
// Directory with template
templateDir: "./templates/CliTemplate",
// Path to script, which will be executed after init
postInitScript: "./script.js",
titlePlaceholder: "@mindinventory React Native Boilerplate",
}
================================================
FILE: templates/CliTemplate/.bundle/config
================================================
BUNDLE_PATH: "vendor/bundle"
BUNDLE_FORCE_RUBY_PLATFORM: 1
================================================
FILE: templates/CliTemplate/.eslintrc.js
================================================
module.exports = {
extends: [
'@react-native',
'prettier',
'plugin:react-hooks/recommended',
'plugin:react-native/all',
],
overrides: [
{
files: ['*.ts', '*.tsx', '*.js'],
rules: {
'@typescript-eslint/no-shadow': ['error'],
'no-shadow': 'off',
'no-undef': 'off',
'react/no-unstable-nested-components': ['off', {allowAsProps: true}],
},
},
],
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
'eslint-plugin-no-inline-styles',
'import',
'react-hooks',
'sort-keys-fix',
'sort-destructure-keys',
'react-native',
],
root: true,
rules: {
'import/newline-after-import': [
'warn',
{
count: 1,
},
],
'import/no-duplicates': 'error',
'import/order': [
'error',
{
alphabetize: {
caseInsensitive: true,
order: 'asc',
},
groups: [
['external', 'builtin'],
'internal',
['sibling', 'parent'],
'index',
],
'newlines-between': 'always',
pathGroups: [
{
group: 'external',
pattern: '@(react|react-native)',
position: 'before',
},
{
group: 'internal',
pattern: '@miBoilerplate/**',
},
{
group: 'internal',
pattern: '@src/**',
},
],
pathGroupsExcludedImportTypes: ['internal', 'react'],
},
],
'no-console': ['error'],
'no-inline-styles/no-inline-styles': 2,
'no-restricted-imports': [
'error',
{
importNames: ['Text', 'Image'],
message: 'Please use @app/blueprints for importing main elements.',
name: 'react-native',
},
],
'no-shadow': 'off',
'prettier/prettier': [
'error',
{
arrowParens: 'avoid',
bracketSameLine: true,
bracketSpacing: true,
quoteProps: 'consistent',
singleQuote: true,
tabWidth: 2,
trailingComma: 'es5',
useTabs: false,
},
],
'react-hooks/exhaustive-deps': 'error',
'react-hooks/rules-of-hooks': 'error',
'sort-destructure-keys/sort-destructure-keys': [2, {caseSensitive: false}],
'sort-imports': [
'error',
{
ignoreCase: true,
ignoreDeclarationSort: true,
ignoreMemberSort: false,
},
],
'sort-keys-fix/sort-keys-fix': [
'error',
'asc',
{
caseSensitive: false,
natural: true,
},
],
},
};
================================================
FILE: templates/CliTemplate/.gitignore
================================================
# OSX
#
.DS_Store
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
**/.xcode.env.local
# Android/IntelliJ
#
build/
.idea
.gradle
local.properties
*.iml
*.hprof
.cxx/
*.keystore
!debug.keystore
# node.js
#
node_modules/
npm-debug.log
yarn-error.log
# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/
**/fastlane/report.xml
**/fastlane/Preview.html
**/fastlane/screenshots
**/fastlane/test_output
# Bundle artifact
*.jsbundle
# Ruby / CocoaPods
**/Pods/
/vendor/bundle/
# Temporary files created by Metro to check the health of the file watcher
.metro-health-check*
# testing
/coverage
# Yarn
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
================================================
FILE: templates/CliTemplate/.husky/commit-msg
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no -- commitlint --edit
================================================
FILE: templates/CliTemplate/.husky/pre-commit
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
yarn fix:lint
================================================
FILE: templates/CliTemplate/.node-version
================================================
18
================================================
FILE: templates/CliTemplate/.prettierrc.js
================================================
module.exports = {
arrowParens: 'avoid',
bracketSameLine: true,
bracketSpacing: true,
quoteProps: 'consistent',
singleQuote: true,
tabWidth: 2,
trailingComma: 'es5',
useTabs: false,
};
================================================
FILE: templates/CliTemplate/.svgrrc
================================================
{
"replaceAttrValues": {
"#FFF": "{props.pathFill}"
}
}
================================================
FILE: templates/CliTemplate/.vscode/settings.json
================================================
{
"eslint.options": {},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.run": "onSave",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"cSpell.words": ["dtos", "Formik", "gradlew", "MMKV", "persistor"],
"conventionalCommits.scopes": ["contents"]
}
================================================
FILE: templates/CliTemplate/.watchmanconfig
================================================
{}
================================================
FILE: templates/CliTemplate/.yarnrc.yml
================================================
nodeLinker: node-modules
================================================
FILE: templates/CliTemplate/App.tsx
================================================
import React from 'react';
import { MainApp } from './src/MainApp';
const App = () => {
return ;
};
export default App;
================================================
FILE: templates/CliTemplate/Gemfile
================================================
source 'https://rubygems.org'
# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
ruby ">= 2.6.10"
# Exclude problematic versions of cocoapods and activesupport that causes build failures.
gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1'
gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0'
================================================
FILE: templates/CliTemplate/README.md
================================================
This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli).
# Getting Started
>**Note**: Make sure you have completed the [React Native - Environment Setup](https://reactnative.dev/docs/environment-setup) instructions till "Creating a new application" step, before proceeding.
## Step 1: Start the Metro Server
First, you will need to start **Metro**, the JavaScript _bundler_ that ships _with_ React Native.
To start Metro, run the following command from the _root_ of your React Native project:
```bash
# using npm
npm start
# OR using Yarn
yarn start
```
## Step 2: Start your Application
Let Metro Bundler run in its _own_ terminal. Open a _new_ terminal from the _root_ of your React Native project. Run the following command to start your _Android_ or _iOS_ app:
### For Android
```bash
# using npm
npm run android
# OR using Yarn
yarn android
```
### For iOS
```bash
# using npm
npm run ios
# OR using Yarn
yarn ios
```
If everything is set up _correctly_, you should see your new app running in your _Android Emulator_ or _iOS Simulator_ shortly provided you have set up your emulator/simulator correctly.
This is one way to run your app — you can also run it directly from within Android Studio and Xcode respectively.
## Step 3: Modifying your App
Now that you have successfully run the app, let's modify it.
1. Open `App.tsx` in your text editor of choice and edit some lines.
2. For **Android**: Press the R key twice or select **"Reload"** from the **Developer Menu** (Ctrl + M (on Window and Linux) or Cmd ⌘ + M (on macOS)) to see your changes!
For **iOS**: Hit Cmd ⌘ + R in your iOS Simulator to reload the app and see your changes!
## Congratulations! :tada:
You've successfully run and modified your React Native App. :partying_face:
### Now what?
- If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps).
- If you're curious to learn more about React Native, check out the [Introduction to React Native](https://reactnative.dev/docs/getting-started).
# Troubleshooting
If you can't get this to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page.
# Learn More
To learn more about React Native, take a look at the following resources:
- [React Native Website](https://reactnative.dev) - learn more about React Native.
- [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment.
- [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**.
- [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts.
- [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native.
================================================
FILE: templates/CliTemplate/__tests__/App.test.tsx
================================================
/**
* @format
*/
import 'react-native';
import React from 'react';
import App from '../App';
// Note: import explicitly to use the types shipped with jest.
import {it} from '@jest/globals';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create();
});
================================================
FILE: templates/CliTemplate/android/app/build.gradle
================================================
apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
/**
* This is the configuration block to customize your React Native Android app.
* By default you don't need to apply any configuration, just uncomment the lines you need.
*/
react {
/* Folders */
// The root of your project, i.e. where "package.json" lives. Default is '../..'
// root = file("../../")
// The folder where the react-native NPM package is. Default is ../../node_modules/react-native
// reactNativeDir = file("../../node_modules/react-native")
// The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen
// codegenDir = file("../../node_modules/@react-native/codegen")
// The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js
// cliFile = file("../../node_modules/react-native/cli.js")
/* Variants */
// The list of variants to that are debuggable. For those we're going to
// skip the bundling of the JS bundle and the assets. By default is just 'debug'.
// If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
// debuggableVariants = ["liteDebug", "prodDebug"]
/* Bundling */
// A list containing the node command and its flags. Default is just 'node'.
// nodeExecutableAndArgs = ["node"]
//
// The command to run when bundling. By default is 'bundle'
// bundleCommand = "ram-bundle"
//
// The path to the CLI configuration file. Default is empty.
// bundleConfig = file(../rn-cli.config.js)
//
// The name of the generated asset file containing your JS bundle
// bundleAssetName = "MyApplication.android.bundle"
//
// The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
// entryFile = file("../js/MyApplication.android.js")
//
// A list of extra flags to pass to the 'bundle' commands.
// See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
// extraPackagerArgs = []
/* Hermes Commands */
// The hermes compiler command to run. By default it is 'hermesc'
// hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
//
// The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
// hermesFlags = ["-O", "-output-source-map"]
/* Autolinking */
autolinkLibrariesWithApp()
}
/**
* Set this to true to Run Proguard on Release builds to minify the Java bytecode.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore (JSC)
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
android {
ndkVersion rootProject.ext.ndkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
compileSdk rootProject.ext.compileSdkVersion
namespace "com.miboilerplate"
defaultConfig {
applicationId "com.miboilerplate"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
}
dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")
if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
} else {
implementation jscFlavor
}
}
// apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
================================================
FILE: templates/CliTemplate/android/app/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
================================================
FILE: templates/CliTemplate/android/app/src/debug/AndroidManifest.xml
================================================
================================================
FILE: templates/CliTemplate/android/app/src/main/AndroidManifest.xml
================================================
================================================
FILE: templates/CliTemplate/android/app/src/main/java/com/miboilerplate/MainActivity.kt
================================================
package com.miboilerplate
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "MIBoilerplate"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
================================================
FILE: templates/CliTemplate/android/app/src/main/java/com/miboilerplate/MainApplication.kt
================================================
package com.miboilerplate
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
}
}
================================================
FILE: templates/CliTemplate/android/app/src/main/res/drawable/rn_edit_text_material.xml
================================================
================================================
FILE: templates/CliTemplate/android/app/src/main/res/values/strings.xml
================================================
MIBoilerplate
================================================
FILE: templates/CliTemplate/android/app/src/main/res/values/styles.xml
================================================
================================================
FILE: templates/CliTemplate/android/build.gradle
================================================
buildscript {
ext {
buildToolsVersion = "34.0.0"
minSdkVersion = 23
compileSdkVersion = 34
targetSdkVersion = 34
ndkVersion = "26.1.10909125"
kotlinVersion = "1.9.24"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle")
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")
}
}
apply plugin: "com.facebook.react.rootproject"
================================================
FILE: templates/CliTemplate/android/gradle/wrapper/gradle-wrapper.properties
================================================
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
================================================
FILE: templates/CliTemplate/android/gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Use this property to specify which architecture you want to build.
# You can also override it from the CLI using
# ./gradlew -PreactNativeArchitectures=x86_64
reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
# Use this property to enable support to the new architecture.
# This will allow you to use TurboModules and the Fabric render in
# your application. You should enable this flag either if you want
# to write custom TurboModules/Fabric components OR use libraries that
# are providing them.
newArchEnabled=false
# Use this property to enable or disable the Hermes JS engine.
# If set to false, you will be using JSC instead.
hermesEnabled=true
================================================
FILE: templates/CliTemplate/android/gradlew
================================================
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
================================================
FILE: templates/CliTemplate/android/gradlew.bat
================================================
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: templates/CliTemplate/android/settings.gradle
================================================
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") }
plugins { id("com.facebook.react.settings") }
extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }
rootProject.name = 'MIBoilerplate'
include ':app'
includeBuild('../node_modules/@react-native/gradle-plugin')
================================================
FILE: templates/CliTemplate/app.json
================================================
{
"name": "MIBoilerplate",
"displayName": "MIBoilerplate"
}
================================================
FILE: templates/CliTemplate/babel.config.js
================================================
module.exports = {
plugins: [
'react-native-reanimated/plugin',
[
'module:react-native-dotenv',
{
envName: 'APP_ENV',
moduleName: '@env',
path: './.env',
},
],
[
'module-resolver',
{
alias: {
'@app/blueprints': './blueprints',
'@src/assets': './src/assets',
'@src/components': './src/components',
'@src/constants': './src/constants',
'@src/context': './src/context',
'@src/hooks': './src/hooks',
'@src/i18n': './src/i18n',
'@src/screens': './src/screens',
'@src/services': './src/services',
'@src/store': './src/store',
'@src/utils': './src/utils',
},
extensions: ['.js', '.json'],
root: ['./src'],
},
],
],
presets: ['module:@react-native/babel-preset'],
};
================================================
FILE: templates/CliTemplate/blueprints/Button/Button.tsx
================================================
import React from 'react';
import {
StyleProp,
StyleSheet,
TextStyle,
TouchableOpacity,
TouchableOpacityProps,
View,
ViewStyle,
} from 'react-native';
import Animated, {
useAnimatedStyle,
useSharedValue,
withSpring,
} from 'react-native-reanimated';
import { useColor } from '@src/context';
import { moderateScale, Palette, scaleHeight } from '@src/utils';
import { Text } from '../Text/Text';
const AnimatedButtonComponent =
Animated.createAnimatedComponent(TouchableOpacity);
interface ExtraButtonProps {
buttonContainerStyle?: StyleProp;
titleContainerStyle?: StyleProp;
titleStyle?: StyleProp;
title?: React.ReactNode;
rightIcon?: JSX.Element;
leftIcon?: JSX.Element;
}
export type AnimatedButtonProps = Omit<
TouchableOpacityProps,
'onPressIn' | 'onPressOut' | 'style'
> & {
containerStyle?: StyleProp;
};
export type ButtonProps = AnimatedButtonProps & ExtraButtonProps;
export const AnimatedTouchableOpacity = React.memo(
(props: AnimatedButtonProps) => {
const { containerStyle } = props;
const scaleValue = useSharedValue(1);
const animatedButtonStyle = useAnimatedStyle(() => {
return {
transform: [{ scale: scaleValue.value }],
};
});
return (
(scaleValue.value = withSpring(0.9))}
onPressOut={() => (scaleValue.value = withSpring(1))}
activeOpacity={0.8}
{...props}>
{props.children}
);
}
);
export const Button = React.memo((props: ButtonProps) => {
const { buttonContainerStyle, title, titleContainerStyle, titleStyle } =
props;
const { color } = useColor();
const styles = buttonStyles(color);
return (
{props.leftIcon}
{title}
{props.rightIcon}
);
});
const buttonStyles = ({ primaryColor }: Palette) =>
StyleSheet.create({
buttonContainer: {
alignItems: 'center',
backgroundColor: primaryColor,
borderRadius: moderateScale(60),
height: scaleHeight(45),
width: '100%',
},
titleContainer: {
alignItems: 'center',
flexDirection: 'row',
height: '100%',
justifyContent: 'center',
width: '100%',
},
});
================================================
FILE: templates/CliTemplate/blueprints/Image/Image.tsx
================================================
import React, { useEffect, useState } from 'react';
import type { LayoutChangeEvent } from 'react-native';
import {
ActivityIndicator,
LayoutRectangle,
StyleProp,
StyleSheet,
View,
ViewStyle,
} from 'react-native';
import FastImage, {
FastImageProps as FastImageProp,
ImageStyle,
Priority,
Source,
} from 'react-native-fast-image';
import { useColor } from '@src/context';
export type FastImageProps = Omit;
export interface ImageProps extends FastImageProps {
containerStyle?: StyleProp;
style?: ImageStyle;
priority?: Priority;
uploading?: boolean;
width?: number;
height?: number;
children?: React.ReactNode;
showIndicator?: boolean;
indicatorSize?: number;
source?: string | Source | number;
loaderColor?: string;
}
export const Image = React.memo((props: ImageProps) => {
const {
children,
containerStyle,
indicatorSize = 20,
loaderColor,
priority,
resizeMode,
showIndicator = true,
source,
style,
uploading,
width,
...rest
} = props;
const { color } = useColor();
const [loading, setLoading] = useState(false);
const [layout, setLayout] = useState(null);
useEffect(() => {
if (typeof uploading !== 'undefined' && uploading !== loading) {
setLoading(uploading);
}
}, [loading, uploading]);
const onLayout = (e: LayoutChangeEvent) => {
const { height } = e.nativeEvent.layout;
if (layout && layout.height === height && layout.width === width) {
return;
}
setLayout(e.nativeEvent.layout);
};
const shouldShowIndicator =
showIndicator &&
typeof source === 'string' &&
(source.startsWith('http') || source.startsWith('https'));
let indicator = null;
if (loading && shouldShowIndicator) {
indicator = (
);
}
let imageSource: number | Source | undefined = {
priority: priority || FastImage.priority.normal,
uri: source as string,
};
if (typeof source !== 'string') {
// Local image
imageSource = source;
}
let imageStyle: StyleProp = style || {};
if (imageStyle.flex === 1 && layout) {
imageStyle = { ...style };
delete imageStyle.flex;
imageStyle = { ...imageStyle, ...layout };
}
return (
{
!loading && setLoading(true);
}}
onError={() => {
loading && setLoading(false);
}}
onLoadEnd={() => {
loading && setLoading(false);
}}
{...rest}>
{children}
{indicator}
);
});
const styles = StyleSheet.create({
container: {},
indicator: {
...StyleSheet.absoluteFillObject,
alignItems: 'center',
justifyContent: 'center',
},
});
================================================
FILE: templates/CliTemplate/blueprints/Indicator/Indicator.tsx
================================================
import React, {
useCallback,
useImperativeHandle,
useRef,
useState,
} from 'react';
import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';
import { useColor } from '@src/context';
import { Palette, scaledSize } from '@src/utils';
import { Text } from '../Text/Text';
export interface IndicatorProps {
isLoading: boolean;
}
export type IndicatorRef = {
hide: () => void;
show: () => void;
};
export const IndicatorViewRef = (
props: IndicatorProps,
ref: React.Ref
) => {
const { isLoading = true } = props;
const { color } = useColor();
const [loading, setIsLoading] = useState(isLoading);
const pressCount = useRef(0);
const show = useCallback(() => setIsLoading(true), []);
const hide = useCallback(() => setIsLoading(false), []);
const handlePressCount = useCallback(() => {
pressCount.current = pressCount.current + 1;
if (pressCount.current === 2) {
setIsLoading(false);
pressCount.current = 0;
}
}, []);
useImperativeHandle(
ref,
() => {
return {
hide,
show,
};
},
[hide, show]
);
const styles = indicatorStyles(color);
if (!loading) return <>>;
return (
Please wait ...
);
};
export const IndicatorView = React.forwardRef(
IndicatorViewRef
);
export const indicatorStyles = ({ backgroundColor }: Palette) => {
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
...StyleSheet.absoluteFillObject,
},
loaderContainer: {
alignItems: 'center',
backgroundColor: backgroundColor,
borderRadius: scaledSize(7),
justifyContent: 'center',
padding: scaledSize(10),
},
loaderStyle: {
padding: scaledSize(7),
},
});
return styles;
};
================================================
FILE: templates/CliTemplate/blueprints/Text/Text.tsx
================================================
import React from 'react';
import {
// eslint-disable-next-line no-restricted-imports
Text as RNText,
StyleProp,
TextProps as TextProperties,
TextStyle,
} from 'react-native';
import { useColor } from '@src/context';
import { scaledSize } from '@src/utils';
export enum Fonts {
Poppins = 'Poppins',
}
const BASE_TEXT: TextStyle = {
fontSize: scaledSize(7),
};
export const presets = {
default: BASE_TEXT,
font400: {
...BASE_TEXT,
//add your font normal for weight 400
fontFamily: Fonts.Poppins,
} as TextStyle,
font500: {
...BASE_TEXT,
//add your font medium for weight 500
fontFamily: Fonts.Poppins,
} as TextStyle,
font600: {
...BASE_TEXT,
//add your font semi-bold for weight 600
fontFamily: Fonts.Poppins,
} as TextStyle,
font700: {
...BASE_TEXT,
//add your font bold for weight 700
fontFamily: Fonts.Poppins,
} as TextStyle,
h1: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(24),
fontWeight: '700',
} as TextStyle,
h2: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(21),
fontWeight: '700',
} as TextStyle,
h3: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(18),
fontWeight: '500',
} as TextStyle,
h4: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(15),
fontWeight: '500',
} as TextStyle,
h5: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(12),
fontWeight: '400',
} as TextStyle,
h6: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(9),
fontWeight: '400',
} as TextStyle,
small: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(6),
fontWeight: '300',
} as TextStyle,
title: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(13),
fontWeight: '700',
} as TextStyle,
};
export type TextPresets = keyof typeof presets;
export interface TextProps extends TextProperties {
style?: StyleProp;
preset?: TextPresets;
color?: string;
textAlign?: 'auto' | 'left' | 'right' | 'center' | 'justify';
}
export const Text = ({ children, ...props }: TextProps) => {
const {
color,
preset = 'default',
style: styleOverride,
textAlign = 'auto',
...rest
} = props;
const { color: palette } = useColor();
return (
{children}
);
};
================================================
FILE: templates/CliTemplate/blueprints/TextInput/Input.tsx
================================================
import React, { useCallback } from 'react';
import {
NativeSyntheticEvent,
Platform,
TextInput as RNTextInput,
StyleSheet,
TargetedEvent,
TextInputFocusEventData,
TextInputProps,
View,
} from 'react-native';
import Animated, {
Easing,
interpolate,
interpolateColor,
useAnimatedProps,
useAnimatedStyle,
useDerivedValue,
useSharedValue,
withTiming,
} from 'react-native-reanimated';
import { useColor } from '@src/context';
import { Palette } from '@src/utils';
import { InputProps } from './TextInputProps';
import { Text } from '../Text/Text';
const AnimatedTextInput = Animated.createAnimatedComponent(RNTextInput);
export const Input = React.memo(
React.forwardRef((props: InputProps, ref?: React.Ref) => {
const {
backgroundColor = 'white',
borderColor = 'black',
error,
errorContainerStyle,
errorStyle,
inputContainerStyle,
inputStyle,
label,
labelColor = 'black',
leftIcon,
leftIconContainerStyle,
onBlur,
onFocus,
onFocusBackgroundColor = '#e9e9e9',
onFocusBorderColor = '#0c5fed',
onFocusLabelColor = '#0c5fed',
onHoverBackgroundColor = '#e9e9e9',
onMouseEnter,
onMouseLeave,
outlineGapColor = 'white',
placeholder,
rightIcon,
rightIconContainerStyle,
style,
variant = 'filled',
...rest
} = props;
const { color } = useColor();
const styles = inputStyles(color);
const hovered = useSharedValue(false);
const focused = useSharedValue(false);
const handleMouseEnter = useCallback(
(event: NativeSyntheticEvent) => {
onMouseEnter?.(event);
hovered.value = true;
},
[hovered, onMouseEnter]
);
const handleMouseLeave = useCallback(
(event: NativeSyntheticEvent) => {
onMouseLeave?.(event);
hovered.value = false;
},
[hovered, onMouseLeave]
);
const handleFocus = useCallback(
(event: NativeSyntheticEvent) => {
onFocus?.(event);
focused.value = true;
},
[focused, onFocus]
);
const handleBlur = useCallback(
(event: NativeSyntheticEvent) => {
onBlur?.(event);
focused.value = false;
},
[focused, onBlur]
);
const focusAnimation = useSharedValue(0);
useDerivedValue(() => {
focusAnimation.value = withTiming(focused.value ? 1 : 0, {
duration: 200,
easing: Easing.out(Easing.ease),
});
}, [focused.value, focusAnimation.value]);
const active = useDerivedValue(
() => focused.value || (rest.value?.length || 0) > 0,
[focused.value, rest.value]
);
const activeAnimation = useSharedValue(0);
useDerivedValue(() => {
activeAnimation.value = withTiming(active.value ? 1 : 0, {
duration: 200,
easing: Easing.out(Easing.ease),
});
}, [active.value, activeAnimation.value]);
const animatedInputContainerStyle = useAnimatedStyle(() => {
return {
backgroundColor:
variant === 'filled'
? focused.value
? onFocusBackgroundColor
: hovered.value
? onHoverBackgroundColor
: backgroundColor
: variant === 'outlined'
? backgroundColor
: backgroundColor,
borderBottomEndRadius: variant !== 'standard' ? 4 : 0,
borderBottomStartRadius: variant !== 'standard' ? 4 : 0,
borderTopEndRadius: 4,
borderTopStartRadius: 4,
};
}, [focused.value, hovered.value, variant]);
const animatedInput = useAnimatedStyle(() => {
return {
fontSize: 16,
minHeight: variant === 'standard' ? 48 : 56,
paddingEnd: rightIcon ? 12 : variant === 'standard' ? 0 : 16,
paddingStart: leftIcon ? 12 : variant === 'standard' ? 0 : 16,
paddingTop: variant === 'filled' && label ? 18 : 0,
};
}, [variant, leftIcon, rightIcon]);
const animatedLeading = useAnimatedStyle(() => {
return {
marginStart: variant === 'standard' ? 0 : 12,
marginVertical: variant === 'standard' ? 12 : 16,
};
}, [variant]);
const animatedTrailing = useAnimatedStyle(() => {
return {
marginEnd: variant === 'standard' ? 0 : 12,
marginVertical: variant === 'standard' ? 12 : 16,
};
}, [variant]);
const animatedOutline = useAnimatedStyle(() => {
return {
borderBottomEndRadius: 4,
borderBottomStartRadius: 4,
borderColor: focused.value
? onFocusBorderColor
: hovered.value
? onFocusBorderColor
: borderColor,
borderTopEndRadius: 4,
borderTopStartRadius: 4,
borderWidth: focused.value ? 2 : 1,
};
}, [focused.value, hovered.value]);
const animatedOutlineLabelGap = useAnimatedStyle(() => {
return {
height: focused.value ? 2 : 1,
};
}, [focused.value]);
const animatedLabelContainer = useAnimatedStyle(() => {
return {
height: variant === 'standard' ? 48 : 56,
start:
variant === 'standard' ? (leftIcon ? 36 : 0) : leftIcon ? 48 : 16,
};
}, [variant, leftIcon]);
const animatedLabel = useAnimatedStyle(() => {
return {
color: interpolateColor(
focusAnimation.value,
[0, 1],
[labelColor, onFocusLabelColor]
),
fontSize: interpolate(activeAnimation.value, [0, 1], [16, 12]),
transform: [
{
translateY: interpolate(
activeAnimation.value,
[0, 1],
[
0,
variant === 'filled' ? -12 : variant === 'outlined' ? -28 : -24,
]
),
},
],
};
}, [focusAnimation, activeAnimation]);
const animatedPlaceholder = useAnimatedProps(() => {
return {
placeholder: label ? (focused.value ? placeholder : '') : placeholder,
};
}, [label, focused, placeholder]);
const animatedUnderline = useAnimatedStyle(() => {
return {
backgroundColor: interpolateColor(
focusAnimation.value,
[0, 1],
[borderColor, onFocusBorderColor]
),
transform: [{ scaleX: focusAnimation.value }],
};
}, [focusAnimation.value]);
const animatedOutlineLabel = useAnimatedStyle(() => {
return {
backgroundColor: interpolateColor(
activeAnimation.value,
[0, 1],
[backgroundColor, outlineGapColor]
),
transform: [{ scaleX: activeAnimation.value }],
};
}, [activeAnimation.value]);
return (
{leftIcon && (
{leftIcon}
)}
{rightIcon && (
{rightIcon}
)}
{(variant === 'filled' || variant === 'standard') && (
<>
>
)}
{variant === 'outlined' && (
)}
{label ? (
{variant === 'outlined' && (
)}
{label}
) : null}
{error ? (
{error}
) : null}
);
})
);
const inputStyles = ({ backgroundColor }: Palette) =>
StyleSheet.create({
errorView: {
marginHorizontal: 16,
marginTop: 4,
},
helperText: {
fontSize: 14,
},
input: {
flex: 1,
...Platform.select({
web: {
outlineStyle: 'none',
},
}),
},
inputContainer: {
flexDirection: 'row',
},
labelContainer: {
justifyContent: 'center',
position: 'absolute',
top: 0,
},
leading: {
alignItems: 'center',
height: 24,
justifyContent: 'center',
width: 24,
},
outline: {},
outlineLabelGap: {
backgroundColor: backgroundColor,
end: -4,
position: 'absolute',
start: -4,
top: 0,
},
trailing: {
alignItems: 'center',
height: 24,
justifyContent: 'center',
width: 24,
},
underline: {
bottom: 0,
end: 0,
height: 1,
position: 'absolute',
start: 0,
},
underlineFocused: {
bottom: 0,
end: 0,
height: 2,
position: 'absolute',
start: 0,
},
});
================================================
FILE: templates/CliTemplate/blueprints/TextInput/TextInput.tsx
================================================
import React from 'react';
import { TextInput as RNTextInput } from 'react-native';
import { Field, FieldProps } from 'formik';
import { Input } from './Input';
import { TextInputProps } from './TextInputProps';
export const TextInput = React.memo(
React.forwardRef(
({ ...props }: TextInputProps, ref?: React.Ref) => {
const { name } = props;
return (
{({ form, meta }: FieldProps) => {
return (
) => {
form?.handleChange(name)(text);
}}
onBlur={form?.handleBlur(name)}
value={meta?.value}
error={meta?.error && meta?.touched ? meta?.error ?? '' : ''}
ref={ref}
{...props}
/>
);
}}
);
}
)
);
================================================
FILE: templates/CliTemplate/blueprints/TextInput/TextInputProps.ts
================================================
import {
NativeSyntheticEvent,
TextInputProps as RNTextInputProps,
StyleProp,
TargetedEvent,
TextStyle,
ViewStyle,
} from 'react-native';
export interface TextInputProps extends InputProps {
name: string;
}
export type Variant = 'filled' | 'outlined' | 'standard';
export interface InputProps extends RNTextInputProps {
/**
* The variant of the TextInput style.
* @default "filled"
*/
variant?: Variant;
/**
* The label to display.
*/
label?: string;
/**
* The element placed before the text input.
*/
leftIcon?: React.ReactNode | null;
/**
* The element placed after the text input.
*/
rightIcon?: React.ReactNode | null;
/**
* The helper text to display.
*/
error?: string;
/**
* Callback function to call when user moves pointer over the input.
*/
onMouseEnter?: (event: NativeSyntheticEvent) => void;
/**
* Callback function to call when user moves pointer away from the input.
*/
onMouseLeave?: (event: NativeSyntheticEvent) => void;
/**
* The style of the container view.
*/
style?: StyleProp;
/**
* The style of the text input container view.
*/
inputContainerStyle?: StyleProp;
/**
* The style of the text input.
*/
inputStyle?: RNTextInputProps['style'];
/**
* The style of the text input's leading element container.
*/
leftIconContainerStyle?: StyleProp;
/**
* The style of the text input's trailing element container.
*/
rightIconContainerStyle?: StyleProp;
/**
* Background color of the input container style.
* @default "white"
*/
backgroundColor?: string;
/**
* On focus background color of the input container style.
* @default "#e9e9e9"
*/
onFocusBackgroundColor?: string;
/**
* Border color of the outline input container style.
* @default "black"
*/
borderColor?: string;
/**
* On focus Border color of the outline input container style.
* @default "#0c5fed"
*/
onFocusBorderColor?: string;
/**
* On hover background color of the filled input container style.
* @default "#e9e9e9"
*/
onHoverBackgroundColor?: string;
/**
* Label text color of the input.
* @default "black"
*/
labelColor?: string;
/**
* On focus Label text color change.
* @default "#0c5fed"
*/
onFocusLabelColor?: string;
/**
* On error or any helper text below text Input container style.
*/
errorContainerStyle?: StyleProp;
/**
* On error or any helper text below text Input Text-Style.
*/
errorStyle?: StyleProp;
/**
* In outlined variant the gap border color.
* @default white
*/
outlineGapColor?: string;
}
================================================
FILE: templates/CliTemplate/blueprints/TextInput/index.tsx
================================================
import { Input } from './Input';
import { TextInput } from './TextInput';
import { InputProps, TextInputProps } from './TextInputProps';
export { TextInput, Input };
export type { TextInputProps, InputProps };
================================================
FILE: templates/CliTemplate/blueprints/index.ts
================================================
export * from './Text/Text';
export * from './Image/Image';
export * from './Indicator/Indicator';
export * from './Button/Button';
export * from './TextInput';
================================================
FILE: templates/CliTemplate/commitlint.config.js
================================================
module.exports = { extends: ['@commitlint/config-conventional'] };
================================================
FILE: templates/CliTemplate/declarations.d.ts
================================================
declare module '*.svg' {
import React from 'react';
import { SvgProps } from 'react-native-svg';
const content: React.FC;
export default content;
}
================================================
FILE: templates/CliTemplate/env.d.ts
================================================
declare module '@env' {
export const API_URL: string;
export const ENV: string;
}
================================================
FILE: templates/CliTemplate/index.js
================================================
/**
* @format
*/
import { AppRegistry } from 'react-native';
import { startNetworkLogging } from 'react-native-network-logger';
import App from './App';
import { name as appName } from './app.json';
if (__DEV__) startNetworkLogging({ ignoredHosts: ['clients3.google.com'] });
AppRegistry.registerComponent(appName, () => App);
================================================
FILE: templates/CliTemplate/ios/.xcode.env
================================================
# This `.xcode.env` file is versioned and is used to source the environment
# used when running script phases inside Xcode.
# To customize your local environment, you can create an `.xcode.env.local`
# file that is not versioned.
# NODE_BINARY variable contains the PATH to the node executable.
#
# Customize the NODE_BINARY variable here.
# For example, to use nvm with brew, add the following line
# . "$(brew --prefix nvm)/nvm.sh" --no-use
export NODE_BINARY=$(command -v node)
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate/AppDelegate.h
================================================
#import
#import
@interface AppDelegate : RCTAppDelegate
@end
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate/AppDelegate.mm
================================================
#import "AppDelegate.h"
#import
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.moduleName = @"MIBoilerplate";
// You can add your custom initial props in the dictionary below.
// They will be passed down to the ViewController used by React Native.
self.initialProps = @{};
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
return [self bundleURL];
}
- (NSURL *)bundleURL
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
@end
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate/Images.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"images" : [
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "60x60"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "60x60"
},
{
"idiom" : "ios-marketing",
"scale" : "1x",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate/Images.xcassets/Contents.json
================================================
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate/Info.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleDisplayName
MIBoilerplate
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
APPL
CFBundleShortVersionString
$(MARKETING_VERSION)
CFBundleSignature
????
CFBundleVersion
$(CURRENT_PROJECT_VERSION)
LSRequiresIPhoneOS
NSAppTransportSecurity
NSAllowsArbitraryLoads
NSAllowsLocalNetworking
NSLocationWhenInUseUsageDescription
UILaunchStoryboardName
LaunchScreen
UIRequiredDeviceCapabilities
arm64
UISupportedInterfaceOrientations
UIInterfaceOrientationPortrait
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
UIViewControllerBasedStatusBarAppearance
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate/LaunchScreen.storyboard
================================================
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate/PrivacyInfo.xcprivacy
================================================
NSPrivacyAccessedAPITypes
NSPrivacyAccessedAPIType
NSPrivacyAccessedAPICategoryFileTimestamp
NSPrivacyAccessedAPITypeReasons
C617.1
NSPrivacyAccessedAPIType
NSPrivacyAccessedAPICategoryUserDefaults
NSPrivacyAccessedAPITypeReasons
CA92.1
NSPrivacyAccessedAPIType
NSPrivacyAccessedAPICategorySystemBootTime
NSPrivacyAccessedAPITypeReasons
35F9.1
NSPrivacyCollectedDataTypes
NSPrivacyTracking
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate/main.m
================================================
#import
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
00E356F31AD99517003FC87E /* MIBoilerplateTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* MIBoilerplateTests.m */; };
0C80B921A6F3F58F76C31292 /* libPods-MIBoilerplate.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-MIBoilerplate.a */; };
13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.mm */; };
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };
7699B88040F8A987B510C191 /* libPods-MIBoilerplate-MIBoilerplateTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 19F6CBCC0A4E27FBF8BF4A61 /* libPods-MIBoilerplate-MIBoilerplateTests.a */; };
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };
AD012B0CAE985EACFCEE8BD9 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 9ED2BB560F2ACE119C9702C2 /* PrivacyInfo.xcprivacy */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 13B07F861A680F5B00A75B9A;
remoteInfo = MIBoilerplate;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
00E356EE1AD99517003FC87E /* MIBoilerplateTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MIBoilerplateTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
00E356F21AD99517003FC87E /* MIBoilerplateTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MIBoilerplateTests.m; sourceTree = ""; };
13B07F961A680F5B00A75B9A /* MIBoilerplate.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = MIBoilerplate.app; sourceTree = BUILT_PRODUCTS_DIR; };
13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = MIBoilerplate/AppDelegate.h; sourceTree = ""; };
13B07FB01A68108700A75B9A /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = MIBoilerplate/AppDelegate.mm; sourceTree = ""; };
13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = MIBoilerplate/Images.xcassets; sourceTree = ""; };
13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = MIBoilerplate/Info.plist; sourceTree = ""; };
13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = MIBoilerplate/main.m; sourceTree = ""; };
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = MIBoilerplate/PrivacyInfo.xcprivacy; sourceTree = ""; };
19F6CBCC0A4E27FBF8BF4A61 /* libPods-MIBoilerplate-MIBoilerplateTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-MIBoilerplate-MIBoilerplateTests.a"; sourceTree = BUILT_PRODUCTS_DIR; };
3B4392A12AC88292D35C810B /* Pods-MIBoilerplate.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MIBoilerplate.debug.xcconfig"; path = "Target Support Files/Pods-MIBoilerplate/Pods-MIBoilerplate.debug.xcconfig"; sourceTree = ""; };
5709B34CF0A7D63546082F79 /* Pods-MIBoilerplate.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MIBoilerplate.release.xcconfig"; path = "Target Support Files/Pods-MIBoilerplate/Pods-MIBoilerplate.release.xcconfig"; sourceTree = ""; };
5B7EB9410499542E8C5724F5 /* Pods-MIBoilerplate-MIBoilerplateTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MIBoilerplate-MIBoilerplateTests.debug.xcconfig"; path = "Target Support Files/Pods-MIBoilerplate-MIBoilerplateTests/Pods-MIBoilerplate-MIBoilerplateTests.debug.xcconfig"; sourceTree = ""; };
5DCACB8F33CDC322A6C60F78 /* libPods-MIBoilerplate.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-MIBoilerplate.a"; sourceTree = BUILT_PRODUCTS_DIR; };
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = MIBoilerplate/LaunchScreen.storyboard; sourceTree = ""; };
89C6BE57DB24E9ADA2F236DE /* Pods-MIBoilerplate-MIBoilerplateTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-MIBoilerplate-MIBoilerplateTests.release.xcconfig"; path = "Target Support Files/Pods-MIBoilerplate-MIBoilerplateTests/Pods-MIBoilerplate-MIBoilerplateTests.release.xcconfig"; sourceTree = ""; };
9ED2BB560F2ACE119C9702C2 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; name = PrivacyInfo.xcprivacy; path = MIBoilerplate/PrivacyInfo.xcprivacy; sourceTree = ""; };
ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
00E356EB1AD99517003FC87E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
7699B88040F8A987B510C191 /* libPods-MIBoilerplate-MIBoilerplateTests.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F8C1A680F5B00A75B9A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
0C80B921A6F3F58F76C31292 /* libPods-MIBoilerplate.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
00E356EF1AD99517003FC87E /* MIBoilerplateTests */ = {
isa = PBXGroup;
children = (
00E356F21AD99517003FC87E /* MIBoilerplateTests.m */,
00E356F01AD99517003FC87E /* Supporting Files */,
);
path = MIBoilerplateTests;
sourceTree = "";
};
00E356F01AD99517003FC87E /* Supporting Files */ = {
isa = PBXGroup;
children = (
00E356F11AD99517003FC87E /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "";
};
13B07FAE1A68108700A75B9A /* MIBoilerplate */ = {
isa = PBXGroup;
children = (
13B07FAF1A68108700A75B9A /* AppDelegate.h */,
13B07FB01A68108700A75B9A /* AppDelegate.mm */,
13B07FB51A68108700A75B9A /* Images.xcassets */,
13B07FB61A68108700A75B9A /* Info.plist */,
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */,
13B07FB71A68108700A75B9A /* main.m */,
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */,
9ED2BB560F2ACE119C9702C2 /* PrivacyInfo.xcprivacy */,
);
name = MIBoilerplate;
sourceTree = "";
};
2D16E6871FA4F8E400B85C8A /* Frameworks */ = {
isa = PBXGroup;
children = (
ED297162215061F000B7C4FE /* JavaScriptCore.framework */,
5DCACB8F33CDC322A6C60F78 /* libPods-MIBoilerplate.a */,
19F6CBCC0A4E27FBF8BF4A61 /* libPods-MIBoilerplate-MIBoilerplateTests.a */,
);
name = Frameworks;
sourceTree = "";
};
832341AE1AAA6A7D00B99B32 /* Libraries */ = {
isa = PBXGroup;
children = (
);
name = Libraries;
sourceTree = "";
};
83CBB9F61A601CBA00E9B192 = {
isa = PBXGroup;
children = (
13B07FAE1A68108700A75B9A /* MIBoilerplate */,
832341AE1AAA6A7D00B99B32 /* Libraries */,
00E356EF1AD99517003FC87E /* MIBoilerplateTests */,
83CBBA001A601CBA00E9B192 /* Products */,
2D16E6871FA4F8E400B85C8A /* Frameworks */,
BBD78D7AC51CEA395F1C20DB /* Pods */,
);
indentWidth = 2;
sourceTree = "";
tabWidth = 2;
usesTabs = 0;
};
83CBBA001A601CBA00E9B192 /* Products */ = {
isa = PBXGroup;
children = (
13B07F961A680F5B00A75B9A /* MIBoilerplate.app */,
00E356EE1AD99517003FC87E /* MIBoilerplateTests.xctest */,
);
name = Products;
sourceTree = "";
};
BBD78D7AC51CEA395F1C20DB /* Pods */ = {
isa = PBXGroup;
children = (
3B4392A12AC88292D35C810B /* Pods-MIBoilerplate.debug.xcconfig */,
5709B34CF0A7D63546082F79 /* Pods-MIBoilerplate.release.xcconfig */,
5B7EB9410499542E8C5724F5 /* Pods-MIBoilerplate-MIBoilerplateTests.debug.xcconfig */,
89C6BE57DB24E9ADA2F236DE /* Pods-MIBoilerplate-MIBoilerplateTests.release.xcconfig */,
);
path = Pods;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
00E356ED1AD99517003FC87E /* MIBoilerplateTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "MIBoilerplateTests" */;
buildPhases = (
A55EABD7B0C7F3A422A6CC61 /* [CP] Check Pods Manifest.lock */,
00E356EA1AD99517003FC87E /* Sources */,
00E356EB1AD99517003FC87E /* Frameworks */,
00E356EC1AD99517003FC87E /* Resources */,
C59DA0FBD6956966B86A3779 /* [CP] Embed Pods Frameworks */,
F6A41C54EA430FDDC6A6ED99 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
00E356F51AD99517003FC87E /* PBXTargetDependency */,
);
name = MIBoilerplateTests;
productName = MIBoilerplateTests;
productReference = 00E356EE1AD99517003FC87E /* MIBoilerplateTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
13B07F861A680F5B00A75B9A /* MIBoilerplate */ = {
isa = PBXNativeTarget;
buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "MIBoilerplate" */;
buildPhases = (
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */,
13B07F871A680F5B00A75B9A /* Sources */,
13B07F8C1A680F5B00A75B9A /* Frameworks */,
13B07F8E1A680F5B00A75B9A /* Resources */,
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */,
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
);
name = MIBoilerplate;
productName = MIBoilerplate;
productReference = 13B07F961A680F5B00A75B9A /* MIBoilerplate.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
83CBB9F71A601CBA00E9B192 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1210;
TargetAttributes = {
00E356ED1AD99517003FC87E = {
CreatedOnToolsVersion = 6.2;
TestTargetID = 13B07F861A680F5B00A75B9A;
};
13B07F861A680F5B00A75B9A = {
LastSwiftMigration = 1120;
};
};
};
buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "MIBoilerplate" */;
compatibilityVersion = "Xcode 12.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 83CBB9F61A601CBA00E9B192;
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
13B07F861A680F5B00A75B9A /* MIBoilerplate */,
00E356ED1AD99517003FC87E /* MIBoilerplateTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
00E356EC1AD99517003FC87E /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F8E1A680F5B00A75B9A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */,
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
AD012B0CAE985EACFCEE8BD9 /* PrivacyInfo.xcprivacy in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"$(SRCROOT)/.xcode.env.local",
"$(SRCROOT)/.xcode.env",
);
name = "Bundle React Native code and images";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -e\n\nWITH_ENVIRONMENT=\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\"\nREACT_NATIVE_XCODE=\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\"\n\n/bin/sh -c \"$WITH_ENVIRONMENT $REACT_NATIVE_XCODE\"\n";
};
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate/Pods-MIBoilerplate-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate/Pods-MIBoilerplate-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate/Pods-MIBoilerplate-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
A55EABD7B0C7F3A422A6CC61 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-MIBoilerplate-MIBoilerplateTests-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-MIBoilerplate-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
C59DA0FBD6956966B86A3779 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate-MIBoilerplateTests/Pods-MIBoilerplate-MIBoilerplateTests-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate-MIBoilerplateTests/Pods-MIBoilerplate-MIBoilerplateTests-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate-MIBoilerplateTests/Pods-MIBoilerplate-MIBoilerplateTests-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate/Pods-MIBoilerplate-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate/Pods-MIBoilerplate-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate/Pods-MIBoilerplate-resources.sh\"\n";
showEnvVarsInLog = 0;
};
F6A41C54EA430FDDC6A6ED99 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate-MIBoilerplateTests/Pods-MIBoilerplate-MIBoilerplateTests-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate-MIBoilerplateTests/Pods-MIBoilerplate-MIBoilerplateTests-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MIBoilerplate-MIBoilerplateTests/Pods-MIBoilerplate-MIBoilerplateTests-resources.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
00E356EA1AD99517003FC87E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
00E356F31AD99517003FC87E /* MIBoilerplateTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F871A680F5B00A75B9A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */,
13B07FC11A68108700A75B9A /* main.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
00E356F51AD99517003FC87E /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 13B07F861A680F5B00A75B9A /* MIBoilerplate */;
targetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
00E356F61AD99517003FC87E /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 5B7EB9410499542E8C5724F5 /* Pods-MIBoilerplate-MIBoilerplateTests.debug.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = MIBoilerplateTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
"$(inherited)",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MIBoilerplate.app/MIBoilerplate";
};
name = Debug;
};
00E356F71AD99517003FC87E /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 89C6BE57DB24E9ADA2F236DE /* Pods-MIBoilerplate-MIBoilerplateTests.release.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
COPY_PHASE_STRIP = NO;
INFOPLIST_FILE = MIBoilerplateTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
"$(inherited)",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MIBoilerplate.app/MIBoilerplate";
};
name = Release;
};
13B07F941A680F5B00A75B9A /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-MIBoilerplate.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = MIBoilerplate/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = MIBoilerplate;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
13B07F951A680F5B00A75B9A /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-MIBoilerplate.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = MIBoilerplate/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = MIBoilerplate;
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
83CBBA201A601CBA00E9B192 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CC = "";
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
CXX = "";
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
LD = "";
LDPLUSPLUS = "";
LD_RUNPATH_SEARCH_PATHS = (
/usr/lib/swift,
"$(inherited)",
);
LIBRARY_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/lib/swift\"",
"\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
"\"$(inherited)\"",
);
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
OTHER_CPLUSPLUSFLAGS = (
"$(OTHER_CFLAGS)",
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
OTHER_LDFLAGS = (
"$(inherited)",
" ",
);
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
USE_HERMES = true;
};
name = Debug;
};
83CBBA211A601CBA00E9B192 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CC = "";
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
CXX = "";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
LD = "";
LDPLUSPLUS = "";
LD_RUNPATH_SEARCH_PATHS = (
/usr/lib/swift,
"$(inherited)",
);
LIBRARY_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/lib/swift\"",
"\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
"\"$(inherited)\"",
);
MTL_ENABLE_DEBUG_INFO = NO;
OTHER_CPLUSPLUSFLAGS = (
"$(OTHER_CFLAGS)",
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
OTHER_LDFLAGS = (
"$(inherited)",
" ",
);
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
USE_HERMES = true;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "MIBoilerplateTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
00E356F61AD99517003FC87E /* Debug */,
00E356F71AD99517003FC87E /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "MIBoilerplate" */ = {
isa = XCConfigurationList;
buildConfigurations = (
13B07F941A680F5B00A75B9A /* Debug */,
13B07F951A680F5B00A75B9A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "MIBoilerplate" */ = {
isa = XCConfigurationList;
buildConfigurations = (
83CBBA201A601CBA00E9B192 /* Debug */,
83CBBA211A601CBA00E9B192 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;
}
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
================================================
IDEDidComputeMac32BitWarning
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate.xcodeproj/xcshareddata/xcschemes/MIBoilerplate.xcscheme
================================================
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate.xcworkspace/contents.xcworkspacedata
================================================
================================================
FILE: templates/CliTemplate/ios/MIBoilerplate.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
================================================
IDEDidComputeMac32BitWarning
================================================
FILE: templates/CliTemplate/ios/MIBoilerplateTests/Info.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
BNDL
CFBundleShortVersionString
1.0
CFBundleSignature
????
CFBundleVersion
1
================================================
FILE: templates/CliTemplate/ios/MIBoilerplateTests/MIBoilerplateTests.m
================================================
#import
#import
#import
#import
#define TIMEOUT_SECONDS 600
#define TEXT_TO_LOOK_FOR @"Welcome to React"
@interface MIBoilerplateTests : XCTestCase
@end
@implementation MIBoilerplateTests
- (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test
{
if (test(view)) {
return YES;
}
for (UIView *subview in [view subviews]) {
if ([self findSubviewInView:subview matching:test]) {
return YES;
}
}
return NO;
}
- (void)testRendersWelcomeScreen
{
UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
BOOL foundElement = NO;
__block NSString *redboxError = nil;
#ifdef DEBUG
RCTSetLogFunction(
^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
if (level >= RCTLogLevelError) {
redboxError = message;
}
});
#endif
while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
[[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
[[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
foundElement = [self findSubviewInView:vc.view
matching:^BOOL(UIView *view) {
if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
return YES;
}
return NO;
}];
}
#ifdef DEBUG
RCTSetLogFunction(RCTDefaultLogFunction);
#endif
XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
}
@end
================================================
FILE: templates/CliTemplate/ios/Podfile
================================================
# Resolve react_native_pods.rb with node to allow for hoisting
require Pod::Executable.execute_command('node', ['-p',
'require.resolve(
"react-native/scripts/react_native_pods.rb",
{paths: [process.argv[1]]},
)', __dir__]).strip
platform :ios, min_ios_version_supported
prepare_react_native_project!
linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
use_frameworks! :linkage => linkage.to_sym
end
target 'MIBoilerplate' do
config = use_native_modules!
use_react_native!(
:path => config[:reactNativePath],
# An absolute path to your application root.
:app_path => "#{Pod::Config.instance.installation_root}/.."
)
target 'MIBoilerplateTests' do
inherit! :complete
# Pods for testing
end
post_install do |installer|
# https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
react_native_post_install(
installer,
config[:reactNativePath],
:mac_catalyst_enabled => false,
# :ccache_enabled => true
)
end
end
================================================
FILE: templates/CliTemplate/jest.config.js
================================================
module.exports = {
preset: 'react-native',
};
================================================
FILE: templates/CliTemplate/metro.config.js
================================================
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
const { assetExts, sourceExts } = defaultConfig.resolver;
/**
* Metro configuration
* https://reactnative.dev/docs/metro
*
* @type {import('metro-config').MetroConfig}
*/
const config = {
resolver: {
assetExts: assetExts.filter(ext => ext !== 'svg'),
sourceExts: [...sourceExts, 'svg'],
},
transformer: {
babelTransformerPath: require.resolve('react-native-svg-transformer'),
},
};
module.exports = mergeConfig(defaultConfig, config);
================================================
FILE: templates/CliTemplate/package.json
================================================
{
"name": "MIBoilerplate",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"fix:lint": "yarn lint --fix && yarn typescript",
"icons": "cd scripts && node icons.js",
"images": "cd scripts && node images.js",
"screens": "cd scripts && node generateScreenFile.js",
"svgs": "cd scripts && node svgIcons.js",
"preios": "ENVFILE=.env",
"preandroid": "ENVFILE=.env",
"ios": "react-native run-ios",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"postinstall": "npx pod-install",
"prepare": "husky",
"refresh": "bash ./scripts/refresh.sh",
"start": "NODE_ENV=default APP_ENV=default npx react-native start --reset-cache",
"start:development": "NODE_ENV=development APP_ENV=development npx react-native start --reset-cache",
"start:staging": "NODE_ENV=staging APP_ENV=staging npx react-native start --reset-cache",
"start:production": "NODE_ENV=production APP_ENV=production npx react-native start --reset-cache",
"test": "jest",
"typescript": "tsc --noEmit"
},
"dependencies": {
"@react-native-community/netinfo": "^11.4.1",
"@react-navigation/native": "^6.1.18",
"@react-navigation/native-stack": "^6.11.0",
"@reduxjs/toolkit": "^2.2.7",
"axios": "^1.7.7",
"formik": "^2.4.6",
"i18n-js": "^4.4.3",
"react": "18.3.1",
"react-native": "0.75.3",
"react-native-fast-image": "^8.6.3",
"react-native-gesture-handler": "^2.20.0",
"react-native-localize": "^3.2.1",
"react-native-mmkv": "^2.12.2",
"react-native-network-logger": "^1.17.0",
"react-native-reanimated": "^3.15.3",
"react-native-safe-area-context": "^4.11.0",
"react-native-screens": "^3.34.0",
"react-native-svg": "^15.7.1",
"react-redux": "^9.1.2",
"redux": "^5.0.1",
"redux-persist": "^6.0.0",
"redux-thunk": "^3.1.0",
"yup": "^1.4.0"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@babel/preset-env": "^7.25.4",
"@babel/runtime": "^7.25.6",
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0",
"@react-native/babel-preset": "0.75.3",
"@react-native/eslint-config": "0.75.3",
"@react-native/metro-config": "0.75.3",
"@react-native/typescript-config": "0.75.3",
"@types/i18n-js": "^3.8.9",
"@types/jest": "^29.5.13",
"@types/react": "^18.3.9",
"@types/react-test-renderer": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^8.7.0",
"@typescript-eslint/parser": "^8.7.0",
"babel-jest": "^29.7.0",
"babel-plugin-module-resolver": "^5.0.2",
"eslint": "^9.11.1",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.30.0",
"eslint-plugin-import-order-autofix": "^0.8.3",
"eslint-plugin-no-inline-styles": "^1.0.5",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-native": "^4.1.0",
"eslint-plugin-sort-destructure-keys": "^2.0.0",
"eslint-plugin-sort-keys-fix": "^1.1.2",
"husky": "^9.1.6",
"jest": "^29.7.0",
"prettier": "3.3.3",
"react-native-dotenv": "^3.4.11",
"react-native-svg-transformer": "^1.5.0",
"react-test-renderer": "18.3.1",
"typescript": "5.6.2"
},
"engines": {
"node": ">=18"
},
"resolutions": {
"@types/react": "^18.0.24"
},
"eslintIgnore": [
"node_modules/",
"lib/"
]
}
================================================
FILE: templates/CliTemplate/react-native.config.js
================================================
module.exports = {
assets: ['./src/assets/fonts'],
project: {
android: {},
ios: {},
},
};
================================================
FILE: templates/CliTemplate/scripts/generateScreenFile.js
================================================
/* eslint-disable no-console */
const fs = require('fs');
const path = require('path');
// get folder name from terminal argument
const folderName = process.argv[2];
if (!folderName) {
console.error('Please provide a folder name');
process.exit(1);
}
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// create the folder
fs.mkdir(`../src/screens/${capitalizeFirstLetter(folderName)}`, err => {
if (err) throw err;
console.log(`Folder ${folderName} created successfully`);
const fileName = capitalizeFirstLetter(folderName);
const useHookFileName = capitalizeFirstLetter(fileName);
// create hook js hookFile.ts
const hookFile = `import { useAppContext } from '@src/context';
import { ${folderName}Styles } from './${fileName}.style';
const use${useHookFileName} = () => {
const { color, navigation } = useAppContext();
// add your code here
return {
navigation,
styles: ${folderName}Styles(color),
};
};
export default use${useHookFileName};
`;
fs.writeFileSync(
path.join(`../src/screens/${fileName}`, `use${useHookFileName}.ts`),
hookFile,
errHook => {
if (errHook) throw errHook;
console.log(`use${fileName}.ts file created successfully`);
}
);
// create styleFile.ts
const styleFile = `import { StyleSheet } from 'react-native';
import { Palette } from '@src/utils';
export const ${folderName}Styles = ({}: Palette) =>
StyleSheet.create({
container: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
});
`;
fs.writeFileSync(
path.join(`../src/screens/${fileName}`, `${fileName}.style.ts`),
styleFile,
errStyles => {
if (errStyles) throw errStyles;
console.log(`${fileName}.style.ts file created successfully`);
}
);
// create defaultScreen.tsx
const defaultScreen = `import React from 'react';
import { View } from 'react-native';
import { Text } from '@app/blueprints';
import use${useHookFileName} from './use${useHookFileName}';
const ${useHookFileName}Screen = () => {
const { styles } = use${useHookFileName}();
return (
${useHookFileName} Screen
);
};
export default React.memo(${useHookFileName}Screen);
`;
fs.writeFileSync(
path.join(`../src/screens/${fileName}`, `${fileName}Screen.tsx`),
defaultScreen,
errScreen => {
if (errScreen) throw errScreen;
console.log(`${fileName}Screen.tsx file created successfully`);
}
);
const exportToIndex = `export { default as ${useHookFileName}Screen } from './${fileName}/${fileName}Screen';\n`;
fs.appendFile(`../src/screens/index.ts`, exportToIndex, errScreen => {
if (errScreen) throw errScreen;
console.log(`${useHookFileName} file created successfully`);
});
});
================================================
FILE: templates/CliTemplate/scripts/icons.js
================================================
const fs = require('fs');
const path = require('path');
const iconFileNames = () => {
const array = fs
.readdirSync('../src/assets/icons')
.filter(file => {
return ['gif', 'jpeg', 'jpg', 'png', 'webp'].includes(file.split('.')[1]);
})
.map(file => {
const ext = path.parse(file).ext;
return file.split('@').length > 1 &&
['1x', '2x', '3x'].includes(file.split('@')[1].split('.')[0])
? file.replace(`@2x${ext}`, `${ext}`).replace(`@3x${ext}`, `${ext}`)
: file;
});
return Array.from(new Set(array));
};
const generate = () => {
let properties = iconFileNames()
.map(name => {
const iconName = path.parse(name).name.toUpperCase();
return `${iconName}_ICONS = require('./${name}'),`;
})
.join('\n ');
const string = `export enum Icons {
${properties}
}
`;
fs.writeFileSync('../src/assets/icons/index.ts', string, 'utf8');
};
generate();
================================================
FILE: templates/CliTemplate/scripts/images.js
================================================
const fs = require('fs');
const path = require('path');
const imageFileNames = () => {
const array = fs
.readdirSync('../src/assets/images')
.filter(file => {
return ['gif', 'jpeg', 'jpg', 'png', 'webp'].includes(file.split('.')[1]);
})
.map(file => {
const ext = path.parse(file).ext;
return file.split('@').length > 1 &&
['1x', '2x', '3x'].includes(file.split('@')[1].split('.')[0])
? file.replace(`@2x${ext}`, `${ext}`).replace(`@3x${ext}`, `${ext}`)
: file;
});
return Array.from(new Set(array));
};
const generate = () => {
let properties = imageFileNames()
.map(name => {
const imageName = path.parse(name).name.toUpperCase().replace(/\s/g, '_');
return `${imageName}_IMAGE = require('./${name}'),`;
})
.join('\n ');
const string = `export enum Images {
${properties}
}
`;
fs.writeFileSync('../src/assets/images/index.ts', string, 'utf8');
};
generate();
================================================
FILE: templates/CliTemplate/scripts/refresh.sh
================================================
echo "START_CLEAR"
rm -rf node_modules
echo "node_modules removed"
rm -rf Gemfile.lock
echo "Gemfile.lock removed"
rm -rf vendor
echo "Bundle file removed"
rm -rf yarn.lock
echo "yarn.lock removed"
rm -rf android/build
echo "android/build removed"
rm -rf android/app/build
echo "android/app/build removed"
rm -rf ios/Pods/
echo "ios/Pods/ removed"
rm -rf ios/Podfile.lock
echo "ios/Podfile.lock removed"
rm -rf android/.idea/
echo "android/.idea/ removed"
echo "CLEAR_DONE - START_YARN"
yarn
echo "YARN_DONE - Start Bundle iOS"
bundle
echo "bundle done - Start_pod install"
npx pod-install --ios
echo "Finished"
================================================
FILE: templates/CliTemplate/scripts/svgIcons.js
================================================
const fs = require('fs');
const path = require('path');
const iconFileNames = () => {
const array = fs
.readdirSync('../src/assets/svgIcons')
.filter(file => {
return file.endsWith('.svg');
})
.map(file => {
return file.replace('@2x.svg', '').replace('@3x.svg', '');
});
return Array.from(new Set(array));
};
const generate = () => {
let properties = iconFileNames()
.map(name => {
const iconName = path.parse(name).name.toUpperCase();
return `import ${iconName}_ICON from './${name}';`;
})
.join('\n');
let exportFiles = iconFileNames()
.map((name, index) => {
const iconName = path.parse(name).name.toUpperCase();
return `${iconName} = ${index + 1},`;
})
.join('\n ');
let mapper = iconFileNames()
.map((name, index) => {
const iconName = path.parse(name).name.toUpperCase();
return `${index + 1}: ${iconName}_ICON,`;
})
.join('\n ');
const string = `${properties}\n\nexport enum SVGIcons {\n ${exportFiles}
}\n\nexport const SVGIconsMapper = {\n ${mapper}
};\n`;
fs.writeFileSync('../src/assets/svgIcons/index.ts', string, 'utf8');
};
generate();
================================================
FILE: templates/CliTemplate/src/MainApp.tsx
================================================
import React from 'react';
import { IndicatorView } from '@app/blueprints';
import { NavigationContainer } from '@react-navigation/native';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { LocalizationProvider, ThemeProvider } from './context';
import { AppNavigation, navigationRef } from './navigation/AppNavigation';
import store, { persistor } from './store';
import { loader } from './utils';
export const MainApp = () => {
return (
{/**
* PersistGate delays the rendering of the app's UI until the persisted state has been retrieved
* and saved to redux.
* The `loading` prop can be `null` or any react instance to show during loading (e.g. a splash screen),
* for example `loading={}`.
* @see https://github.com/rt2zz/redux-persist/blob/master/docs/PersistGate.md
*/}
);
};
================================================
FILE: templates/CliTemplate/src/assets/icons/index.ts
================================================
export enum Icons {
DEBUG_ICONS = require('./debug.png'),
}
================================================
FILE: templates/CliTemplate/src/assets/images/index.ts
================================================
export enum Images {
PLACEHOLDER_IMAGE = require('./placeholder.webp'),
}
================================================
FILE: templates/CliTemplate/src/assets/index.ts
================================================
export * from './images';
export * from './icons';
export * from './svgIcons';
================================================
FILE: templates/CliTemplate/src/assets/svgIcons/index.ts
================================================
import SETTING_ICON from './setting.svg';
export enum SVGIcons {
SETTING = 1,
}
export const SVGIconsMapper = {
1: SETTING_ICON,
};
================================================
FILE: templates/CliTemplate/src/components/AppIcon/AppIcon.tsx
================================================
import React from 'react';
// eslint-disable-next-line no-restricted-imports
import { Image, ImageProps } from 'react-native';
import { SvgProps } from 'react-native-svg';
import { Icons, SVGIcons, SVGIconsMapper } from '@src/assets';
import { scaled } from '@src/utils';
export type IconProps = Omit & {
icon: Icons;
};
export const Icon = (props: IconProps) => {
const { icon } = props;
return (
);
};
/**
* SVG ICON
*/
export type SVGIconProps = SvgProps & {
icon: SVGIcons;
height?: number | string;
width?: number | string;
pathFill?: string;
};
export const SvgIcon = (props: SVGIconProps) => {
const { icon, pathFill = '#FFF' } = props;
const IconsImage = SVGIconsMapper[icon];
return ;
};
================================================
FILE: templates/CliTemplate/src/components/AppImage/AppImage.tsx
================================================
import React from 'react';
import { Image, ImageProps } from '@app/blueprints';
import { Images } from '@src/assets';
export type ImageSource = Images | string;
export interface AppImageProps extends Omit {
source: ImageSource;
}
export const AppImage = (props: AppImageProps) => {
return (
);
};
================================================
FILE: templates/CliTemplate/src/components/BaseLayout/BaseLayout.tsx
================================================
import React from 'react';
import {
SafeAreaView,
StatusBar,
StyleProp,
StyleSheet,
ViewStyle,
} from 'react-native';
import { useColor } from '@src/context';
import { Palette } from '@src/utils';
export type BaseLayoutProps = React.PropsWithChildren & {
style?: StyleProp;
};
export const BaseLayout = React.memo(({ children, style }: BaseLayoutProps) => {
const { appTheme, color } = useColor();
const styles = baseLayoutStyles(color);
return (
{children}
);
});
export const baseLayoutStyles = ({ backgroundColor }: Palette) =>
StyleSheet.create({
safeAreaStyle: {
backgroundColor: backgroundColor,
flex: 1,
},
});
================================================
FILE: templates/CliTemplate/src/components/index.ts
================================================
export * from './BaseLayout/BaseLayout';
export * from './AppImage/AppImage';
export * from './AppIcon/AppIcon';
================================================
FILE: templates/CliTemplate/src/constants/config.ts
================================================
import { API_URL, ENV } from '@env';
export const AppConfig = {
API_URL,
ENV,
};
================================================
FILE: templates/CliTemplate/src/constants/index.ts
================================================
export * from './config';
export * from './platform';
export * from './storageKeys';
================================================
FILE: templates/CliTemplate/src/constants/platform.ts
================================================
import { Platform } from 'react-native';
const isAndroid = Platform.OS === 'android';
const isIOS = Platform.OS === 'ios';
export { isAndroid, isIOS, Platform };
================================================
FILE: templates/CliTemplate/src/constants/storageKeys.ts
================================================
export enum StorageKeys {
APP_THEME = 'APP_THEME',
APP_LANGUAGE = 'APP_LANGUAGE',
FIRST_LAUNCH = 'FIRST_LAUNCH',
PROFILE_DATA = 'PROFILE_DATA',
}
export type STORAGES_KEY = StorageKeys;
================================================
FILE: templates/CliTemplate/src/context/LocalizationContext.tsx
================================================
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { StorageKeys } from '@src/constants';
import i18n, { ContentLanguage } from '@src/i18n';
import { storage } from './storage';
export type LocalizationAppContextType = {
/**
* This variable is of type ContentLanguage and is used to store the language of content.
* language = "English";
*/
language: ContentLanguage;
/**
* For setLanguage change content lang
* @example i18n.locale = ContentLanguage.France
* @return void change app content language.
*/
setLanguageInApp: (lang: ContentLanguage) => void;
};
export const LocalizationAppContext = createContext<
LocalizationAppContextType | undefined
>(undefined);
export const useLanguage = () => {
const context = useContext(LocalizationAppContext);
if (!context)
throw Error('useLanguage must be used inside LocalizationAppContext');
return context;
};
export const LocalizationProvider = ({ children }: React.PropsWithChildren) => {
const [language, setLanguage] = useState(
ContentLanguage.English
);
/**
* For setLanguage change content lang
* i18n.locale = ContentLanguage.France
* @return void change app content language.
*/
const setLanguageInApp = useCallback((lang: ContentLanguage) => {
storage.setData(StorageKeys.APP_LANGUAGE, lang);
i18n.locale = lang;
setLanguage(lang);
}, []);
const value: LocalizationAppContextType = useMemo(() => {
return {
language,
setLanguageInApp,
};
}, [language, setLanguageInApp]);
useEffect(() => {
const appLanguage = storage.getData(StorageKeys.APP_LANGUAGE);
if (appLanguage) {
setLanguageInApp(appLanguage);
}
}, [setLanguageInApp]);
return (
{children}
);
};
================================================
FILE: templates/CliTemplate/src/context/ThemeContext.tsx
================================================
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { useColorScheme } from 'react-native';
import { StorageKeys } from '@src/constants';
import { color, Palette, Theme } from '@src/utils';
import { storage } from './storage';
export interface AppThemeContextType {
/**
* The appTheme variable is used to define the color scheme used for the application. It takes a ColorSchemeName as its value.
*/
appTheme: Theme;
/**
* This function is used to set the theme of the application. It takes a single argument, _theme, which should be of type ColorSchemeName.
* @example setAppTheme('dark');
* @param theme ColorSchemeName
* @returns void
*/
setAppTheme: (theme: Theme) => void;
/**
* Get app palette colors.
*/
color: Palette;
}
export const AppThemeContext = createContext(
undefined
);
export const useColor = () => {
const context = useContext(AppThemeContext);
if (!context) throw Error('useColor must be used inside AppThemeContext');
return context;
};
export const ThemeProvider = ({ children }: React.PropsWithChildren) => {
const colorScheme = useColorScheme();
const [appTheme, setTheme] = useState(colorScheme);
/**
* For setAppTheme change app theming.
* setTheme(ColorSchemeName)
* @return void change app Theme.
*/
const setAppTheme = useCallback((theme: Theme) => {
storage.setData(StorageKeys.APP_THEME, theme);
setTheme(theme);
}, []);
const value: AppThemeContextType = useMemo(() => {
return {
appTheme,
color: color[appTheme || 'light'],
setAppTheme,
};
}, [appTheme, setAppTheme]);
useEffect(() => {
const theme = storage.getData(StorageKeys.APP_THEME);
if (theme) {
setTheme(theme);
} else {
setTheme(colorScheme);
}
}, [colorScheme, setAppTheme]);
return (
{children}
);
};
================================================
FILE: templates/CliTemplate/src/context/content.ts
================================================
import { TranslateOptions } from 'i18n-js';
import i18n, { TxKeyPath } from '../i18n';
/**
* Translates text.
*
* @param key The i18n key.
* @param options The i18n options.
* @returns The translated text.
*
* @example
* Translations:
*
* ```en.json
* {
* "hello": "Hello, {{name}}!"
* }
* ```
*
* Usage:
* ```ts
* import { contents } from '@src/context';
*
* contents("common.hello", { name: "world" })
* => "Hello world!"
* ```
*/
export const contents = (key: TxKeyPath, options?: TranslateOptions) => {
return i18n.t(key, options);
};
================================================
FILE: templates/CliTemplate/src/context/context.ts
================================================
import { loader } from '@src/utils';
import { useLanguage } from './LocalizationContext';
import { storage } from './storage';
import { useColor } from './ThemeContext';
import { AppNavigationProp } from '../navigation/appNavigation.type';
import {
useWithNavigation,
WithNavigation,
} from '../navigation/withNavigation';
import { appServices } from '../services/appServices';
export const useAppContextOnly = () => {
const color = useColor();
const { ...language } = useLanguage();
return {
loader: loader,
services: appServices,
storage,
...color,
...language,
};
};
export type AppContextType = ReturnType;
export const useAppContext = (): WithNavigation<
AppNavigationProp,
AppContextType
> => {
return useWithNavigation(
useAppContextOnly()
);
};
================================================
FILE: templates/CliTemplate/src/context/index.ts
================================================
export * from './context';
export * from './storage';
export * from './content';
export * from './ThemeContext';
export * from './LocalizationContext';
================================================
FILE: templates/CliTemplate/src/context/storage.ts
================================================
import { MMKV } from 'react-native-mmkv';
import { Storage as ReduxStorage } from 'redux-persist';
import type { STORAGES_KEY } from '@src/constants';
import { logger } from '@src/utils';
export type dataStoreType = 'string' | 'boolean' | 'number' | 'object';
export const storageMmkv = new MMKV();
export const getData = (key: STORAGES_KEY, _type?: dataStoreType) => {
try {
const data = storageMmkv.getString(key);
if (data) {
const parseData = JSON.parse(data);
return parseData;
}
} catch (error) {
logger('storage getData', error);
}
};
export const setData = (key: STORAGES_KEY, value: any) => {
try {
if (typeof value === 'boolean') {
storageMmkv.set(key, value);
} else if (typeof value === 'number') {
storageMmkv.set(key, value);
} else {
const jsonValue = JSON.stringify(value);
storageMmkv.set(key, jsonValue);
}
} catch (error) {
logger('storage setData', error);
}
};
export const getStorageKey = () => {
const keys = storageMmkv.getAllKeys();
return keys;
};
export const deleteStorage = (key: STORAGES_KEY) => {
return storageMmkv.delete(key);
};
export const storage = {
deleteStorage,
getData,
getStorageKey,
setData,
};
export const reduxStorage: ReduxStorage = {
getItem: key => {
const value = storageMmkv.getString(key);
return Promise.resolve(value);
},
removeItem: key => {
storageMmkv.delete(key);
return Promise.resolve();
},
setItem: (key, value) => {
storageMmkv.set(key, value);
return Promise.resolve(true);
},
};
export type Storage = typeof storage;
================================================
FILE: templates/CliTemplate/src/hooks/index.ts
================================================
export * from './useDebounce';
export * from './useIsFirstRender';
export * from './useIsMounted';
export * from './useTimer';
================================================
FILE: templates/CliTemplate/src/hooks/useBackHandler.ts
================================================
import { useEffect } from 'react';
import { BackHandler } from 'react-native';
export const useBackHandler = () => {
useEffect(() => {
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
() => {
BackHandler.exitApp();
return true;
}
);
return () => backHandler.remove();
}, []);
};
================================================
FILE: templates/CliTemplate/src/hooks/useDebounce.ts
================================================
import { useEffect, useState } from 'react';
export function useDebounce(value: T, delay?: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay || 500);
return () => {
clearTimeout(timer);
};
}, [value, delay]);
return debouncedValue;
}
================================================
FILE: templates/CliTemplate/src/hooks/useIsFirstRender.ts
================================================
import { useRef } from 'react';
export const useIsFirstRender = (): boolean => {
const isFirst = useRef(true);
if (isFirst.current) {
isFirst.current = false;
return true;
}
return isFirst.current;
};
================================================
FILE: templates/CliTemplate/src/hooks/useIsMounted.ts
================================================
import * as React from 'react';
export const useIsMounted = () => {
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
};
================================================
FILE: templates/CliTemplate/src/hooks/useTimer.ts
================================================
import { useEffect, useRef } from 'react';
type ClearTimerFn = (id: number | undefined) => void;
type RunTimerFn = (handler: () => void, timeout: number) => number;
const creteUseTimer =
(clear: ClearTimerFn, runTimer: RunTimerFn) =>
(callback: () => void, delay: number): void => {
const timerRef = useRef();
useEffect(() => {
const stop = () => clear(timerRef.current);
stop();
timerRef.current = runTimer(callback, delay);
return stop;
}, [callback, delay]);
};
export const useInterval = creteUseTimer(
clearInterval as ClearTimerFn,
setInterval
);
export const useTimeout = creteUseTimer(
clearTimeout as ClearTimerFn,
setTimeout
);
================================================
FILE: templates/CliTemplate/src/i18n/index.ts
================================================
import { I18n } from 'i18n-js';
import * as RNLocalize from 'react-native-localize';
import en from './locales/en.json';
import hi from './locales/hi.json';
const locales = RNLocalize.getLocales();
const i18n = new I18n();
if (Array.isArray(locales)) {
i18n.locale = locales[0]?.languageTag ? locales[0].languageTag : 'en';
}
export const locale = locales[0]?.languageCode;
i18n.enableFallback = true;
i18n.defaultLocale = 'en';
i18n.translations = {
en,
hi,
};
export default i18n;
export enum ContentLanguage {
English = 'en',
Hindi = 'hi',
}
export type TxKeyPath = RecursiveKeyOf;
// via: https://stackoverflow.com/a/65333050
type RecursiveKeyOf = {
[TKey in keyof TObj & (string | number)]: RecursiveKeyOfHandleValue<
TObj[TKey],
`${TKey}`
>;
}[keyof TObj & (string | number)];
type RecursiveKeyOfInner = {
[TKey in keyof TObj & (string | number)]: RecursiveKeyOfHandleValue<
TObj[TKey],
`['${TKey}']` | `.${TKey}`
>;
}[keyof TObj & (string | number)];
type RecursiveKeyOfHandleValue<
TValue,
Text extends string
> = TValue extends any[]
? Text
: TValue extends object
? Text | `${Text}${RecursiveKeyOfInner}`
: Text;
================================================
FILE: templates/CliTemplate/src/i18n/locales/en.json
================================================
{
"common": {
"cancel": "Cancel",
"create": "Create",
"delete": "Delete",
"errorMessage": "Unknown error..!!!",
"hey": "Hey there,",
"ohhNo": "Ohh Noo!!!",
"or": "Or",
"ok": "OK",
"save": "Save",
"see_more": "See More",
"skip": "Skip",
"welcome": "Welcome",
"yes": "Yes",
"hello": "Hello {{name}}!",
"internetConnectionError": "Please check you internet connectivity."
},
"newsList": {
"breakingNews": "Breaking News",
"general": "general"
},
"newsDetail": {
"anonymous": "anonymous"
},
"forceUpdate": {
"update": "Update",
"updateMessage": "We've release a new version of the App!\nPlease update your app to enjoy these new features.",
"retry": "Try again"
},
"setting": {
"languages": "Languages",
"settingScreen": "Setting Screen",
"theme": "Theme"
},
"login": {
"log_in": "Log-in",
"email": "Email",
"yourEmailId": "Your Email ID",
"password": "Password",
"login": "Login",
"don'tHaveAnAccount": "Don't have an account ?",
"sign_up": "Sign-up"
},
"signUp": {
"sign_up": "Sign-up",
"name": "Name",
"email": "Email",
"yourEmailId": "Your Email ID",
"password": "Password",
"confirmPassword": "Confirm Password",
"signUp": "SignUp"
}
}
================================================
FILE: templates/CliTemplate/src/i18n/locales/hi.json
================================================
{
"common": {
"cancel": "रद्द करना",
"create": "बनाएं",
"delete": "मिटाना",
"errorMessage": "अज्ञात त्रुटि..!!!",
"hey": "सुनो,",
"ohhNo": "ओह तेरी!!!",
"or": "या",
"ok": "ठीक",
"save": "बचाना",
"see_more": "और देखें",
"skip": "छोड़ें",
"welcome": "स्वागत",
"yes": "हाँ",
"internetConnectionError": "कृपया आप इंटरनेट कनेक्टिविटी की जाँच करें।"
},
"newsList": {
"breakingNews": "आज की ताजा खबर",
"general": "आम"
},
"newsDetail": {
"anonymous": "अनाम"
},
"setting": {
"languages": "भाषा",
"settingScreen": "स्क्रीन सेट करना",
"theme": "विषय-वस्तु"
}
}
================================================
FILE: templates/CliTemplate/src/navigation/AppNavigation.tsx
================================================
import React from 'react';
import { NavigationContainerRef } from '@react-navigation/native';
import {
createNativeStackNavigator,
NativeStackNavigationOptions,
} from '@react-navigation/native-stack';
import { useSelector } from 'react-redux';
import {
LoginScreen,
NetworkLoggerScreen,
NewsDetailScreen,
NewsListScreen,
SettingScreen,
} from '@src/screens';
import { isForceUpdate } from '@src/store';
import { NavStackParams, Screen } from './appNavigation.type';
import { ForUpdateStack } from './ForceupdateStack';
export const navigationRef =
React.createRef>();
const Stack = createNativeStackNavigator();
const screenOptions: NativeStackNavigationOptions = {
animation: 'slide_from_right',
headerShown: false,
};
export const AppNavigation = () => {
const isForceUpdateApp = useSelector(isForceUpdate);
return (
<>
{isForceUpdateApp ? (
) : (
{__DEV__ && (
)}
)}
>
);
};
================================================
FILE: templates/CliTemplate/src/navigation/ForceupdateStack.tsx
================================================
import React from 'react';
import { NavigationContainerRef } from '@react-navigation/native';
import {
createNativeStackNavigator,
NativeStackNavigationOptions,
} from '@react-navigation/native-stack';
import { ForceUpdateScreen, NetworkLoggerScreen } from '@src/screens';
import { NavStackParams, Screen } from './appNavigation.type';
export const navigationRef =
React.createRef>();
const ForceUpdateStack = createNativeStackNavigator();
const screenOptions: NativeStackNavigationOptions = {
animation: 'slide_from_right',
headerShown: false,
};
export const ForUpdateStack = () => {
return (
{__DEV__ && (
)}
);
};
================================================
FILE: templates/CliTemplate/src/navigation/appNavigation.type.ts
================================================
import type { RouteProp } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { NewsResult } from '@src/services';
export enum Screen {
FORCE_UPDATE_SCREEN = 'FORCE_UPDATE_SCREEN',
NETWORK_CHECK = 'NETWORK_CHECK',
NEWS_DETAIL = 'NEWS_DETAIL',
NEWS_LIST = 'NEWS_LIST',
SETTING = 'SETTING',
LOGIN = 'LOGIN',
SIGNUP = 'SIGNUP',
}
export type NavStackParams = {
[Screen.FORCE_UPDATE_SCREEN]: undefined;
[Screen.NETWORK_CHECK]: undefined;
[Screen.NEWS_DETAIL]: NewsDetailParams;
[Screen.NEWS_LIST]: undefined;
[Screen.SETTING]: undefined;
[Screen.LOGIN]: undefined;
[Screen.SIGNUP]: undefined;
};
export type NewsDetailParams = {
item: NewsResult;
};
export type AppNavigationProp = NativeStackNavigationProp;
export type NewsDetailRoute = RouteProp;
================================================
FILE: templates/CliTemplate/src/navigation/withNavigation.ts
================================================
import {
NavigationProp,
ParamListBase,
useNavigation,
} from '@react-navigation/native';
export declare type WithNavigation<
NavProp extends NavigationProp,
T
> = {
navigation: NavProp;
} & T;
export function useWithNavigation<
NavProp extends NavigationProp,
T extends object
>(data: T): WithNavigation {
const navigation = useNavigation();
return { ...data, navigation };
}
================================================
FILE: templates/CliTemplate/src/screens/ErrorBoundary/ErrorBoundary.tsx
================================================
import React, { ErrorInfo, ReactNode } from 'react';
// import { ErrorDetails } from "./ErrorDetails"
interface Props {
children: ReactNode;
catchErrors: 'always' | 'dev' | 'prod' | 'never';
}
interface State {
error: Error | null;
errorInfo: ErrorInfo | null;
}
/**
* This component handles whenever the user encounters a JS error in the
* app. It follows the "error boundary" pattern in React. We're using a
* class component because according to the documentation, only class
* components can be error boundaries.
*
* - [Documentation and Examples](https://github.com/infinitered/ignite/blob/master/docs/Error-Boundary.md)
* - [React Error Boundaries](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
*/
export class ErrorBoundary extends React.Component {
state = { error: null, errorInfo: null };
// If an error in a child is encountered, this will run
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// Only set errors if enabled
if (!this.isEnabled()) {
return;
}
// Catch errors in any components below and re-render with error message
this.setState({
error,
errorInfo,
});
// You can also log error messages to an error reporting service here
// This is a great place to put BugSnag, Sentry, crashlytics, etc:
// reportCrash(error)
}
// Reset the error back to null
resetError = () => {
this.setState({ error: null, errorInfo: null });
};
// To avoid unnecessary re-renders
shouldComponentUpdate(
_nextProps: Readonly,
nextState: Readonly
): boolean {
return nextState.error !== this.state.error;
}
// Only enable if we're catching errors in the right environment
isEnabled(): boolean {
return (
this.props.catchErrors === 'always' ||
(this.props.catchErrors === 'dev' && __DEV__) ||
(this.props.catchErrors === 'prod' && !__DEV__)
);
}
// Render an error UI if there's an error; otherwise, render children
render() {
return this.isEnabled() && this.state.error
? //
null
: this.props.children;
}
}
================================================
FILE: templates/CliTemplate/src/screens/ForceUpdate/ForceUpdate.style.ts
================================================
import { StyleSheet } from 'react-native';
import { Palette, scaledSize, scaleHeight, scaleWidth } from '@src/utils';
export const forceUpdateStyles = ({ backgroundColor, textColor }: Palette) =>
StyleSheet.create({
buttonContainer: {
marginTop: scaleHeight(40),
},
container: {
backgroundColor: backgroundColor,
flex: 1,
justifyContent: 'center',
paddingHorizontal: scaleWidth(35),
},
messageStyle: {
color: textColor,
fontSize: scaledSize(18),
marginBottom: scaleHeight(40),
textAlign: 'center',
},
retryButton: {
backgroundColor: backgroundColor,
borderColor: textColor,
borderWidth: scaleWidth(1),
marginTop: scaleHeight(20),
},
retryText: {
color: textColor,
},
updateText: {
color: backgroundColor,
},
});
================================================
FILE: templates/CliTemplate/src/screens/ForceUpdate/ForceUpdateScreen.tsx
================================================
import React from 'react';
import { View } from 'react-native';
import { Button, Text } from '@app/blueprints';
import { contents } from '@src/context';
import useForceUpdate from './useForceUpdate';
const ForceUpdateScreen = () => {
const { styles } = useForceUpdate();
return (
{contents('forceUpdate.updateMessage')}
);
};
export default React.memo(ForceUpdateScreen);
================================================
FILE: templates/CliTemplate/src/screens/ForceUpdate/useForceUpdate.ts
================================================
import { useCallback } from 'react';
import { Linking } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { AppConfig, isIOS } from '@src/constants';
import { useAppContext } from '@src/context';
import { logger } from '@src/utils';
import { forceUpdateStyles } from './ForceUpdate.style';
const useForceUpdate = () => {
const { color, ...props } = useAppContext();
const styles = forceUpdateStyles(color);
const onUpdatePress = useCallback(() => {
try {
const URLToOpen = isIOS
? AppConfig.APP_STORE_URL
: AppConfig.PLAY_STORE_URL;
Linking.canOpenURL(URLToOpen)
.then(res => {
res && Linking.openURL(URLToOpen);
})
.catch(error => {
logger(`Error:: ${error}`);
});
} catch (error) {
logger(`Error:: ${error}`);
}
}, []);
const onRetryPress = useCallback(() => {}, []);
useFocusEffect(
useCallback(() => {
onRetryPress();
}, [onRetryPress])
);
return {
onRetryPress,
onUpdatePress,
styles,
...props,
};
};
export default useForceUpdate;
================================================
FILE: templates/CliTemplate/src/screens/Login/Login.style.ts
================================================
import { StyleSheet } from 'react-native';
import { Palette, scaledSize, scaleHeight, scaleWidth } from '@src/utils';
export const loginStyles = ({ backgroundColor, secondaryColor }: Palette) =>
StyleSheet.create({
container: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
content: {
backgroundColor: backgroundColor,
borderRadius: scaledSize(30),
flex: 2,
paddingHorizontal: scaleWidth(15),
paddingTop: scaleHeight(25),
top: -scaleHeight(25),
},
fieldContainer: {},
header: {
backgroundColor: secondaryColor,
flex: 1,
},
input: {
marginVertical: scaleHeight(10),
},
loginBtn: {
marginTop: scaleHeight(15),
},
});
================================================
FILE: templates/CliTemplate/src/screens/Login/LoginScreen.tsx
================================================
import React from 'react';
import { View } from 'react-native';
import { Button, Text, TextInput } from '@app/blueprints';
import { Formik } from 'formik';
import { BaseLayout } from '@src/components';
import { contents } from '@src/context';
import useLogin from './useLogin';
const LoginScreen = () => {
const {
disabled,
fieldValidation,
handleButtonSubmit,
initialValues,
passwordRef,
styles,
} = useLogin();
return (
{contents('login.log_in')}
{({ resetForm, submitForm }) => (
{
passwordRef.current?.focus();
}}
/>
)}
);
};
export default React.memo(LoginScreen);
================================================
FILE: templates/CliTemplate/src/screens/Login/useLogin.ts
================================================
import { useCallback, useRef, useState } from 'react';
import { TextInput } from 'react-native';
import * as yup from 'yup';
import { useAppContext } from '@src/context';
import { logger } from '@src/utils';
import { loginStyles } from './Login.style';
const useLogin = () => {
const { color, navigation } = useAppContext();
const [disabled, setDisabled] = useState(false);
const passwordRef = useRef(null);
const fieldValidation = yup.object().shape({
email: yup.string().trim().required('Please enter your Email'),
password: yup.string().trim().required('Please enter your Password'),
});
const initialValues = {
email: '',
password: '',
};
const handleButtonSubmit = useCallback(
async (values: typeof initialValues) => {
logger('values: ', values);
setDisabled(true);
await new Promise(res => setTimeout(res, 3000));
setDisabled(false);
},
[]
);
return {
disabled,
fieldValidation,
handleButtonSubmit,
initialValues,
navigation,
passwordRef,
styles: loginStyles(color),
};
};
export default useLogin;
================================================
FILE: templates/CliTemplate/src/screens/NetworkLogger/NetworkLoggerScreen.tsx
================================================
import React from 'react';
import NetworkLogger from 'react-native-network-logger';
import { BaseLayout } from '@src/components';
const NetworkLoggerScreen = () => {
return (
);
};
export default React.memo(NetworkLoggerScreen);
================================================
FILE: templates/CliTemplate/src/screens/NewsDetail/NewsDetail.style.ts
================================================
import { StyleSheet } from 'react-native';
import { Palette, scaleHeight, scaleWidth, screenWidth } from '@src/utils';
export const newsDetailStyles = ({}: Palette) =>
StyleSheet.create({
descriptionText: {},
infoContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginVertical: scaleHeight(16),
},
newsImage: {
height: screenWidth * 0.8,
width: screenWidth - scaleWidth(20),
},
scrollViewContainer: { paddingHorizontal: scaleWidth(10) },
title: {
marginBottom: scaleHeight(15),
textAlign: 'center',
},
});
================================================
FILE: templates/CliTemplate/src/screens/NewsDetail/NewsDetailScreen.tsx
================================================
import React from 'react';
import { ScrollView, View } from 'react-native';
import { Button, Text } from '@app/blueprints';
import { AppImage, BaseLayout } from '@src/components';
import { contents } from '@src/context';
import { scaleHeight } from '@src/utils';
import useNewsDetail from './useNewsDetail';
const NewsDetailScreen = () => {
const { data, getPublishedMonth, handleGoBack, styles } = useNewsDetail();
return (
{data.title}
{data.categories
? data.categories
: contents('newsDetail.anonymous')}
{getPublishedMonth(data.published_on)}
{data.body}
);
};
export default React.memo(NewsDetailScreen);
================================================
FILE: templates/CliTemplate/src/screens/NewsDetail/useNewsDetail.ts
================================================
import { useCallback } from 'react';
import { useRoute } from '@react-navigation/native';
import { contents, useAppContext } from '@src/context';
import { newsDetailStyles } from './NewsDetail.style';
import { NewsDetailRoute } from '../../navigation/appNavigation.type';
const useNewsDetail = () => {
const { color, navigation } = useAppContext();
const {
params: { item: data },
} = useRoute();
const getPublishedMonth = useCallback((val: number) => {
const publishedAt = new Date(val).toString();
return publishedAt.split(' ').slice(0, 3).join(' ');
}, []);
const handleGoBack = useCallback(async () => {
navigation.goBack();
}, [navigation]);
return {
contents,
data,
getPublishedMonth,
handleGoBack,
navigation,
styles: newsDetailStyles(color),
};
};
export default useNewsDetail;
================================================
FILE: templates/CliTemplate/src/screens/NewsList/NewsList.style.ts
================================================
import { StyleSheet } from 'react-native';
import {
Palette,
scaled,
scaledSize,
scaleHeight,
scaleWidth,
} from '@src/utils';
export const newsListStyles = ({ backgroundColor, primaryColor }: Palette) =>
StyleSheet.create({
debugIcon: {
...scaled(25),
tintColor: primaryColor,
},
flatlistStyles: { paddingHorizontal: scaledSize(5) },
headerContainer: {
alignItems: 'center',
justifyContent: 'center',
marginVertical: scaleHeight(10),
},
networkButton: {
position: 'absolute',
right: scaleWidth(5),
},
newsImage: {
borderRadius: scaledSize(5),
height: scaleHeight(95),
width: scaleWidth(120),
},
newsItemContainer: {
backgroundColor,
borderRadius: scaledSize(5),
flex: 1,
flexDirection: 'row',
marginBottom: scaleHeight(5),
marginTop: scaleHeight(5),
},
newsTextView: {
flex: 1,
padding: scaledSize(5),
},
settingBtn: {
position: 'absolute',
right: scaleWidth(40),
},
});
================================================
FILE: templates/CliTemplate/src/screens/NewsList/NewsListScreen.tsx
================================================
import React from 'react';
import { FlatList, TouchableOpacity, View } from 'react-native';
import { AnimatedTouchableOpacity, Text } from '@app/blueprints';
import { Icons, SVGIcons } from '@src/assets';
import { AppImage, BaseLayout, Icon, SvgIcon } from '@src/components';
import { contents } from '@src/context';
import type { NewsResult } from '@src/services';
import { scaled } from '@src/utils';
import useNewsList from './useNewsList';
const NewsListScreen = () => {
const {
color,
data,
handleNavigationNetwork,
handleNavigationNewsItem,
handleSetting,
styles,
} = useNewsList();
const renderItem = ({ item }: { item: NewsResult }) => {
return (
{item?.source ? item.source : contents('newsList.general')}
{item.title}
);
};
return (
`${item.id}_${item.title}`}
renderItem={renderItem}
ListHeaderComponent={
{contents('newsList.breakingNews')}
}
/>
);
};
export default React.memo(NewsListScreen);
================================================
FILE: templates/CliTemplate/src/screens/NewsList/useNewsList.ts
================================================
import { useCallback, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { contents, useAppContext } from '@src/context';
import { NewsResult } from '@src/services';
import { getNewsData as newsData, setNews, useAppDispatch } from '@src/store';
import { logger } from '@src/utils';
import { newsListStyles } from './NewsList.style';
import { Screen } from '../../navigation/appNavigation.type';
const useNewsList = () => {
const { color, loader, navigation, services } = useAppContext();
const dispatch = useAppDispatch();
const data = useSelector(newsData);
const getNewsData = useCallback(async () => {
loader.current?.show();
try {
const getNews = await services.getNews();
dispatch(setNews(getNews));
} catch (error) {
logger('Error getNews>>', error);
} finally {
loader.current?.hide();
}
}, [loader, services, dispatch]);
const handleNavigationNetwork = useCallback(() => {
navigation.navigate(Screen.NETWORK_CHECK);
}, [navigation]);
const handleNavigationNewsItem = useCallback(
(item: NewsResult) => () => {
navigation.navigate(Screen.NEWS_DETAIL, {
item,
});
},
[navigation]
);
const handleSetting = useCallback(() => {
navigation.navigate(Screen.SETTING);
}, [navigation]);
useEffect(() => {
logger('Calling Use Effect');
getNewsData();
}, [getNewsData]);
return {
color,
contents,
data,
handleNavigationNetwork,
handleNavigationNewsItem,
handleSetting,
styles: newsListStyles(color),
};
};
export default useNewsList;
================================================
FILE: templates/CliTemplate/src/screens/Setting/Setting.style.ts
================================================
import { StyleSheet } from 'react-native';
import { Palette, scaled, scaleHeight, scaleWidth } from '@src/utils';
export const settingStyles = ({ primaryColor }: Palette) =>
StyleSheet.create({
btn: {
marginTop: scaleHeight(30),
},
content: {
marginTop: scaleHeight(25),
paddingHorizontal: scaleWidth(50),
},
header: {
alignItems: 'center',
justifyContent: 'center',
},
radio: {
...scaled(20),
alignItems: 'center',
borderRadius: 10,
borderWidth: 1,
justifyContent: 'center',
},
selectedRadio: {
...scaled(10),
backgroundColor: primaryColor,
borderRadius: 10,
},
themes: {
flexDirection: 'row',
justifyContent: 'space-between',
marginVertical: scaleHeight(5),
},
});
================================================
FILE: templates/CliTemplate/src/screens/Setting/SettingScreen.tsx
================================================
import React from 'react';
import { View } from 'react-native';
import { AnimatedTouchableOpacity, Button, Text } from '@app/blueprints';
import { BaseLayout } from '@src/components';
import { contents } from '@src/context';
import { ContentLanguage } from '@src/i18n';
import useSetting from './useSetting';
const SettingScreen = () => {
const {
appTheme,
handleChangeLanguage,
handleChangeTheme,
handleLogin,
language,
languages,
styles,
themes,
} = useSetting();
return (
{contents('setting.settingScreen')}
{contents('setting.theme')}
{themes.map(m => {
return (
{m}
{appTheme === m.toLowerCase() ? (
) : null}
);
})}
{contents('setting.languages')}
{languages.map(m => {
return (
{m}
{ContentLanguage[m as keyof typeof ContentLanguage] ===
language ? (
) : null}
);
})}
);
};
export default React.memo(SettingScreen);
================================================
FILE: templates/CliTemplate/src/screens/Setting/useSetting.ts
================================================
import { useCallback } from 'react';
import { useAppContext } from '@src/context';
import { ContentLanguage } from '@src/i18n';
import { Theme } from '@src/utils';
import { settingStyles } from './Setting.style';
import { Screen } from '../../navigation/appNavigation.type';
const themes = ['Dark', 'Light', 'Theme1', 'Theme2', 'Theme3'];
const languages = Object.keys(ContentLanguage);
const useSetting = () => {
const {
appTheme,
color,
language,
navigation,
setAppTheme,
setLanguageInApp,
} = useAppContext();
const handleChangeTheme = useCallback(
(m: string) => () => {
setAppTheme(m as Theme);
},
[setAppTheme]
);
const handleChangeLanguage = useCallback(
(m: string) => () => {
setLanguageInApp(ContentLanguage[m as keyof typeof ContentLanguage]);
},
[setLanguageInApp]
);
const handleLogin = useCallback(() => {
navigation.navigate(Screen.LOGIN);
}, [navigation]);
// add your code here
return {
appTheme,
color,
handleChangeLanguage,
handleChangeTheme,
handleLogin,
language,
languages,
navigation,
styles: settingStyles(color),
themes,
};
};
export default useSetting;
================================================
FILE: templates/CliTemplate/src/screens/index.ts
================================================
export { default as NetworkLoggerScreen } from './NetworkLogger/NetworkLoggerScreen';
export { default as NewsListScreen } from './NewsList/NewsListScreen';
export { default as NewsDetailScreen } from './NewsDetail/NewsDetailScreen';
export { default as ForceUpdateScreen } from './ForceUpdate/ForceUpdateScreen';
export { default as SettingScreen } from './Setting/SettingScreen';
export { default as LoginScreen } from './Login/LoginScreen';
================================================
FILE: templates/CliTemplate/src/services/apiHandler.ts
================================================
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { AppConfig } from '@src/constants';
class APIhandler {
private readonly axiosInstance: AxiosInstance;
private readonly axiosHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
constructor() {
this.axiosInstance = axios.create({
baseURL: AppConfig.API_URL,
headers: this.axiosHeaders,
timeout: 10000,
timeoutErrorMessage: 'Slow Network',
validateStatus(status) {
return (
(status >= 200 && status < 300) || status === 400 || status === 401
);
},
});
// ***** Uncomment lines for debugging Request *****
// this.axiosInstance.interceptors.request.use(req => {
// if (__DEV__) {
// // eslint-disable-next-line no-console
// console.log(
// '⛔️⛔️⛔️ this.axiosInstance.interceptors.request: ',
// JSON.stringify(req, null, ' ')
// );
// }
// return req;
// });
//***** Uncomment lines for debugging Response *****
// this.axiosInstance.interceptors.response.use(res => {
// if (__DEV__) {
// // eslint-disable-next-line no-console
// console.log(
// '🚀🚀🚀🚀 this.axiosInstance.interceptors.response: ',
// JSON.stringify(res, null, ' ')
// );
// }
// return res;
// });
}
requestHeader = () => {
return {
Authorization: `Bearer `,
};
};
handleBodyResponse = async (response: AxiosResponse): Promise => {
if (response.status === 200) {
return Promise.resolve(JSON.parse(JSON.stringify(response.data)));
} else if (response.status === 400) {
return Promise.reject({
cause: response.status.toString(),
message: response.data.message,
} as Error);
} else if (response.status === 401) {
return Promise.reject({
cause: response.status.toString(),
message: 'Your session has been expired..!!! please login again...',
} as Error);
} else {
return Promise.reject({
cause: response.status.toString(),
message: response.statusText,
} as Error);
}
};
postAPIService = async (api: string, reqParams: any): Promise => {
try {
const response = await this.axiosInstance.post(api, reqParams, {
headers: { ...this.axiosHeaders, ...this.requestHeader() },
});
return this.handleBodyResponse(response);
} catch (error) {
return Promise.reject(error);
}
};
async getAPIService(api: string): Promise {
try {
// get, D = any>(url: string, config?: AxiosRequestConfig): Promise;
const response = await this.axiosInstance.get(api, {
headers: { ...this.axiosHeaders, ...this.requestHeader() },
});
return this.handleBodyResponse(response);
} catch (error) {
return Promise.reject(error);
}
}
deleteAPIService = async (api: string, reqParams: any = {}): Promise => {
try {
const response = await this.axiosInstance.delete(api, {
headers: { ...this.axiosHeaders, ...this.requestHeader() },
params: reqParams,
});
return this.handleBodyResponse(response);
} catch (error) {
return Promise.reject(error);
}
};
putAPIService = async (api: string, reqParams: any = {}): Promise => {
try {
const response = await this.axiosInstance({
data: reqParams,
headers: { ...this.axiosHeaders, ...this.requestHeader() },
method: 'PUT',
url: api,
});
return this.handleBodyResponse(response);
} catch (error) {
return Promise.reject(error);
}
};
}
export const API = new APIhandler();
================================================
FILE: templates/CliTemplate/src/services/appServices.ts
================================================
import { API_METHODS } from './appServices.type';
import { ServicesEndPoints } from './appServicesEndPoints';
import { getNewsCommercialResponseAdapter } from './commercial/adapters/response/getNewsCommercialResponseAdapter';
import { GetUserCommercialResponseAdapter } from './commercial/adapters/response/getUserCommercialResponseAdapter';
import { PostLoginCommercialResponseAdapter } from './commercial/adapters/response/postLoginCommercialResponseAdapter';
import { NewsResponseDTO } from './commercial/dtos/NewsResponseDTO';
import {
LoginResponseDTO,
UserResponseDTO,
} from './commercial/dtos/UserResponseDTO';
import { ListUserReq, NewsResult, UserResult } from './models';
import { LoginParams, LoginResult } from './models/login';
import serviceAdapter from './serviceAdapter';
export class AppServices {
constructor() {}
loginUser = async (loginParams: LoginParams): Promise => {
return new Promise((resolve, reject) => {
serviceAdapter(
API_METHODS.POST,
ServicesEndPoints.LOGIN,
loginParams
)
.then(res => {
resolve(new PostLoginCommercialResponseAdapter().service(res));
})
.catch(error => {
reject(error);
});
});
};
listUsers = async (listUserReq: ListUserReq): Promise => {
return new Promise((resolve, reject) => {
serviceAdapter(
API_METHODS.GET,
`${ServicesEndPoints.USERS}?page=${listUserReq.page}&per_page=${listUserReq.per_page}`
)
.then(res => {
resolve(new GetUserCommercialResponseAdapter().service(res));
})
.catch(error => {
reject(error);
});
});
};
getNews = async (): Promise => {
return new Promise((resolve, reject) => {
serviceAdapter(
API_METHODS.GET,
ServicesEndPoints.NEWS
)
.then(res => {
resolve(new getNewsCommercialResponseAdapter().service(res));
})
.catch(error => {
reject(error);
});
});
};
}
export const appServices = new AppServices();
================================================
FILE: templates/CliTemplate/src/services/appServices.type.ts
================================================
export enum API_METHODS {
DELETE = 'DELETE',
GET = 'GET',
POST = 'POST',
PUT = 'PUT',
}
================================================
FILE: templates/CliTemplate/src/services/appServicesEndPoints.ts
================================================
export enum ServicesEndPoints {
USERS = '/users',
LOGIN = '/login',
NEWS = '/news/',
}
================================================
FILE: templates/CliTemplate/src/services/commercial/adapters/response/getNewsCommercialResponseAdapter.ts
================================================
import { NewsResult } from '../../../models';
import { NewDataResponse, NewsResponseDTO } from '../../dtos/NewsResponseDTO';
export class getNewsCommercialResponseAdapter {
constructor() {}
service(dto: NewsResponseDTO): NewsResult[] {
return dto.Data.map((item: NewDataResponse) => {
return {
body: item.body,
categories: item.categories,
id: item.id,
imageUrl: item.imageurl,
published_on: item.published_on,
source: item.source,
tags: item.tags,
title: item.title,
};
});
}
}
================================================
FILE: templates/CliTemplate/src/services/commercial/adapters/response/getUserCommercialResponseAdapter.ts
================================================
import { UserResult } from '@src/services/models/user';
import { UserResponseDTO } from '../../dtos/UserResponseDTO';
export class GetUserCommercialResponseAdapter {
constructor() {}
service(dto: UserResponseDTO): UserResult[] {
return dto.data.map(item => {
return {
firstName: item.first_name,
id: item.id,
lastName: item.last_name,
};
});
}
}
================================================
FILE: templates/CliTemplate/src/services/commercial/adapters/response/postLoginCommercialResponseAdapter.ts
================================================
import { LoginResult } from '@src/services/models/login';
import { LoginResponseDTO } from '../../dtos/UserResponseDTO';
export class PostLoginCommercialResponseAdapter {
constructor() {}
service(dto: LoginResponseDTO): LoginResult {
return {
userToken: dto.token,
};
}
}
================================================
FILE: templates/CliTemplate/src/services/commercial/dtos/NewsResponseDTO.ts
================================================
export interface NewsResponseDTO {
Type: number;
Message: string;
Promoted?: null[] | null;
Data: NewDataResponse[];
RateLimit: Object;
HasWarning: boolean;
}
export interface NewDataResponse {
id: string;
guid?: string;
published_on: number;
imageurl: string;
title: string;
url?: string;
body: string;
tags: string;
lang?: string;
upvotes?: string;
downvotes?: string;
categories: string;
source_info?: SourceInfo;
source: string;
}
export interface SourceInfo {
name: string;
img: string;
lang: string;
}
================================================
FILE: templates/CliTemplate/src/services/commercial/dtos/UserResponseDTO.ts
================================================
export interface UserResponseDTO {
page: number;
per_page: number;
total: number;
total_pages: number;
data: DatumDTO[];
support: SupportDTO;
}
export interface DatumDTO {
id: number;
email: string;
first_name: string;
last_name: string;
avatar: string;
}
export interface SupportDTO {
url: string;
text: string;
}
export interface LoginResponseDTO {
token: string;
}
================================================
FILE: templates/CliTemplate/src/services/index.ts
================================================
export * from './apiHandler';
export * from './appServicesEndPoints';
export * from './serviceAdapter';
export * from './models';
export * from './appServices';
================================================
FILE: templates/CliTemplate/src/services/models/index.ts
================================================
export * from './unknown';
export * from './user';
export * from './news';
================================================
FILE: templates/CliTemplate/src/services/models/login.ts
================================================
export interface LoginResult {
userToken: string;
}
export interface LoginParams {
email: string;
password: string;
}
================================================
FILE: templates/CliTemplate/src/services/models/news.ts
================================================
export interface Source {
id?: null | string | number;
name: string;
}
export interface NewsResult {
body: string;
categories: string;
id: string;
imageUrl: string;
published_on: number;
source: string;
tags: string;
title: string;
}
================================================
FILE: templates/CliTemplate/src/services/models/unknown.ts
================================================
export interface ApiUnknownResponse {}
export interface ApiUnknownRequestParams {}
export interface UnknownResponse {}
================================================
FILE: templates/CliTemplate/src/services/models/user.ts
================================================
export interface ListUserReq {
page: number;
per_page: number;
}
export interface UserResult {
firstName: string;
id: number;
lastName: string;
}
================================================
FILE: templates/CliTemplate/src/services/serviceAdapter.ts
================================================
import { isNetworkConnected } from '@src/utils';
import { API } from './apiHandler';
import { API_METHODS } from './appServices.type';
import { contents } from '../context/content';
export default async function serviceAdapter(
method: API_METHODS,
url: string,
requestParam?: reqParams
): Promise {
const status = await isNetworkConnected();
if (status) {
if (method.toString() === API_METHODS.GET) {
return API.getAPIService(url);
} else if (method.toString() === API_METHODS.DELETE) {
return API.deleteAPIService(url, requestParam);
} else if (method.toString() === API_METHODS.PUT) {
return API.putAPIService(url, requestParam);
} else if (method.toString() === API_METHODS.POST) {
return API.postAPIService(url, requestParam);
} else {
return Promise.reject('REST METHOD NOT EXITSt');
}
} else {
return Promise.reject(Error(contents('common.internetConnectionError')));
}
}
================================================
FILE: templates/CliTemplate/src/store/index.ts
================================================
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import { useDispatch } from 'react-redux';
import {
FLUSH,
PAUSE,
PERSIST,
PersistConfig,
persistReducer,
persistStore,
PURGE,
REGISTER,
REHYDRATE,
} from 'redux-persist';
import { reduxStorage } from '@src/context';
import { newsData, newsDataName, userData } from './reducers';
const rootReducer = combineReducers({
newsData,
userData,
});
export type RootState = ReturnType;
const persistConfig: PersistConfig = {
key: 'root',
storage: reduxStorage,
whitelist: [newsDataName],
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
devTools: true,
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
thunk: {
extraArgument: {},
},
}),
reducer: persistedReducer,
});
export const persistor = persistStore(store);
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch();
export default store;
export * from './reducers';
export * from './observers';
================================================
FILE: templates/CliTemplate/src/store/observers/index.ts
================================================
export * from './users';
export * from './news';
================================================
FILE: templates/CliTemplate/src/store/observers/news.ts
================================================
import { RootState } from '../index';
export const getNewsData = (state: RootState) => state.newsData.news;
================================================
FILE: templates/CliTemplate/src/store/observers/users.ts
================================================
import { RootState } from '../index';
export const usersData = (state: RootState) => state.userData.users;
export const isForceUpdate = (state: RootState) => state.userData.isForceUpdate;
================================================
FILE: templates/CliTemplate/src/store/reducers/index.ts
================================================
export * from './usersData';
export * from './newsData';
================================================
FILE: templates/CliTemplate/src/store/reducers/newsData.ts
================================================
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { NewsResult } from '@src/services';
type NewsData = {
news: NewsResult[];
};
const initialState: NewsData = {
news: [],
};
export const newsDataSlice = createSlice({
initialState,
name: 'newsData',
reducers: {
resetNewsData: () => initialState,
setNews: (state, { payload }: PayloadAction) => {
state.news = payload;
},
},
});
export const {
actions: { resetNewsData, setNews },
name: newsDataName,
reducer: newsData,
} = newsDataSlice;
================================================
FILE: templates/CliTemplate/src/store/reducers/usersData.ts
================================================
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { UserResult } from '@src/services';
type AppData = {
users: UserResult[];
isForceUpdate: boolean;
};
const initialState: AppData = {
isForceUpdate: false,
users: [],
};
export const userDataSlice = createSlice({
initialState,
name: 'userData',
reducers: {
resetUserData: () => initialState,
setForceUpdate: (state, { payload }: PayloadAction) => {
state.isForceUpdate = payload;
},
setUsers: (state, { payload }: PayloadAction) => {
state.users = payload;
},
},
});
export const {
actions: { resetUserData, setForceUpdate, setUsers },
name: userDataName,
reducer: userData,
} = userDataSlice;
================================================
FILE: templates/CliTemplate/src/utils/color.ts
================================================
import { ColorSchemeName } from 'react-native';
export const color = {
dark: {
backgroundColor: '#212121', // light grey
primaryColor: '#0a84ff', // bright blue
secondaryColor: '#dcdcdc', // dark grey
textColor: '#f8f9fa', // off-white
},
light: {
backgroundColor: '#f8f9fa', // grey
primaryColor: '#000080', // blue
secondaryColor: '#6c757d', // off-white
textColor: '#343a40', // dark grey
},
theme1: {
backgroundColor: '#f8f8f8', // light pink
primaryColor: '#ff5a5f', // red
secondaryColor: '#f2c9c9', // off-white
textColor: '#424242', // dark grey
},
theme2: {
backgroundColor: '#e5e5e5', // wheat
primaryColor: '#000080', // navy blue
secondaryColor: '#f5deb3', // light grey
textColor: '#333333', // dark grey
},
theme3: {
backgroundColor: '#f0f0f0', // light yellow
primaryColor: '#800000', // maroon
secondaryColor: '#ffffe0', // light grey
textColor: '#2f4f4f', // dark slate grey
},
theme4: {
backgroundColor: '#f5f5f5', // misty rose
primaryColor: '#663399', // rebecca purple
secondaryColor: '#ffe4e1', // light grey
textColor: '#333333', // dark grey
},
};
export type Palette = (typeof color)[keyof typeof color];
export type Theme = ColorSchemeName | keyof typeof color;
================================================
FILE: templates/CliTemplate/src/utils/dimensions.ts
================================================
import { Dimensions } from 'react-native';
const { height: screenHeight, width: screenWidth } = Dimensions.get('window');
// resolution changes as per design
export const designWidth = 375;
export const designHeight = 812;
const scaleWidth = (val: number) => {
return (screenWidth * val) / designWidth;
};
const scaleHeight = (val: number) => {
return (screenHeight * val) / designHeight;
};
const scale = Math.min(screenWidth / designWidth, screenHeight / designHeight);
const moderateScale = (size: number, factor = 1) =>
size + (scaleWidth(size) - size) * factor;
const scaledSize = (size: number) => Math.ceil(size * scale);
export {
moderateScale,
scaledSize,
scaleHeight,
scaleWidth,
screenHeight,
screenWidth,
};
================================================
FILE: templates/CliTemplate/src/utils/helper.ts
================================================
import { createRef } from 'react';
import NetInfo from '@react-native-community/netinfo';
import { scaledSize } from './dimensions';
import { IndicatorRef } from '../../blueprints/Indicator/Indicator';
export const isNetworkConnected = async () => {
const state = await NetInfo.refresh();
return state.isConnected || false;
};
export function isEmpty(obj: object) {
return Object.keys(obj).length === 0;
}
export const logger = (...args: any) => {
if (__DEV__) {
// eslint-disable-next-line no-console
console.log(...args);
}
};
export const scaled = (value: number) => {
return {
height: scaledSize(value),
width: scaledSize(value),
};
};
export function boxShadow(
color: string,
offset = { height: 2, width: 2 },
radius = 8,
opacity = 0.2
) {
return {
elevation: radius,
shadowColor: color,
shadowOffset: offset,
shadowOpacity: opacity,
shadowRadius: radius,
};
}
export function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve as () => void, ms));
}
export const loader = createRef();
================================================
FILE: templates/CliTemplate/src/utils/index.ts
================================================
export * from './dimensions';
export * from './helper';
export * from './color';
================================================
FILE: templates/CliTemplate/tsconfig.json
================================================
{
"extends": "@react-native/typescript-config/tsconfig.json",
"compilerOptions": {
/* Basic Options */
"target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "esnext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"lib": [
"esnext"
] /* Specify library files to be included in the compilation. */,
"allowJs": true /* Allow javascript files to be compiled. */,
"jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,
"moduleResolution": "bundler" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"paths": {
"@src/*": ["./src/*"],
"@app/blueprints": ["./blueprints"]
} /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */,
"strict": true /* Enable all strict type-checking options. */,
"noUnusedLocals": true /* Report errors on unused locals. */,
"noUnusedParameters": true /* Report errors on unused parameters. */,
"noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
"noImplicitUseStrict": false,
"noStrictGenericChecks": false,
"noUncheckedIndexedAccess": true,
"types": ["react-native", "jest", "node"],
"typeRoots": ["@types", "./node_modules/@types"],
"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"skipLibCheck": true /* Skip type checking of declaration files. */,
"resolveJsonModule": true /* Allows importing modules with a ‘.json’ extension, which is a common practice in node projects. */
/* Module Resolution Options */
// "importsNotUsedAsValues": "error",
// "baseUrl": "..", /* Base directory to resolve non-absolute module names. */,
// "checkJs": true, /* Report errors in .js files. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true /* Do not emit outputs. */,
// "incremental": true, /* Enable incremental compilation */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
/* Strict Type-Checking Options */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Additional Checks */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
},
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}
================================================
FILE: templates/ExpoTemplate/.eslintrc.js
================================================
module.exports = {
extends: [
'@react-native',
'prettier',
'plugin:react-hooks/recommended',
'plugin:react-native/all',
],
overrides: [
{
files: ['*.ts', '*.tsx', '*.js'],
rules: {
'@typescript-eslint/no-shadow': ['error'],
'no-shadow': 'off',
'no-undef': 'off',
'react/no-unstable-nested-components': ['off', { allowAsProps: true }],
},
},
],
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
'eslint-plugin-no-inline-styles',
'import',
'react-hooks',
'sort-keys-fix',
'sort-destructure-keys',
'react-native',
],
root: true,
rules: {
'import/newline-after-import': [
'warn',
{
count: 1,
},
],
'import/no-duplicates': 'error',
'import/order': [
'error',
{
'alphabetize': {
caseInsensitive: true,
order: 'asc',
},
'groups': [
['external', 'builtin'],
'internal',
['sibling', 'parent'],
'index',
],
'newlines-between': 'always',
'pathGroups': [
{
group: 'external',
pattern: '@(react|react-native)',
position: 'before',
},
{
group: 'internal',
pattern: '@miBoilerplate/**',
},
{
group: 'internal',
pattern: '@src/**',
},
],
'pathGroupsExcludedImportTypes': ['internal', 'react'],
},
],
'no-console': ['error'],
'no-inline-styles/no-inline-styles': 2,
'no-restricted-imports': [
'error',
{
importNames: ['Text', 'Image'],
message: 'Please use @app/blueprints for importing main elements.',
name: 'react-native',
},
],
'no-shadow': 'off',
'prettier/prettier': [
'error',
{
arrowParens: 'avoid',
bracketSameLine: true,
bracketSpacing: true,
quoteProps: 'consistent',
singleQuote: true,
tabWidth: 2,
trailingComma: 'es5',
useTabs: false,
},
],
'react-hooks/exhaustive-deps': 'error',
'react-hooks/rules-of-hooks': 'error',
'sort-destructure-keys/sort-destructure-keys': [
2,
{ caseSensitive: false },
],
'sort-imports': [
'error',
{
ignoreCase: true,
ignoreDeclarationSort: true,
ignoreMemberSort: false,
},
],
'sort-keys-fix/sort-keys-fix': [
'error',
'asc',
{
caseSensitive: false,
natural: true,
},
],
},
};
================================================
FILE: templates/ExpoTemplate/.gitignore
================================================
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# dependencies
node_modules/
dist/*
# Expo
.expo/
web-build/
# Native
*.orig.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
# Metro
.metro-health-check*
# debug
npm-debug.*
yarn-debug.*
yarn-error.*
# macOS
.DS_Store
*.pem
# local env files
.env*.local
# typescript
*.tsbuildinfo
.yarn/
================================================
FILE: templates/ExpoTemplate/.husky/commit-msg
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no -- commitlint --edit
================================================
FILE: templates/ExpoTemplate/.husky/pre-commit
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
yarn lint & npx yarn typescript
================================================
FILE: templates/ExpoTemplate/.prettierrc.js
================================================
module.exports = {
arrowParens: "avoid",
bracketSameLine: true,
bracketSpacing: true,
quoteProps: "consistent",
singleQuote: true,
tabWidth: 2,
trailingComma: "es5",
useTabs: false,
};
================================================
FILE: templates/ExpoTemplate/.vscode/settings.json
================================================
{
"eslint.options": {},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.run": "onSave",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"cSpell.words": ["dtos", "Formik", "gradlew", "MMKV", "persistor"],
"conventionalCommits.scopes": ["contents"]
}
================================================
FILE: templates/ExpoTemplate/.yarnrc.yml
================================================
nodeLinker: node-modules
compressionLevel: mixed
enableGlobalCache: false
================================================
FILE: templates/ExpoTemplate/App.tsx
================================================
import React from 'react';
import { useFonts } from 'expo-font';
import { MainApp } from './src/MainApp';
const App = () => {
const [fontsLoaded] = useFonts({
Poppins: require('./src/assets/fonts/Poppins.ttf'),
});
if (!fontsLoaded) {
return null;
}
return ;
};
export default App;
================================================
FILE: templates/ExpoTemplate/app.json
================================================
{
"expo": {
"name": "MIBoilerplate",
"slug": "mindinventory-expo-boilerplate",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"assetBundlePatterns": ["**/*"],
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
}
},
"web": {
"favicon": "./assets/favicon.png"
},
"plugins": ["expo-localization", "expo-font"]
}
}
================================================
FILE: templates/ExpoTemplate/babel.config.js
================================================
module.exports = function (api) {
api.cache(true);
return {
plugins: [
'react-native-reanimated/plugin',
[
'module:react-native-dotenv',
{
envName: 'APP_ENV',
moduleName: '@env',
path: './.env',
safe: true,
allowUndefined: false,
},
],
[
'module-resolver',
{
alias: {
'@app/blueprints': './blueprints',
'@src/assets': './src/assets',
'@src/components': './src/components',
'@src/constants': './src/constants',
'@src/context': './src/context',
'@src/hooks': './src/hooks',
'@src/i18n': './src/i18n',
'@src/screens': './src/screens',
'@src/services': './src/services',
'@src/store': './src/store',
'@src/utils': './src/utils',
},
extensions: ['.js', '.json'],
root: ['./src'],
},
],
],
presets: ['babel-preset-expo'],
};
};
================================================
FILE: templates/ExpoTemplate/blueprints/Button/Button.tsx
================================================
import React from 'react';
import {
StyleProp,
StyleSheet,
TextStyle,
TouchableOpacity,
TouchableOpacityProps,
View,
ViewStyle,
} from 'react-native';
import Animated, {
useAnimatedStyle,
useSharedValue,
withSpring,
} from 'react-native-reanimated';
import { useColor } from '@src/context';
import { moderateScale, Palette, scaleHeight } from '@src/utils';
import { Text } from '../Text/Text';
const AnimatedButtonComponent =
Animated.createAnimatedComponent(TouchableOpacity);
interface ExtraButtonProps {
buttonContainerStyle?: StyleProp;
titleContainerStyle?: StyleProp;
titleStyle?: StyleProp;
title?: React.ReactNode;
rightIcon?: JSX.Element;
leftIcon?: JSX.Element;
}
export type AnimatedButtonProps = Omit<
TouchableOpacityProps,
'onPressIn' | 'onPressOut' | 'style'
> & {
containerStyle?: StyleProp;
};
export type ButtonProps = AnimatedButtonProps & ExtraButtonProps;
export const AnimatedTouchableOpacity = React.memo(
(props: AnimatedButtonProps) => {
const { containerStyle } = props;
const scaleValue = useSharedValue(1);
const animatedButtonStyle = useAnimatedStyle(() => {
return {
transform: [{ scale: scaleValue.value }],
};
});
return (
(scaleValue.value = withSpring(0.9))}
onPressOut={() => (scaleValue.value = withSpring(1))}
activeOpacity={0.8}
{...props}>
{props.children}
);
}
);
export const Button = React.memo((props: ButtonProps) => {
const { buttonContainerStyle, title, titleContainerStyle, titleStyle } =
props;
const { color } = useColor();
const styles = buttonStyles(color);
return (
{props.leftIcon}
{title}
{props.rightIcon}
);
});
const buttonStyles = ({ primaryColor }: Palette) =>
StyleSheet.create({
buttonContainer: {
alignItems: 'center',
backgroundColor: primaryColor,
borderRadius: moderateScale(60),
height: scaleHeight(45),
width: '100%',
},
titleContainer: {
alignItems: 'center',
flexDirection: 'row',
height: '100%',
justifyContent: 'center',
width: '100%',
},
});
================================================
FILE: templates/ExpoTemplate/blueprints/Image/Image.tsx
================================================
import React, { useEffect, useState } from 'react';
import type { LayoutChangeEvent } from 'react-native';
import {
ActivityIndicator,
LayoutRectangle,
StyleProp,
StyleSheet,
View,
ViewStyle,
} from 'react-native';
import {
Image as ExpoImage,
ImageProps as ExpoImageProps,
ImageSource as ExpoImageSource,
ImageStyle,
} from 'expo-image';
import { useColor } from '@src/context';
type ImgPriority = 'low' | 'normal' | 'high' | null;
export interface ImageProps extends Omit {
containerStyle?: StyleProp;
style?: ImageStyle;
priority?: ImgPriority;
uploading?: boolean;
width?: number;
height?: number;
children?: React.ReactNode;
showIndicator?: boolean;
indicatorSize?: number;
source?: string | ExpoImageSource | number;
loaderColor?: string;
}
export const Image = React.memo((props: ImageProps) => {
const {
children,
containerStyle,
indicatorSize = 20,
loaderColor,
priority,
showIndicator = true,
source,
style = { backgroundColor: 'red', flex: 1 },
uploading,
width,
...rest
} = props;
const { color } = useColor();
const [loading, setLoading] = useState(false);
const [layout, setLayout] = useState(null);
useEffect(() => {
if (typeof uploading !== 'undefined' && uploading !== loading) {
setLoading(uploading);
}
}, [loading, uploading]);
const onLayout = (e: LayoutChangeEvent) => {
const { height } = e.nativeEvent.layout;
if (layout && layout.height === height && layout.width === width) {
return;
}
setLayout(e.nativeEvent.layout);
};
const shouldShowIndicator =
showIndicator &&
typeof source === 'string' &&
(source.startsWith('http') || source.startsWith('https'));
let indicator = null;
if (loading && shouldShowIndicator) {
indicator = (
);
}
let imageSource: number | ExpoImageSource | undefined = {
uri: source as string,
};
if (typeof source !== 'string') {
// Local image
imageSource = source;
}
let imageStyle: ImageStyle = style || {};
if (imageStyle.flex === 1 && layout) {
imageStyle = { ...style };
delete imageStyle.flex;
imageStyle = { ...imageStyle, ...layout };
}
return (
{
!loading && setLoading(true);
}}
onError={() => {
loading && setLoading(false);
}}
onLoadEnd={() => {
loading && setLoading(false);
}}
priority={priority || 'normal'}
{...rest}>
{children}
{indicator}
);
});
const styles = StyleSheet.create({
container: {},
indicator: {
...StyleSheet.absoluteFillObject,
alignItems: 'center',
justifyContent: 'center',
},
});
================================================
FILE: templates/ExpoTemplate/blueprints/Indicator/Indicator.tsx
================================================
import React, {
useCallback,
useImperativeHandle,
useRef,
useState,
} from 'react';
import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';
import { useColor } from '@src/context';
import { Palette, scaledSize } from '@src/utils';
import { Text } from '../Text/Text';
export interface IndicatorProps {
isLoading: boolean;
}
export type IndicatorRef = {
hide: () => void;
show: () => void;
};
export const IndicatorViewRef = (
props: IndicatorProps,
ref: React.Ref
) => {
const { isLoading = true } = props;
const { color } = useColor();
const [loading, setIsLoading] = useState(isLoading);
const pressCount = useRef(0);
const show = useCallback(() => setIsLoading(true), []);
const hide = useCallback(() => setIsLoading(false), []);
const handlePressCount = useCallback(() => {
pressCount.current = pressCount.current + 1;
if (pressCount.current === 2) {
setIsLoading(false);
pressCount.current = 0;
}
}, []);
useImperativeHandle(ref, () => {
return {
hide,
show,
};
}, [hide, show]);
const styles = indicatorStyles(color);
if (!loading) return <>>;
return (
Please wait ...
);
};
export const IndicatorView = React.forwardRef(
IndicatorViewRef
);
export const indicatorStyles = ({ backgroundColor }: Palette) => {
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
...StyleSheet.absoluteFillObject,
},
loaderContainer: {
alignItems: 'center',
backgroundColor: backgroundColor,
borderRadius: scaledSize(7),
justifyContent: 'center',
padding: scaledSize(10),
},
loaderStyle: {
padding: scaledSize(7),
},
});
return styles;
};
================================================
FILE: templates/ExpoTemplate/blueprints/Text/Text.tsx
================================================
import React from 'react';
import {
// eslint-disable-next-line no-restricted-imports
Text as RNText,
StyleProp,
TextProps as TextProperties,
TextStyle,
} from 'react-native';
import { useColor } from '@src/context';
import { scaledSize } from '@src/utils';
export enum Fonts {
Poppins = 'Poppins',
}
const BASE_TEXT: TextStyle = {
fontSize: scaledSize(7),
};
export const presets = {
default: BASE_TEXT,
font400: {
...BASE_TEXT,
//add your font normal for weight 400
fontFamily: Fonts.Poppins,
} as TextStyle,
font500: {
...BASE_TEXT,
//add your font medium for weight 500
fontFamily: Fonts.Poppins,
} as TextStyle,
font600: {
...BASE_TEXT,
//add your font semi-bold for weight 600
fontFamily: Fonts.Poppins,
} as TextStyle,
font700: {
...BASE_TEXT,
//add your font bold for weight 700
fontFamily: Fonts.Poppins,
} as TextStyle,
h1: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(24),
fontWeight: '700',
} as TextStyle,
h2: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(21),
fontWeight: '700',
} as TextStyle,
h3: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(18),
fontWeight: '500',
} as TextStyle,
h4: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(15),
fontWeight: '500',
} as TextStyle,
h5: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(12),
fontWeight: '400',
} as TextStyle,
h6: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(9),
fontWeight: '400',
} as TextStyle,
small: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(6),
fontWeight: '300',
} as TextStyle,
title: {
...BASE_TEXT,
fontFamily: Fonts.Poppins,
fontSize: scaledSize(13),
fontWeight: '700',
} as TextStyle,
};
export type TextPresets = keyof typeof presets;
export interface TextProps extends TextProperties {
style?: StyleProp;
preset?: TextPresets;
color?: string;
textAlign?: 'auto' | 'left' | 'right' | 'center' | 'justify';
}
export const Text = ({ children, ...props }: TextProps) => {
const {
color,
preset = 'default',
style: styleOverride,
textAlign = 'auto',
...rest
} = props;
const { color: palette } = useColor();
return (
{children}
);
};
================================================
FILE: templates/ExpoTemplate/blueprints/TextInput/Input.tsx
================================================
import React, { useCallback } from 'react';
import {
NativeSyntheticEvent,
Platform,
TextInput as RNTextInput,
StyleSheet,
TargetedEvent,
TextInputFocusEventData,
TextInputProps,
View,
} from 'react-native';
import Animated, {
Easing,
interpolate,
interpolateColor,
useAnimatedProps,
useAnimatedStyle,
useDerivedValue,
useSharedValue,
withTiming,
} from 'react-native-reanimated';
import { useColor } from '@src/context';
import { Palette } from '@src/utils';
import { InputProps } from './TextInputProps';
import { Text } from '../Text/Text';
const AnimatedTextInput = Animated.createAnimatedComponent(RNTextInput);
export const Input = React.memo(
React.forwardRef((props: InputProps, ref?: React.Ref) => {
const {
backgroundColor = 'white',
borderColor = 'black',
error,
errorContainerStyle,
errorStyle,
inputContainerStyle,
inputStyle,
label,
labelColor = 'black',
leftIcon,
leftIconContainerStyle,
onBlur,
onFocus,
onFocusBackgroundColor = '#e9e9e9',
onFocusBorderColor = '#0c5fed',
onFocusLabelColor = '#0c5fed',
onHoverBackgroundColor = '#e9e9e9',
onMouseEnter,
onMouseLeave,
outlineGapColor = 'white',
placeholder,
rightIcon,
rightIconContainerStyle,
style,
variant = 'filled',
...rest
} = props;
const { color } = useColor();
const styles = inputStyles(color);
const hovered = useSharedValue(false);
const focused = useSharedValue(false);
const handleMouseEnter = useCallback(
(event: NativeSyntheticEvent) => {
onMouseEnter?.(event);
hovered.value = true;
},
[hovered, onMouseEnter]
);
const handleMouseLeave = useCallback(
(event: NativeSyntheticEvent) => {
onMouseLeave?.(event);
hovered.value = false;
},
[hovered, onMouseLeave]
);
const handleFocus = useCallback(
(event: NativeSyntheticEvent) => {
onFocus?.(event);
focused.value = true;
},
[focused, onFocus]
);
const handleBlur = useCallback(
(event: NativeSyntheticEvent) => {
onBlur?.(event);
focused.value = false;
},
[focused, onBlur]
);
const focusAnimation = useSharedValue(0);
useDerivedValue(() => {
focusAnimation.value = withTiming(focused.value ? 1 : 0, {
duration: 200,
easing: Easing.out(Easing.ease),
});
}, [focused.value, focusAnimation.value]);
const active = useDerivedValue(
() => focused.value || (rest.value?.length || 0) > 0,
[focused.value, rest.value]
);
const activeAnimation = useSharedValue(0);
useDerivedValue(() => {
activeAnimation.value = withTiming(active.value ? 1 : 0, {
duration: 200,
easing: Easing.out(Easing.ease),
});
}, [active.value, activeAnimation.value]);
const animatedInputContainerStyle = useAnimatedStyle(() => {
return {
backgroundColor:
variant === 'filled'
? focused.value
? onFocusBackgroundColor
: hovered.value
? onHoverBackgroundColor
: backgroundColor
: variant === 'outlined'
? backgroundColor
: backgroundColor,
borderBottomEndRadius: variant !== 'standard' ? 4 : 0,
borderBottomStartRadius: variant !== 'standard' ? 4 : 0,
borderTopEndRadius: 4,
borderTopStartRadius: 4,
};
}, [focused.value, hovered.value, variant]);
const animatedInput = useAnimatedStyle(() => {
return {
fontSize: 16,
minHeight: variant === 'standard' ? 48 : 56,
paddingEnd: rightIcon ? 12 : variant === 'standard' ? 0 : 16,
paddingStart: leftIcon ? 12 : variant === 'standard' ? 0 : 16,
paddingTop: variant === 'filled' && label ? 18 : 0,
};
}, [variant, leftIcon, rightIcon]);
const animatedLeading = useAnimatedStyle(() => {
return {
marginStart: variant === 'standard' ? 0 : 12,
marginVertical: variant === 'standard' ? 12 : 16,
};
}, [variant]);
const animatedTrailing = useAnimatedStyle(() => {
return {
marginEnd: variant === 'standard' ? 0 : 12,
marginVertical: variant === 'standard' ? 12 : 16,
};
}, [variant]);
const animatedOutline = useAnimatedStyle(() => {
return {
borderBottomEndRadius: 4,
borderBottomStartRadius: 4,
borderColor: focused.value
? onFocusBorderColor
: hovered.value
? onFocusBorderColor
: borderColor,
borderTopEndRadius: 4,
borderTopStartRadius: 4,
borderWidth: focused.value ? 2 : 1,
};
}, [focused.value, hovered.value]);
const animatedOutlineLabelGap = useAnimatedStyle(() => {
return {
height: focused.value ? 2 : 1,
};
}, [focused.value]);
const animatedLabelContainer = useAnimatedStyle(() => {
return {
height: variant === 'standard' ? 48 : 56,
start:
variant === 'standard' ? (leftIcon ? 36 : 0) : leftIcon ? 48 : 16,
};
}, [variant, leftIcon]);
const animatedLabel = useAnimatedStyle(() => {
return {
color: interpolateColor(
focusAnimation.value,
[0, 1],
[labelColor, onFocusLabelColor]
),
fontSize: interpolate(activeAnimation.value, [0, 1], [16, 12]),
transform: [
{
translateY: interpolate(
activeAnimation.value,
[0, 1],
[
0,
variant === 'filled' ? -12 : variant === 'outlined' ? -28 : -24,
]
),
},
],
};
}, [focusAnimation, activeAnimation]);
const animatedPlaceholder = useAnimatedProps(() => {
return {
placeholder: label ? (focused.value ? placeholder : '') : placeholder,
};
}, [label, focused, placeholder]);
const animatedUnderline = useAnimatedStyle(() => {
return {
backgroundColor: interpolateColor(
focusAnimation.value,
[0, 1],
[borderColor, onFocusBorderColor]
),
transform: [{ scaleX: focusAnimation.value }],
};
}, [focusAnimation.value]);
const animatedOutlineLabel = useAnimatedStyle(() => {
return {
backgroundColor: interpolateColor(
activeAnimation.value,
[0, 1],
[backgroundColor, outlineGapColor]
),
transform: [{ scaleX: activeAnimation.value }],
};
}, [activeAnimation.value]);
return (
{leftIcon && (
{leftIcon}
)}
{rightIcon && (
{rightIcon}
)}
{(variant === 'filled' || variant === 'standard') && (
<>
>
)}
{variant === 'outlined' && (
)}
{label ? (
{variant === 'outlined' && (
)}
{label}
) : null}
{error ? (
{error}
) : null}
);
})
);
const inputStyles = ({ backgroundColor }: Palette) =>
StyleSheet.create({
errorView: {
marginHorizontal: 16,
marginTop: 4,
},
helperText: {
fontSize: 14,
},
input: {
flex: 1,
...Platform.select({
web: {
outlineStyle: 'none',
},
}),
},
inputContainer: {
flexDirection: 'row',
},
labelContainer: {
justifyContent: 'center',
position: 'absolute',
top: 0,
},
leading: {
alignItems: 'center',
height: 24,
justifyContent: 'center',
width: 24,
},
outline: {},
outlineLabelGap: {
backgroundColor: backgroundColor,
end: -4,
position: 'absolute',
start: -4,
top: 0,
},
trailing: {
alignItems: 'center',
height: 24,
justifyContent: 'center',
width: 24,
},
underline: {
bottom: 0,
end: 0,
height: 1,
position: 'absolute',
start: 0,
},
underlineFocused: {
bottom: 0,
end: 0,
height: 2,
position: 'absolute',
start: 0,
},
});
================================================
FILE: templates/ExpoTemplate/blueprints/TextInput/TextInput.tsx
================================================
import React from 'react';
import { TextInput as RNTextInput } from 'react-native';
import { Field, FieldProps } from 'formik';
import { Input } from './Input';
import { TextInputProps } from './TextInputProps';
export const TextInput = React.memo(
React.forwardRef(
({ ...props }: TextInputProps, ref?: React.Ref) => {
const { name } = props;
return (
{({ form, meta }: FieldProps) => {
return (
) => {
form?.handleChange(name)(text);
}}
onBlur={form?.handleBlur(name)}
value={meta?.value}
error={meta?.error && meta?.touched ? meta?.error ?? '' : ''}
ref={ref}
{...props}
/>
);
}}
);
}
)
);
================================================
FILE: templates/ExpoTemplate/blueprints/TextInput/TextInputProps.ts
================================================
import {
NativeSyntheticEvent,
TextInputProps as RNTextInputProps,
StyleProp,
TargetedEvent,
TextStyle,
ViewStyle,
} from 'react-native';
export interface TextInputProps extends InputProps {
name: string;
}
export type Variant = 'filled' | 'outlined' | 'standard';
export interface InputProps extends RNTextInputProps {
/**
* The variant of the TextInput style.
* @default "filled"
*/
variant?: Variant;
/**
* The label to display.
*/
label?: string;
/**
* The element placed before the text input.
*/
leftIcon?: React.ReactNode | null;
/**
* The element placed after the text input.
*/
rightIcon?: React.ReactNode | null;
/**
* The helper text to display.
*/
error?: string;
/**
* Callback function to call when user moves pointer over the input.
*/
onMouseEnter?: (event: NativeSyntheticEvent) => void;
/**
* Callback function to call when user moves pointer away from the input.
*/
onMouseLeave?: (event: NativeSyntheticEvent) => void;
/**
* The style of the container view.
*/
style?: StyleProp;
/**
* The style of the text input container view.
*/
inputContainerStyle?: StyleProp;
/**
* The style of the text input.
*/
inputStyle?: RNTextInputProps['style'];
/**
* The style of the text input's leading element container.
*/
leftIconContainerStyle?: StyleProp;
/**
* The style of the text input's trailing element container.
*/
rightIconContainerStyle?: StyleProp;
/**
* Background color of the input container style.
* @default "white"
*/
backgroundColor?: string;
/**
* On focus background color of the input container style.
* @default "#e9e9e9"
*/
onFocusBackgroundColor?: string;
/**
* Border color of the outline input container style.
* @default "black"
*/
borderColor?: string;
/**
* On focus Border color of the outline input container style.
* @default "#0c5fed"
*/
onFocusBorderColor?: string;
/**
* On hover background color of the filled input container style.
* @default "#e9e9e9"
*/
onHoverBackgroundColor?: string;
/**
* Label text color of the input.
* @default "black"
*/
labelColor?: string;
/**
* On focus Label text color change.
* @default "#0c5fed"
*/
onFocusLabelColor?: string;
/**
* On error or any helper text below text Input container style.
*/
errorContainerStyle?: StyleProp;
/**
* On error or any helper text below text Input Text-Style.
*/
errorStyle?: StyleProp;
/**
* In outlined variant the gap border color.
* @default white
*/
outlineGapColor?: string;
}
================================================
FILE: templates/ExpoTemplate/blueprints/TextInput/index.tsx
================================================
import { Input } from './Input';
import { TextInput } from './TextInput';
import { InputProps, TextInputProps } from './TextInputProps';
export { TextInput, Input };
export type { TextInputProps, InputProps };
================================================
FILE: templates/ExpoTemplate/blueprints/index.ts
================================================
export * from './Text/Text';
export * from './Image/Image';
export * from './Indicator/Indicator';
export * from './Button/Button';
export * from './TextInput';
================================================
FILE: templates/ExpoTemplate/commitlint.config.js
================================================
module.exports = {
extends: ['@commitlint/config-conventional'],
};
================================================
FILE: templates/ExpoTemplate/env.d.ts
================================================
declare module '@env' {
export const API_URL: string;
export const ENV: string;
}
================================================
FILE: templates/ExpoTemplate/jest.config.js
================================================
module.exports = {
preset: 'react-native',
};
================================================
FILE: templates/ExpoTemplate/metro.config.js
================================================
const { getDefaultConfig } = require('expo/metro-config');
module.exports = (() => {
const config = getDefaultConfig(__dirname);
const { resolver, transformer } = config;
config.transformer = {
...transformer,
babelTransformerPath: require.resolve('react-native-svg-transformer'),
};
config.resolver = {
...resolver,
assetExts: resolver.assetExts.filter(ext => ext !== 'svg'),
sourceExts: [...resolver.sourceExts, 'svg'],
};
return config;
})();
================================================
FILE: templates/ExpoTemplate/package.json
================================================
{
"name": "mindinventory-expo-boilerplate",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "NODE_ENV=default APP_ENV=default npx expo start --reset-cache",
"start:development": "NODE_ENV=development APP_ENV=development npx expo start --reset-cache",
"start:staging": "NODE_ENV=staging APP_ENV=staging npx expo start --reset-cache",
"start:production": "NODE_ENV=production APP_ENV=production npx expo start --reset-cache",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"typescript": "tsc --noEmit",
"prepare": "husky install",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"fix:lint": "yarn lint --fix && yarn typescript",
"icons": "cd scripts && node icons.js",
"images": "cd scripts && node images.js",
"screens": "cd scripts && node generateScreenFile.js",
"svgs": "cd scripts && node svgIcons.js"
},
"dependencies": {
"@react-native-async-storage/async-storage": "1.23.1",
"@react-native-community/netinfo": "11.3.1",
"@react-navigation/native": "^6.1.18",
"@react-navigation/native-stack": "^6.11.0",
"@reduxjs/toolkit": "^2.2.7",
"axios": "^1.7.7",
"expo": "^51.0.28",
"expo-font": "~12.0.9",
"expo-image": "~1.13.0",
"expo-localization": "~15.0.3",
"expo-status-bar": "~1.12.1",
"formik": "^2.4.6",
"i18n-js": "^4.4.3",
"react": "18.2.0",
"react-native": "0.74.5",
"react-native-gesture-handler": "~2.16.1",
"react-native-network-logger": "^1.17.0",
"react-native-reanimated": "~3.10.1",
"react-native-safe-area-context": "4.10.5",
"react-native-screens": "3.31.1",
"react-native-svg": "15.2.0",
"react-redux": "^9.1.2",
"redux": "^5.0.1",
"redux-persist": "^6.0.0",
"redux-thunk": "^3.1.0",
"yup": "^1.4.0"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@babel/preset-env": "^7.25.4",
"@babel/runtime": "^7.25.6",
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0",
"@react-native/eslint-config": "^0.75.3",
"@react-native/metro-config": "^0.75.3",
"@react-native/typescript-config": "^0.75.3",
"@types/i18n-js": "^3.8.9",
"@types/jest": "^29.5.13",
"@types/react": "~18.2.79",
"@types/react-test-renderer": "^18.3.0",
"@typescript-eslint/parser": "^8.7.0",
"babel-jest": "^29.7.0",
"babel-plugin-module-resolver": "^5.0.2",
"eslint": "^9.11.1",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.30.0",
"eslint-plugin-import-order-autofix": "^0.8.3",
"eslint-plugin-no-inline-styles": "^1.0.5",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-native": "^4.1.0",
"eslint-plugin-sort-destructure-keys": "^2.0.0",
"eslint-plugin-sort-keys-fix": "^1.1.2",
"husky": "^9.1.6",
"jest": "^29.7.0",
"prettier": "^3.3.3",
"react-native-dotenv": "^3.4.11",
"react-native-svg-transformer": "^1.5.0",
"react-test-renderer": "^18.3.1",
"typescript": "~5.3.3"
},
"resolutions": {
"@types/react": "^18.0.24"
},
"eslintIgnore": [
"node_modules/",
"lib/"
]
}
================================================
FILE: templates/ExpoTemplate/scripts/generateScreenFile.js
================================================
/* eslint-disable no-console */
const fs = require('fs');
const path = require('path');
// get folder name from terminal argument
const folderName = process.argv[2];
if (!folderName) {
console.error('Please provide a folder name');
process.exit(1);
}
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// create the folder
fs.mkdir(`../src/screens/${capitalizeFirstLetter(folderName)}`, err => {
if (err) throw err;
console.log(`Folder ${folderName} created successfully`);
const fileName = capitalizeFirstLetter(folderName);
const useHookFileName = capitalizeFirstLetter(fileName);
// create hook js hookFile.ts
const hookFile = `import { useAppContext } from '@src/context';
import { ${folderName}Styles } from './${fileName}.style';
const use${useHookFileName} = () => {
const { color, navigation } = useAppContext();
// add your code here
return {
navigation,
styles: ${folderName}Styles(color),
};
};
export default use${useHookFileName};
`;
fs.writeFileSync(
path.join(`../src/screens/${fileName}`, `use${useHookFileName}.ts`),
hookFile,
errHook => {
if (errHook) throw errHook;
console.log(`use${fileName}.ts file created successfully`);
}
);
// create styleFile.ts
const styleFile = `import { StyleSheet } from 'react-native';
import { Palette } from '@src/utils';
export const ${folderName}Styles = ({}: Palette) =>
StyleSheet.create({
container: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
});
`;
fs.writeFileSync(
path.join(`../src/screens/${fileName}`, `${fileName}.style.ts`),
styleFile,
errStyles => {
if (errStyles) throw errStyles;
console.log(`${fileName}.style.ts file created successfully`);
}
);
// create defaultScreen.tsx
const defaultScreen = `import React from 'react';
import { View } from 'react-native';
import { Text } from '@app/blueprints';
import use${useHookFileName} from './use${useHookFileName}';
const ${useHookFileName}Screen = () => {
const { styles } = use${useHookFileName}();
return (
${useHookFileName} Screen
);
};
export default React.memo(${useHookFileName}Screen);
`;
fs.writeFileSync(
path.join(`../src/screens/${fileName}`, `${fileName}Screen.tsx`),
defaultScreen,
errScreen => {
if (errScreen) throw errScreen;
console.log(`${fileName}Screen.tsx file created successfully`);
}
);
const exportToIndex = `export { default as ${useHookFileName}Screen } from './${fileName}/${fileName}Screen';\n`;
fs.appendFile(`../src/screens/index.ts`, exportToIndex, errScreen => {
if (errScreen) throw errScreen;
console.log(`${useHookFileName} file created successfully`);
});
});
================================================
FILE: templates/ExpoTemplate/scripts/icons.js
================================================
const fs = require('fs');
const path = require('path');
const iconFileNames = () => {
const array = fs
.readdirSync('../src/assets/icons')
.filter(file => {
return ['gif', 'jpeg', 'jpg', 'png', 'webp'].includes(file.split('.')[1]);
})
.map(file => {
const ext = path.parse(file).ext;
return file.split('@').length > 1 &&
['1x', '2x', '3x'].includes(file.split('@')[1].split('.')[0])
? file.replace(`@2x${ext}`, `${ext}`).replace(`@3x${ext}`, `${ext}`)
: file;
});
return Array.from(new Set(array));
};
const generate = () => {
let properties = iconFileNames()
.map(name => {
const iconName = path.parse(name).name.toUpperCase();
return `${iconName}_ICONS = require('./${name}'),`;
})
.join('\n ');
const string = `export enum Icons {
${properties}
}
`;
fs.writeFileSync('../src/assets/icons/index.ts', string, 'utf8');
};
generate();
================================================
FILE: templates/ExpoTemplate/scripts/images.js
================================================
const fs = require('fs');
const path = require('path');
const imageFileNames = () => {
const array = fs
.readdirSync('../src/assets/images')
.filter(file => {
return ['gif', 'jpeg', 'jpg', 'png', 'webp'].includes(file.split('.')[1]);
})
.map(file => {
const ext = path.parse(file).ext;
return file.split('@').length > 1 &&
['1x', '2x', '3x'].includes(file.split('@')[1].split('.')[0])
? file.replace(`@2x${ext}`, `${ext}`).replace(`@3x${ext}`, `${ext}`)
: file;
});
return Array.from(new Set(array));
};
const generate = () => {
let properties = imageFileNames()
.map(name => {
const imageName = path.parse(name).name.toUpperCase().replace(/\s/g, '_');
return `${imageName}_IMAGE = require('./${name}'),`;
})
.join('\n ');
const string = `export enum Images {
${properties}
}
`;
fs.writeFileSync('../src/assets/images/index.ts', string, 'utf8');
};
generate();
================================================
FILE: templates/ExpoTemplate/scripts/refresh.sh
================================================
echo "START_CLEAR"
rm -rf node_modules
echo "node_modules removed"
rm -rf Gemfile.lock
echo "Gemfile.lock removed"
rm -rf vendor
echo "Bundle file removed"
rm -rf yarn.lock
echo "yarn.lock removed"
rm -rf android/build
echo "android/build removed"
rm -rf android/app/build
echo "android/app/build removed"
rm -rf ios/Pods/
echo "ios/Pods/ removed"
rm -rf ios/Podfile.lock
echo "ios/Podfile.lock removed"
rm -rf android/.idea/
echo "android/.idea/ removed"
echo "CLEAR_DONE - START_YARN"
yarn
echo "YARN_DONE - Start Bundle iOS"
bundle
echo "bundle done - Start_pod install"
npx pod-install --ios
echo "Finished"
================================================
FILE: templates/ExpoTemplate/scripts/svgIcons.js
================================================
const fs = require('fs');
const path = require('path');
const iconFileNames = () => {
const array = fs
.readdirSync('../src/assets/svgIcons')
.filter(file => {
return file.endsWith('.svg');
})
.map(file => {
return file.replace('@2x.svg', '').replace('@3x.svg', '');
});
return Array.from(new Set(array));
};
const generate = () => {
let properties = iconFileNames()
.map(name => {
const iconName = path.parse(name).name.toUpperCase();
return `import ${iconName}_ICON from './${name}';`;
})
.join('\n');
let exportFiles = iconFileNames()
.map((name, index) => {
const iconName = path.parse(name).name.toUpperCase();
return `${iconName} = ${index + 1},`;
})
.join('\n ');
let mapper = iconFileNames()
.map((name, index) => {
const iconName = path.parse(name).name.toUpperCase();
return `${index + 1}: ${iconName}_ICON,`;
})
.join('\n ');
const string = `${properties}\n\nexport enum SVGIcons {\n ${exportFiles}
}\n\nexport const SVGIconsMapper = {\n ${mapper}
};\n`;
fs.writeFileSync('../src/assets/svgIcons/index.ts', string, 'utf8');
};
generate();
================================================
FILE: templates/ExpoTemplate/src/MainApp.tsx
================================================
import React from 'react';
import { IndicatorView } from '@app/blueprints';
import { NavigationContainer } from '@react-navigation/native';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { LocalizationProvider, ThemeProvider } from './context';
import { AppNavigation, navigationRef } from './navigation/AppNavigation';
import store, { persistor } from './store';
import { loader } from './utils';
export const MainApp = () => {
return (
{/**
* PersistGate delays the rendering of the app's UI until the persisted state has been retrieved
* and saved to redux.
* The `loading` prop can be `null` or any react instance to show during loading (e.g. a splash screen),
* for example `loading={}`.
* @see https://github.com/rt2zz/redux-persist/blob/master/docs/PersistGate.md
*/}
);
};
================================================
FILE: templates/ExpoTemplate/src/assets/icons/index.ts
================================================
export enum Icons {
DEBUG_ICONS = require('./debug.png'),
}
================================================
FILE: templates/ExpoTemplate/src/assets/images/index.ts
================================================
export enum Images {
PLACEHOLDER_IMAGE = require('./placeholder.webp'),
}
================================================
FILE: templates/ExpoTemplate/src/assets/index.ts
================================================
export * from './images';
export * from './icons';
export * from './svgIcons';
================================================
FILE: templates/ExpoTemplate/src/assets/svgIcons/index.ts
================================================
import SETTING_ICON from './setting.svg';
export enum SVGIcons {
SETTING = 1,
}
export const SVGIconsMapper = {
1: SETTING_ICON,
};
================================================
FILE: templates/ExpoTemplate/src/components/AppIcon/AppIcon.tsx
================================================
import React from 'react';
// eslint-disable-next-line no-restricted-imports
import { Image, ImageProps } from 'react-native';
import { SvgProps } from 'react-native-svg';
import { Icons, SVGIcons, SVGIconsMapper } from '@src/assets';
import { scaled } from '@src/utils';
export type IconProps = Omit & {
icon: Icons;
};
export const Icon = (props: IconProps) => {
const { icon } = props;
return ;
};
/**
* SVG ICON
*/
export type SVGIconProps = SvgProps & {
icon: SVGIcons;
height?: number | string;
width?: number | string;
pathFill?: string;
};
export const SvgIcon = (props: SVGIconProps) => {
const { icon, pathFill = '#FFF' } = props;
const IconsImage = SVGIconsMapper[icon];
return ;
};
================================================
FILE: templates/ExpoTemplate/src/components/AppImage/AppImage.tsx
================================================
import React from 'react';
import { Image, ImageProps } from '@app/blueprints';
import { Images } from '@src/assets';
export type ImageSource = Images | string;
export interface AppImageProps extends Omit {
source: ImageSource;
}
export const AppImage = (props: AppImageProps) => {
return (
);
};
================================================
FILE: templates/ExpoTemplate/src/components/BaseLayout/BaseLayout.tsx
================================================
import React from 'react';
import {
SafeAreaView,
StatusBar,
StyleProp,
StyleSheet,
ViewStyle,
} from 'react-native';
import { useColor } from '@src/context';
import { Palette } from '@src/utils';
export type BaseLayoutProps = React.PropsWithChildren & {
style?: StyleProp;
};
export const BaseLayout = React.memo(({ children, style }: BaseLayoutProps) => {
const { appTheme, color } = useColor();
const styles = baseLayoutStyles(color);
return (
{children}
);
});
export const baseLayoutStyles = ({ backgroundColor }: Palette) =>
StyleSheet.create({
safeAreaStyle: {
backgroundColor: backgroundColor,
flex: 1,
},
});
================================================
FILE: templates/ExpoTemplate/src/components/index.ts
================================================
export * from './BaseLayout/BaseLayout';
export * from './AppImage/AppImage';
export * from './AppIcon/AppIcon';
================================================
FILE: templates/ExpoTemplate/src/constants/config.ts
================================================
import { API_URL, ENV } from '@env';
export const AppConfig = {
API_URL,
ENV,
};
================================================
FILE: templates/ExpoTemplate/src/constants/index.ts
================================================
export * from './config';
export * from './platform';
export * from './storageKeys';
================================================
FILE: templates/ExpoTemplate/src/constants/platform.ts
================================================
import { Platform } from 'react-native';
const isAndroid = Platform.OS === 'android';
const isIOS = Platform.OS === 'ios';
export { isAndroid, isIOS, Platform };
================================================
FILE: templates/ExpoTemplate/src/constants/storageKeys.ts
================================================
export enum StorageKeys {
APP_THEME = 'APP_THEME',
APP_LANGUAGE = 'APP_LANGUAGE',
FIRST_LAUNCH = 'FIRST_LAUNCH',
PROFILE_DATA = 'PROFILE_DATA',
}
export type STORAGES_KEY = StorageKeys;
================================================
FILE: templates/ExpoTemplate/src/context/LocalizationContext.tsx
================================================
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { StorageKeys } from '@src/constants';
import i18n, { ContentLanguage } from '@src/i18n';
import { storage } from './storage';
export type LocalizationAppContextType = {
/**
* This variable is of type ContentLanguage and is used to store the language of content.
* language = "English";
*/
language: ContentLanguage;
/**
* For setLanguage change content lang
* @example i18n.locale = ContentLanguage.France
* @return void change app content language.
*/
setLanguageInApp: (lang: ContentLanguage) => void;
};
export const LocalizationAppContext = createContext<
LocalizationAppContextType | undefined
>(undefined);
export const useLanguage = () => {
const context = useContext(LocalizationAppContext);
if (!context)
throw Error('useLanguage must be used inside LocalizationAppContext');
return context;
};
export const LocalizationProvider = ({ children }: React.PropsWithChildren) => {
const [language, setLanguage] = useState(
ContentLanguage.English
);
/**
* For setLanguage change content lang
* i18n.locale = ContentLanguage.France
* @return void change app content language.
*/
const setLanguageInApp = useCallback(async (lang: ContentLanguage) => {
await storage.setData(StorageKeys.APP_LANGUAGE, lang);
i18n.locale = lang;
setLanguage(lang);
}, []);
const value: LocalizationAppContextType = useMemo(() => {
return {
language,
setLanguageInApp,
};
}, [language, setLanguageInApp]);
useEffect(() => {
const init = async () => {
const appLanguage = await storage.getData(StorageKeys.APP_LANGUAGE);
if (appLanguage) {
await setLanguageInApp(appLanguage);
}
};
init();
}, [setLanguageInApp]);
return (
{children}
);
};
================================================
FILE: templates/ExpoTemplate/src/context/ThemeContext.tsx
================================================
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { useColorScheme } from 'react-native';
import { StorageKeys } from '@src/constants';
import { color, Palette, Theme } from '@src/utils';
import { storage } from './storage';
export interface AppThemeContextType {
/**
* The appTheme variable is used to define the color scheme used for the application. It takes a ColorSchemeName as its value.
*/
appTheme: Theme;
/**
* This function is used to set the theme of the application. It takes a single argument, _theme, which should be of type ColorSchemeName.
* @example setAppTheme('dark');
* @param theme ColorSchemeName
* @returns void
*/
setAppTheme: (theme: Theme) => void;
/**
* Get app palette colors.
*/
color: Palette;
}
export const AppThemeContext = createContext(
undefined
);
export const useColor = () => {
const context = useContext(AppThemeContext);
if (!context) throw Error('useColor must be used inside AppThemeContext');
return context;
};
export const ThemeProvider = ({ children }: React.PropsWithChildren) => {
const colorScheme = useColorScheme();
const [appTheme, setTheme] = useState(colorScheme);
/**
* For setAppTheme change app theming.
* setTheme(ColorSchemeName)
* @return void change app Theme.
*/
const setAppTheme = useCallback((theme: Theme) => {
storage.setData(StorageKeys.APP_THEME, theme);
setTheme(theme);
}, []);
const value: AppThemeContextType = useMemo(() => {
return {
appTheme,
color: color[appTheme || 'light'],
setAppTheme,
};
}, [appTheme, setAppTheme]);
useEffect(() => {
const init = async () => {
const theme = await storage.getData(StorageKeys.APP_THEME);
if (theme) {
setTheme(theme);
} else {
setTheme(colorScheme);
}
};
init();
}, [colorScheme, setAppTheme]);
return (
{children}
);
};
================================================
FILE: templates/ExpoTemplate/src/context/content.ts
================================================
import { TranslateOptions } from 'i18n-js';
import i18n, { TxKeyPath } from '../i18n';
/**
* Translates text.
*
* @param key The i18n key.
* @param options The i18n options.
* @returns The translated text.
*
* @example
* Translations:
*
* ```en.json
* {
* "hello": "Hello, {{name}}!"
* }
* ```
*
* Usage:
* ```ts
* import { contents } from '@src/context';
*
* contents("common.hello", { name: "world" })
* => "Hello world!"
* ```
*/
export const contents = (key: TxKeyPath, options?: TranslateOptions) => {
return i18n.t(key, options);
};
================================================
FILE: templates/ExpoTemplate/src/context/context.ts
================================================
import { loader } from '@src/utils';
import { useLanguage } from './LocalizationContext';
import { storage } from './storage';
import { useColor } from './ThemeContext';
import { AppNavigationProp } from '../navigation/appNavigation.type';
import {
useWithNavigation,
WithNavigation,
} from '../navigation/withNavigation';
import { appServices } from '../services/appServices';
export const useAppContextOnly = () => {
const color = useColor();
const { ...language } = useLanguage();
return {
loader: loader,
services: appServices,
storage,
...color,
...language,
};
};
export type AppContextType = ReturnType;
export const useAppContext = (): WithNavigation<
AppNavigationProp,
AppContextType
> => {
return useWithNavigation(
useAppContextOnly()
);
};
================================================
FILE: templates/ExpoTemplate/src/context/index.ts
================================================
export * from './context';
export * from './storage';
export * from './content';
export * from './ThemeContext';
export * from './LocalizationContext';
================================================
FILE: templates/ExpoTemplate/src/context/storage.ts
================================================
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Storage as ReduxStorage } from 'redux-persist';
import type { STORAGES_KEY } from '@src/constants';
import { logger } from '@src/utils';
export type dataStoreType = 'string' | 'boolean' | 'number' | 'object';
export const getData = async (key: STORAGES_KEY, _type?: dataStoreType) => {
try {
const data = await AsyncStorage.getItem(key);
if (data) {
const parseData = JSON.parse(data);
return parseData;
}
} catch (error) {
logger('storage getData', error);
}
};
export const setData = async (key: STORAGES_KEY, value: any) => {
try {
const jsonValue = JSON.stringify(value);
await AsyncStorage.setItem(key, jsonValue);
} catch (error) {
logger('storage setData', error);
}
};
export const getStorageKey = async () => {
const keys = await AsyncStorage.getAllKeys();
return keys;
};
export const deleteStorage = async (key: STORAGES_KEY) => {
return await AsyncStorage.removeItem(key);
};
export const storage = {
deleteStorage,
getData,
getStorageKey,
setData,
};
export const reduxStorage: ReduxStorage = {
getItem: async key => {
const value = await AsyncStorage.getItem(key);
return Promise.resolve(value);
},
removeItem: async key => {
await AsyncStorage.removeItem(key);
return Promise.resolve();
},
setItem: async (key, value) => {
await AsyncStorage.setItem(key, value);
return Promise.resolve(true);
},
};
export type Storage = typeof storage;
================================================
FILE: templates/ExpoTemplate/src/hooks/index.ts
================================================
export * from './useDebounce';
export * from './useIsFirstRender';
export * from './useIsMounted';
export * from './useTimer';
================================================
FILE: templates/ExpoTemplate/src/hooks/useBackHandler.ts
================================================
import { useEffect } from 'react';
import { BackHandler } from 'react-native';
export const useBackHandler = () => {
useEffect(() => {
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
() => {
BackHandler.exitApp();
return true;
}
);
return () => backHandler.remove();
}, []);
};
================================================
FILE: templates/ExpoTemplate/src/hooks/useDebounce.ts
================================================
import { useEffect, useState } from 'react';
export function useDebounce(value: T, delay?: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay || 500);
return () => {
clearTimeout(timer);
};
}, [value, delay]);
return debouncedValue;
}
================================================
FILE: templates/ExpoTemplate/src/hooks/useIsFirstRender.ts
================================================
import { useRef } from 'react';
export const useIsFirstRender = (): boolean => {
const isFirst = useRef(true);
if (isFirst.current) {
isFirst.current = false;
return true;
}
return isFirst.current;
};
================================================
FILE: templates/ExpoTemplate/src/hooks/useIsMounted.ts
================================================
import * as React from 'react';
export const useIsMounted = () => {
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
};
================================================
FILE: templates/ExpoTemplate/src/hooks/useTimer.ts
================================================
import { useEffect, useRef } from 'react';
type ClearTimerFn = (id: number | undefined) => void;
type RunTimerFn = (handler: () => void, timeout: number) => number;
const creteUseTimer =
(clear: ClearTimerFn, runTimer: RunTimerFn) =>
(callback: () => void, delay: number): void => {
const timerRef = useRef();
useEffect(() => {
const stop = () => clear(timerRef.current);
stop();
timerRef.current = runTimer(callback, delay);
return stop;
}, [callback, delay]);
};
export const useInterval = creteUseTimer(
clearInterval as ClearTimerFn,
setInterval
);
export const useTimeout = creteUseTimer(
clearTimeout as ClearTimerFn,
setTimeout
);
================================================
FILE: templates/ExpoTemplate/src/i18n/index.ts
================================================
import { getLocales } from 'expo-localization';
import { I18n } from 'i18n-js';
import en from './locales/en.json';
import hi from './locales/hi.json';
const locales = getLocales();
const i18n = new I18n();
if (Array.isArray(locales)) {
i18n.locale = locales[0]?.languageTag ? locales[0].languageTag : 'en';
}
export const locale = locales[0]?.languageCode;
i18n.enableFallback = true;
i18n.defaultLocale = 'en';
i18n.translations = {
en,
hi,
};
export default i18n;
export enum ContentLanguage {
English = 'en',
Hindi = 'hi',
}
export type TxKeyPath = RecursiveKeyOf;
// via: https://stackoverflow.com/a/65333050
type RecursiveKeyOf = {
[TKey in keyof TObj & (string | number)]: RecursiveKeyOfHandleValue<
TObj[TKey],
`${TKey}`
>;
}[keyof TObj & (string | number)];
type RecursiveKeyOfInner = {
[TKey in keyof TObj & (string | number)]: RecursiveKeyOfHandleValue<
TObj[TKey],
`['${TKey}']` | `.${TKey}`
>;
}[keyof TObj & (string | number)];
type RecursiveKeyOfHandleValue<
TValue,
Text extends string,
> = TValue extends any[]
? Text
: TValue extends object
? Text | `${Text}${RecursiveKeyOfInner}`
: Text;
================================================
FILE: templates/ExpoTemplate/src/i18n/locales/en.json
================================================
{
"common": {
"cancel": "Cancel",
"create": "Create",
"delete": "Delete",
"errorMessage": "Unknown error..!!!",
"hey": "Hey there,",
"ohhNo": "Ohh Noo!!!",
"or": "Or",
"ok": "OK",
"save": "Save",
"see_more": "See More",
"skip": "Skip",
"welcome": "Welcome",
"yes": "Yes",
"hello": "Hello {{name}}!",
"internetConnectionError": "Please check you internet connectivity."
},
"newsList": {
"breakingNews": "Breaking News",
"general": "general"
},
"newsDetail": {
"anonymous": "anonymous"
},
"forceUpdate": {
"update": "Update",
"updateMessage": "We've release a new version of the App!\nPlease update your app to enjoy these new features.",
"retry": "Try again"
},
"setting": {
"languages": "Languages",
"settingScreen": "Setting Screen",
"theme": "Theme"
},
"login": {
"log_in": "Log-in",
"email": "Email",
"yourEmailId": "Your Email ID",
"password": "Password",
"login": "Login",
"don'tHaveAnAccount": "Don't have an account ?",
"sign_up": "Sign-up"
},
"signUp": {
"sign_up": "Sign-up",
"name": "Name",
"email": "Email",
"yourEmailId": "Your Email ID",
"password": "Password",
"confirmPassword": "Confirm Password",
"signUp": "SignUp"
}
}
================================================
FILE: templates/ExpoTemplate/src/i18n/locales/hi.json
================================================
{
"common": {
"cancel": "रद्द करना",
"create": "बनाएं",
"delete": "मिटाना",
"errorMessage": "अज्ञात त्रुटि..!!!",
"hey": "सुनो,",
"ohhNo": "ओह तेरी!!!",
"or": "या",
"ok": "ठीक",
"save": "बचाना",
"see_more": "और देखें",
"skip": "छोड़ें",
"welcome": "स्वागत",
"yes": "हाँ",
"internetConnectionError": "कृपया आप इंटरनेट कनेक्टिविटी की जाँच करें।"
},
"newsList": {
"breakingNews": "आज की ताजा खबर",
"general": "आम"
},
"newsDetail": {
"anonymous": "अनाम"
},
"setting": {
"languages": "भाषा",
"settingScreen": "स्क्रीन सेट करना",
"theme": "विषय-वस्तु"
}
}
================================================
FILE: templates/ExpoTemplate/src/navigation/AppNavigation.tsx
================================================
import React from 'react';
import { NavigationContainerRef } from '@react-navigation/native';
import {
createNativeStackNavigator,
NativeStackNavigationOptions,
} from '@react-navigation/native-stack';
import { useSelector } from 'react-redux';
import {
LoginScreen,
NetworkLoggerScreen,
NewsDetailScreen,
NewsListScreen,
SettingScreen,
} from '@src/screens';
import { isForceUpdate } from '@src/store';
import { NavStackParams, Screen } from './appNavigation.type';
import { ForUpdateStack } from './ForceupdateStack';
export const navigationRef =
React.createRef>();
const Stack = createNativeStackNavigator();
const screenOptions: NativeStackNavigationOptions = {
animation: 'slide_from_right',
headerShown: false,
};
export const AppNavigation = () => {
const isForceUpdateApp = useSelector(isForceUpdate);
return (
<>
{isForceUpdateApp ? (
) : (
{__DEV__ && (
)}
)}
>
);
};
================================================
FILE: templates/ExpoTemplate/src/navigation/ForceupdateStack.tsx
================================================
import React from 'react';
import { NavigationContainerRef } from '@react-navigation/native';
import {
createNativeStackNavigator,
NativeStackNavigationOptions,
} from '@react-navigation/native-stack';
import { ForceUpdateScreen, NetworkLoggerScreen } from '@src/screens';
import { NavStackParams, Screen } from './appNavigation.type';
export const navigationRef =
React.createRef>();
const ForceUpdateStack = createNativeStackNavigator();
const screenOptions: NativeStackNavigationOptions = {
animation: 'slide_from_right',
headerShown: false,
};
export const ForUpdateStack = () => {
return (
{__DEV__ && (
)}
);
};
================================================
FILE: templates/ExpoTemplate/src/navigation/appNavigation.type.ts
================================================
import type { RouteProp } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { NewsResult } from '@src/services';
export enum Screen {
FORCE_UPDATE_SCREEN = 'FORCE_UPDATE_SCREEN',
NETWORK_CHECK = 'NETWORK_CHECK',
NEWS_DETAIL = 'NEWS_DETAIL',
NEWS_LIST = 'NEWS_LIST',
SETTING = 'SETTING',
LOGIN = 'LOGIN',
SIGNUP = 'SIGNUP',
}
export type NavStackParams = {
[Screen.FORCE_UPDATE_SCREEN]: undefined;
[Screen.NETWORK_CHECK]: undefined;
[Screen.NEWS_DETAIL]: NewsDetailParams;
[Screen.NEWS_LIST]: undefined;
[Screen.SETTING]: undefined;
[Screen.LOGIN]: undefined;
[Screen.SIGNUP]: undefined;
};
export type NewsDetailParams = {
item: NewsResult;
};
export type AppNavigationProp = NativeStackNavigationProp;
export type NewsDetailRoute = RouteProp;
================================================
FILE: templates/ExpoTemplate/src/navigation/withNavigation.ts
================================================
import {
NavigationProp,
ParamListBase,
useNavigation,
} from '@react-navigation/native';
export declare type WithNavigation<
NavProp extends NavigationProp,
T,
> = {
navigation: NavProp;
} & T;
export function useWithNavigation<
NavProp extends NavigationProp,
T extends object,
>(data: T): WithNavigation {
const navigation = useNavigation();
return { ...data, navigation };
}
================================================
FILE: templates/ExpoTemplate/src/screens/ErrorBoundary/ErrorBoundary.tsx
================================================
import React, { ErrorInfo, ReactNode } from 'react';
// import { ErrorDetails } from "./ErrorDetails"
interface Props {
children: ReactNode;
catchErrors: 'always' | 'dev' | 'prod' | 'never';
}
interface State {
error: Error | null;
errorInfo: ErrorInfo | null;
}
/**
* This component handles whenever the user encounters a JS error in the
* app. It follows the "error boundary" pattern in React. We're using a
* class component because according to the documentation, only class
* components can be error boundaries.
*
* - [Documentation and Examples](https://github.com/infinitered/ignite/blob/master/docs/Error-Boundary.md)
* - [React Error Boundaries](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
*/
export class ErrorBoundary extends React.Component {
state = { error: null, errorInfo: null };
// If an error in a child is encountered, this will run
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// Only set errors if enabled
if (!this.isEnabled()) {
return;
}
// Catch errors in any components below and re-render with error message
this.setState({
error,
errorInfo,
});
// You can also log error messages to an error reporting service here
// This is a great place to put BugSnag, Sentry, crashlytics, etc:
// reportCrash(error)
}
// Reset the error back to null
resetError = () => {
this.setState({ error: null, errorInfo: null });
};
// To avoid unnecessary re-renders
shouldComponentUpdate(
_nextProps: Readonly,
nextState: Readonly
): boolean {
return nextState.error !== this.state.error;
}
// Only enable if we're catching errors in the right environment
isEnabled(): boolean {
return (
this.props.catchErrors === 'always' ||
(this.props.catchErrors === 'dev' && __DEV__) ||
(this.props.catchErrors === 'prod' && !__DEV__)
);
}
// Render an error UI if there's an error; otherwise, render children
render() {
return this.isEnabled() && this.state.error
? //
null
: this.props.children;
}
}
================================================
FILE: templates/ExpoTemplate/src/screens/ForceUpdate/ForceUpdate.style.ts
================================================
import { StyleSheet } from 'react-native';
import { Palette, scaledSize, scaleHeight, scaleWidth } from '@src/utils';
export const forceUpdateStyles = ({ backgroundColor, textColor }: Palette) =>
StyleSheet.create({
buttonContainer: {
marginTop: scaleHeight(40),
},
container: {
backgroundColor: backgroundColor,
flex: 1,
justifyContent: 'center',
paddingHorizontal: scaleWidth(35),
},
messageStyle: {
color: textColor,
fontSize: scaledSize(18),
marginBottom: scaleHeight(40),
textAlign: 'center',
},
retryButton: {
backgroundColor: backgroundColor,
borderColor: textColor,
borderWidth: scaleWidth(1),
marginTop: scaleHeight(20),
},
retryText: {
color: textColor,
},
updateText: {
color: backgroundColor,
},
});
================================================
FILE: templates/ExpoTemplate/src/screens/ForceUpdate/ForceUpdateScreen.tsx
================================================
import React from 'react';
import { View } from 'react-native';
import { Button, Text } from '@app/blueprints';
import { contents } from '@src/context';
import useForceUpdate from './useForceUpdate';
const ForceUpdateScreen = () => {
const { styles } = useForceUpdate();
return (
{contents('forceUpdate.updateMessage')}
);
};
export default React.memo(ForceUpdateScreen);
================================================
FILE: templates/ExpoTemplate/src/screens/ForceUpdate/useForceUpdate.ts
================================================
import { useCallback } from 'react';
import { Linking } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { AppConfig, isIOS } from '@src/constants';
import { useAppContext } from '@src/context';
import { logger } from '@src/utils';
import { forceUpdateStyles } from './ForceUpdate.style';
const useForceUpdate = () => {
const { color, ...props } = useAppContext();
const styles = forceUpdateStyles(color);
const onUpdatePress = useCallback(() => {
try {
const URLToOpen = isIOS
? AppConfig.APP_STORE_URL
: AppConfig.PLAY_STORE_URL;
Linking.canOpenURL(URLToOpen)
.then(res => {
res && Linking.openURL(URLToOpen);
})
.catch(error => {
logger(`Error:: ${error}`);
});
} catch (error) {
logger(`Error:: ${error}`);
}
}, []);
const onRetryPress = useCallback(() => {}, []);
useFocusEffect(
useCallback(() => {
onRetryPress();
}, [onRetryPress])
);
return {
onRetryPress,
onUpdatePress,
styles,
...props,
};
};
export default useForceUpdate;
================================================
FILE: templates/ExpoTemplate/src/screens/Login/Login.style.ts
================================================
import { StyleSheet } from 'react-native';
import { Palette, scaledSize, scaleHeight, scaleWidth } from '@src/utils';
export const loginStyles = ({ backgroundColor, secondaryColor }: Palette) =>
StyleSheet.create({
container: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
content: {
backgroundColor: backgroundColor,
borderRadius: scaledSize(30),
flex: 2,
paddingHorizontal: scaleWidth(15),
paddingTop: scaleHeight(25),
top: -scaleHeight(25),
},
fieldContainer: {},
header: {
backgroundColor: secondaryColor,
flex: 1,
},
input: {
marginVertical: scaleHeight(10),
},
loginBtn: {
marginTop: scaleHeight(15),
},
});
================================================
FILE: templates/ExpoTemplate/src/screens/Login/LoginScreen.tsx
================================================
import React from 'react';
import { View } from 'react-native';
import { Button, Text, TextInput } from '@app/blueprints';
import { Formik } from 'formik';
import { BaseLayout } from '@src/components';
import { contents } from '@src/context';
import useLogin from './useLogin';
const LoginScreen = () => {
const {
disabled,
fieldValidation,
handleButtonSubmit,
initialValues,
passwordRef,
styles,
} = useLogin();
return (
{contents('login.log_in')}
{({ resetForm, submitForm }) => (
{
passwordRef.current?.focus();
}}
/>
)}
);
};
export default React.memo(LoginScreen);
================================================
FILE: templates/ExpoTemplate/src/screens/Login/useLogin.ts
================================================
import { useCallback, useRef, useState } from 'react';
import { TextInput } from 'react-native';
import * as yup from 'yup';
import { useAppContext } from '@src/context';
import { logger } from '@src/utils';
import { loginStyles } from './Login.style';
const useLogin = () => {
const { color, navigation } = useAppContext();
const [disabled, setDisabled] = useState(false);
const passwordRef = useRef(null);
const fieldValidation = yup.object().shape({
email: yup.string().trim().required('Please enter your Email'),
password: yup.string().trim().required('Please enter your Password'),
});
const initialValues = {
email: '',
password: '',
};
const handleButtonSubmit = useCallback(
async (values: typeof initialValues) => {
logger('values: ', values);
setDisabled(true);
await new Promise(res => setTimeout(res, 3000));
setDisabled(false);
},
[]
);
return {
disabled,
fieldValidation,
handleButtonSubmit,
initialValues,
navigation,
passwordRef,
styles: loginStyles(color),
};
};
export default useLogin;
================================================
FILE: templates/ExpoTemplate/src/screens/NetworkLogger/NetworkLoggerScreen.tsx
================================================
import React from 'react';
import NetworkLogger from 'react-native-network-logger';
import { BaseLayout } from '@src/components';
const NetworkLoggerScreen = () => {
return (
);
};
export default React.memo(NetworkLoggerScreen);
================================================
FILE: templates/ExpoTemplate/src/screens/NewsDetail/NewsDetail.style.ts
================================================
import { StyleSheet } from 'react-native';
import { Palette, scaleHeight, scaleWidth, screenWidth } from '@src/utils';
export const newsDetailStyles = ({}: Palette) =>
StyleSheet.create({
descriptionText: {},
infoContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginVertical: scaleHeight(16),
},
newsImage: {
height: screenWidth * 0.8,
width: screenWidth - scaleWidth(20),
},
scrollViewContainer: { paddingHorizontal: scaleWidth(10) },
title: {
marginBottom: scaleHeight(15),
textAlign: 'center',
},
});
================================================
FILE: templates/ExpoTemplate/src/screens/NewsDetail/NewsDetailScreen.tsx
================================================
import React from 'react';
import { ScrollView, View } from 'react-native';
import { Button, Text } from '@app/blueprints';
import { AppImage, BaseLayout } from '@src/components';
import { contents } from '@src/context';
import { scaleHeight } from '@src/utils';
import useNewsDetail from './useNewsDetail';
const NewsDetailScreen = () => {
const { data, getPublishedMonth, handleGoBack, styles } = useNewsDetail();
return (
{data.title}
{data.categories
? data.categories
: contents('newsDetail.anonymous')}
{getPublishedMonth(data.published_on)}
{data.body}
);
};
export default React.memo(NewsDetailScreen);
================================================
FILE: templates/ExpoTemplate/src/screens/NewsDetail/useNewsDetail.ts
================================================
import { useCallback } from 'react';
import { useRoute } from '@react-navigation/native';
import { contents, useAppContext } from '@src/context';
import { newsDetailStyles } from './NewsDetail.style';
import { NewsDetailRoute } from '../../navigation/appNavigation.type';
const useNewsDetail = () => {
const { color, navigation } = useAppContext();
const {
params: { item: data },
} = useRoute();
const getPublishedMonth = useCallback((val: number) => {
const publishedAt = new Date(val).toString();
return publishedAt.split(' ').slice(0, 3).join(' ');
}, []);
const handleGoBack = useCallback(async () => {
navigation.goBack();
}, [navigation]);
return {
contents,
data,
getPublishedMonth,
handleGoBack,
navigation,
styles: newsDetailStyles(color),
};
};
export default useNewsDetail;
================================================
FILE: templates/ExpoTemplate/src/screens/NewsList/NewsList.style.ts
================================================
import { StyleSheet } from 'react-native';
import {
Palette,
scaled,
scaledSize,
scaleHeight,
scaleWidth,
} from '@src/utils';
export const newsListStyles = ({ backgroundColor, primaryColor }: Palette) =>
StyleSheet.create({
debugIcon: {
...scaled(25),
tintColor: primaryColor,
},
flatlistStyles: { paddingHorizontal: scaledSize(5) },
headerContainer: {
alignItems: 'center',
justifyContent: 'center',
marginVertical: scaleHeight(10),
},
networkButton: {
position: 'absolute',
right: scaleWidth(5),
},
newsImage: {
borderRadius: scaledSize(5),
height: scaleHeight(95),
width: scaleWidth(120),
},
newsItemContainer: {
backgroundColor,
borderRadius: scaledSize(5),
flex: 1,
flexDirection: 'row',
marginBottom: scaleHeight(5),
marginTop: scaleHeight(5),
},
newsTextView: {
flex: 1,
padding: scaledSize(5),
},
settingBtn: {
position: 'absolute',
right: scaleWidth(40),
},
});
================================================
FILE: templates/ExpoTemplate/src/screens/NewsList/NewsListScreen.tsx
================================================
import React from 'react';
import { FlatList, TouchableOpacity, View } from 'react-native';
import { AnimatedTouchableOpacity, Text } from '@app/blueprints';
import { Icons, SVGIcons } from '@src/assets';
import { AppImage, BaseLayout, Icon, SvgIcon } from '@src/components';
import { contents } from '@src/context';
import type { NewsResult } from '@src/services';
import { scaled } from '@src/utils';
import useNewsList from './useNewsList';
const NewsListScreen = () => {
const {
color,
data,
handleNavigationNetwork,
handleNavigationNewsItem,
handleSetting,
styles,
} = useNewsList();
const renderItem = ({ item }: { item: NewsResult }) => {
return (
{item?.source ? item.source : contents('newsList.general')}
{item.title}
);
};
return (
`${item.id}_${item.title}`}
renderItem={renderItem}
ListHeaderComponent={
{contents('newsList.breakingNews')}
}
/>
);
};
export default React.memo(NewsListScreen);
================================================
FILE: templates/ExpoTemplate/src/screens/NewsList/useNewsList.ts
================================================
import { useCallback, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { contents, useAppContext } from '@src/context';
import { NewsResult } from '@src/services';
import { getNewsData as newsData, setNews, useAppDispatch } from '@src/store';
import { logger } from '@src/utils';
import { newsListStyles } from './NewsList.style';
import { Screen } from '../../navigation/appNavigation.type';
const useNewsList = () => {
const { color, loader, navigation, services } = useAppContext();
const dispatch = useAppDispatch();
const data = useSelector(newsData);
const getNewsData = useCallback(async () => {
loader.current?.show();
try {
const getNews = await services.getNews();
dispatch(setNews(getNews));
} catch (error) {
logger('Error getNews>>', error);
} finally {
loader.current?.hide();
}
}, [loader, services, dispatch]);
const handleNavigationNetwork = useCallback(() => {
navigation.navigate(Screen.NETWORK_CHECK);
}, [navigation]);
const handleNavigationNewsItem = useCallback(
(item: NewsResult) => () => {
navigation.navigate(Screen.NEWS_DETAIL, {
item,
});
},
[navigation]
);
const handleSetting = useCallback(() => {
navigation.navigate(Screen.SETTING);
}, [navigation]);
useEffect(() => {
getNewsData();
}, [getNewsData]);
return {
color,
contents,
data,
handleNavigationNetwork,
handleNavigationNewsItem,
handleSetting,
styles: newsListStyles(color),
};
};
export default useNewsList;
================================================
FILE: templates/ExpoTemplate/src/screens/Setting/Setting.style.ts
================================================
import { StyleSheet } from 'react-native';
import { Palette, scaled, scaleHeight, scaleWidth } from '@src/utils';
export const settingStyles = ({ primaryColor }: Palette) =>
StyleSheet.create({
btn: {
marginTop: scaleHeight(30),
},
content: {
marginTop: scaleHeight(25),
paddingHorizontal: scaleWidth(50),
},
header: {
alignItems: 'center',
justifyContent: 'center',
},
radio: {
...scaled(20),
alignItems: 'center',
borderRadius: 10,
borderWidth: 1,
justifyContent: 'center',
},
selectedRadio: {
...scaled(10),
backgroundColor: primaryColor,
borderRadius: 10,
},
themes: {
flexDirection: 'row',
justifyContent: 'space-between',
marginVertical: scaleHeight(5),
},
});
================================================
FILE: templates/ExpoTemplate/src/screens/Setting/SettingScreen.tsx
================================================
import React from 'react';
import { View } from 'react-native';
import { AnimatedTouchableOpacity, Button, Text } from '@app/blueprints';
import { BaseLayout } from '@src/components';
import { contents } from '@src/context';
import { ContentLanguage } from '@src/i18n';
import useSetting from './useSetting';
const SettingScreen = () => {
const {
appTheme,
handleChangeLanguage,
handleChangeTheme,
handleLogin,
language,
languages,
styles,
themes,
} = useSetting();
return (
{contents('setting.settingScreen')}
{contents('setting.theme')}
{themes.map(m => {
return (
{m}
{appTheme === m.toLowerCase() ? (
) : null}
);
})}
{contents('setting.languages')}
{languages.map(m => {
return (
{m}
{ContentLanguage[m as keyof typeof ContentLanguage] ===
language ? (
) : null}
);
})}
);
};
export default React.memo(SettingScreen);
================================================
FILE: templates/ExpoTemplate/src/screens/Setting/useSetting.ts
================================================
import { useCallback } from 'react';
import { useAppContext } from '@src/context';
import { ContentLanguage } from '@src/i18n';
import { Theme } from '@src/utils';
import { settingStyles } from './Setting.style';
import { Screen } from '../../navigation/appNavigation.type';
const themes = ['Dark', 'Light', 'Theme1', 'Theme2', 'Theme3'];
const languages = Object.keys(ContentLanguage);
const useSetting = () => {
const {
appTheme,
color,
language,
navigation,
setAppTheme,
setLanguageInApp,
} = useAppContext();
const handleChangeTheme = useCallback(
(m: string) => () => {
setAppTheme(m as Theme);
},
[setAppTheme]
);
const handleChangeLanguage = useCallback(
(m: string) => async () => {
await setLanguageInApp(
ContentLanguage[m as keyof typeof ContentLanguage]
);
},
[setLanguageInApp]
);
const handleLogin = useCallback(() => {
navigation.navigate(Screen.LOGIN);
}, [navigation]);
// add your code here
return {
appTheme,
color,
handleChangeLanguage,
handleChangeTheme,
handleLogin,
language,
languages,
navigation,
styles: settingStyles(color),
themes,
};
};
export default useSetting;
================================================
FILE: templates/ExpoTemplate/src/screens/index.ts
================================================
export { default as NetworkLoggerScreen } from './NetworkLogger/NetworkLoggerScreen';
export { default as NewsListScreen } from './NewsList/NewsListScreen';
export { default as NewsDetailScreen } from './NewsDetail/NewsDetailScreen';
export { default as ForceUpdateScreen } from './ForceUpdate/ForceUpdateScreen';
export { default as SettingScreen } from './Setting/SettingScreen';
export { default as LoginScreen } from './Login/LoginScreen';
================================================
FILE: templates/ExpoTemplate/src/services/apiHandler.ts
================================================
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { AppConfig } from '@src/constants';
class APIhandler {
private readonly axiosInstance: AxiosInstance;
private readonly axiosHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
constructor() {
this.axiosInstance = axios.create({
baseURL: AppConfig.API_URL,
headers: this.axiosHeaders,
timeout: 10000,
timeoutErrorMessage: 'Slow Network',
validateStatus(status) {
return (
(status >= 200 && status < 300) || status === 400 || status === 401
);
},
});
// ***** Uncomment lines for debugging Request *****
// this.axiosInstance.interceptors.request.use(req => {
// if (__DEV__) {
// // eslint-disable-next-line no-console
// console.log(
// '⛔️⛔️⛔️ this.axiosInstance.interceptors.request: ',
// JSON.stringify(req, null, ' ')
// );
// }
// return req;
// });
//***** Uncomment lines for debugging Response *****
// this.axiosInstance.interceptors.response.use(res => {
// if (__DEV__) {
// // eslint-disable-next-line no-console
// console.log(
// '🚀🚀🚀🚀 this.axiosInstance.interceptors.response: ',
// JSON.stringify(res, null, ' ')
// );
// }
// return res;
// });
}
requestHeader = () => {
return {
Authorization: `Bearer `,
};
};
handleBodyResponse = async (response: AxiosResponse): Promise => {
if (response.status === 200) {
return Promise.resolve(JSON.parse(JSON.stringify(response.data)));
} else if (response.status === 400) {
return Promise.reject({
cause: response.status.toString(),
message: response.data.message,
} as Error);
} else if (response.status === 401) {
return Promise.reject({
cause: response.status.toString(),
message: 'Your session has been expired..!!! please login again...',
} as Error);
} else {
return Promise.reject({
cause: response.status.toString(),
message: response.statusText,
} as Error);
}
};
postAPIService = async (api: string, reqParams: any): Promise => {
try {
const response = await this.axiosInstance.post(api, reqParams, {
headers: { ...this.axiosHeaders, ...this.requestHeader() },
});
return this.handleBodyResponse(response);
} catch (error) {
return Promise.reject(error);
}
};
async getAPIService(api: string): Promise {
try {
// get, D = any>(url: string, config?: AxiosRequestConfig): Promise;
const response = await this.axiosInstance.get(api, {
headers: { ...this.axiosHeaders, ...this.requestHeader() },
});
return this.handleBodyResponse(response);
} catch (error) {
return Promise.reject(error);
}
}
deleteAPIService = async (api: string, reqParams: any = {}): Promise => {
try {
const response = await this.axiosInstance.delete(api, {
headers: { ...this.axiosHeaders, ...this.requestHeader() },
params: reqParams,
});
return this.handleBodyResponse(response);
} catch (error) {
return Promise.reject(error);
}
};
putAPIService = async (api: string, reqParams: any = {}): Promise => {
try {
const response = await this.axiosInstance({
data: reqParams,
headers: { ...this.axiosHeaders, ...this.requestHeader() },
method: 'PUT',
url: api,
});
return this.handleBodyResponse(response);
} catch (error) {
return Promise.reject(error);
}
};
}
export const API = new APIhandler();
================================================
FILE: templates/ExpoTemplate/src/services/appServices.ts
================================================
import { API_METHODS } from './appServices.type';
import { ServicesEndPoints } from './appServicesEndPoints';
import { getNewsCommercialResponseAdapter } from './commercial/adapters/response/getNewsCommercialResponseAdapter';
import { GetUserCommercialResponseAdapter } from './commercial/adapters/response/getUserCommercialResponseAdapter';
import { PostLoginCommercialResponseAdapter } from './commercial/adapters/response/postLoginCommercialResponseAdapter';
import { NewsResponseDTO } from './commercial/dtos/NewsResponseDTO';
import {
LoginResponseDTO,
UserResponseDTO,
} from './commercial/dtos/UserResponseDTO';
import { ListUserReq, NewsResult, UserResult } from './models';
import { LoginParams, LoginResult } from './models/login';
import serviceAdapter from './serviceAdapter';
export class AppServices {
constructor() {}
loginUser = async (loginParams: LoginParams): Promise => {
return new Promise((resolve, reject) => {
serviceAdapter(
API_METHODS.POST,
ServicesEndPoints.LOGIN,
loginParams
)
.then(res => {
resolve(new PostLoginCommercialResponseAdapter().service(res));
})
.catch(error => {
reject(error);
});
});
};
listUsers = async (listUserReq: ListUserReq): Promise => {
return new Promise((resolve, reject) => {
serviceAdapter(
API_METHODS.GET,
`${ServicesEndPoints.USERS}?page=${listUserReq.page}&per_page=${listUserReq.per_page}`
)
.then(res => {
resolve(new GetUserCommercialResponseAdapter().service(res));
})
.catch(error => {
reject(error);
});
});
};
getNews = async (): Promise => {
return new Promise((resolve, reject) => {
serviceAdapter(
API_METHODS.GET,
ServicesEndPoints.NEWS
)
.then(res => {
resolve(new getNewsCommercialResponseAdapter().service(res));
})
.catch(error => {
reject(error);
});
});
};
}
export const appServices = new AppServices();
================================================
FILE: templates/ExpoTemplate/src/services/appServices.type.ts
================================================
export enum API_METHODS {
DELETE = 'DELETE',
GET = 'GET',
POST = 'POST',
PUT = 'PUT',
}
================================================
FILE: templates/ExpoTemplate/src/services/appServicesEndPoints.ts
================================================
export enum ServicesEndPoints {
USERS = '/users',
LOGIN = '/login',
NEWS = '/news/',
}
================================================
FILE: templates/ExpoTemplate/src/services/commercial/adapters/response/getNewsCommercialResponseAdapter.ts
================================================
import { NewsResult } from '../../../models';
import { NewDataResponse, NewsResponseDTO } from '../../dtos/NewsResponseDTO';
export class getNewsCommercialResponseAdapter {
constructor() {}
service(dto: NewsResponseDTO): NewsResult[] {
return dto.Data.map((item: NewDataResponse) => {
return {
body: item.body,
categories: item.categories,
id: item.id,
imageUrl: item.imageurl,
published_on: item.published_on,
source: item.source,
tags: item.tags,
title: item.title,
};
});
}
}
================================================
FILE: templates/ExpoTemplate/src/services/commercial/adapters/response/getUserCommercialResponseAdapter.ts
================================================
import { UserResult } from '@src/services/models/user';
import { UserResponseDTO } from '../../dtos/UserResponseDTO';
export class GetUserCommercialResponseAdapter {
constructor() {}
service(dto: UserResponseDTO): UserResult[] {
return dto.data.map(item => {
return {
firstName: item.first_name,
id: item.id,
lastName: item.last_name,
};
});
}
}
================================================
FILE: templates/ExpoTemplate/src/services/commercial/adapters/response/postLoginCommercialResponseAdapter.ts
================================================
import { LoginResult } from '@src/services/models/login';
import { LoginResponseDTO } from '../../dtos/UserResponseDTO';
export class PostLoginCommercialResponseAdapter {
constructor() {}
service(dto: LoginResponseDTO): LoginResult {
return {
userToken: dto.token,
};
}
}
================================================
FILE: templates/ExpoTemplate/src/services/commercial/dtos/NewsResponseDTO.ts
================================================
export interface NewsResponseDTO {
Type: number;
Message: string;
Promoted?: null[] | null;
Data: NewDataResponse[];
RateLimit: Object;
HasWarning: boolean;
}
export interface NewDataResponse {
id: string;
guid?: string;
published_on: number;
imageurl: string;
title: string;
url?: string;
body: string;
tags: string;
lang?: string;
upvotes?: string;
downvotes?: string;
categories: string;
source_info?: SourceInfo;
source: string;
}
export interface SourceInfo {
name: string;
img: string;
lang: string;
}
================================================
FILE: templates/ExpoTemplate/src/services/commercial/dtos/UserResponseDTO.ts
================================================
export interface UserResponseDTO {
page: number;
per_page: number;
total: number;
total_pages: number;
data: DatumDTO[];
support: SupportDTO;
}
export interface DatumDTO {
id: number;
email: string;
first_name: string;
last_name: string;
avatar: string;
}
export interface SupportDTO {
url: string;
text: string;
}
export interface LoginResponseDTO {
token: string;
}
================================================
FILE: templates/ExpoTemplate/src/services/index.ts
================================================
export * from './apiHandler';
export * from './appServicesEndPoints';
export * from './serviceAdapter';
export * from './models';
export * from './appServices';
================================================
FILE: templates/ExpoTemplate/src/services/models/index.ts
================================================
export * from './unknown';
export * from './user';
export * from './news';
================================================
FILE: templates/ExpoTemplate/src/services/models/login.ts
================================================
export interface LoginResult {
userToken: string;
}
export interface LoginParams {
email: string;
password: string;
}
================================================
FILE: templates/ExpoTemplate/src/services/models/news.ts
================================================
export interface Source {
id?: null | string | number;
name: string;
}
export interface NewsResult {
body: string;
categories: string;
id: string;
imageUrl: string;
published_on: number;
source: string;
tags: string;
title: string;
}
================================================
FILE: templates/ExpoTemplate/src/services/models/unknown.ts
================================================
export interface ApiUnknownResponse {}
export interface ApiUnknownRequestParams {}
export interface UnknownResponse {}
================================================
FILE: templates/ExpoTemplate/src/services/models/user.ts
================================================
export interface ListUserReq {
page: number;
per_page: number;
}
export interface UserResult {
firstName: string;
id: number;
lastName: string;
}
================================================
FILE: templates/ExpoTemplate/src/services/serviceAdapter.ts
================================================
import { isNetworkConnected } from '@src/utils';
import { API } from './apiHandler';
import { API_METHODS } from './appServices.type';
import { contents } from '../context/content';
export default async function serviceAdapter(
method: API_METHODS,
url: string,
requestParam?: reqParams
): Promise {
const status = await isNetworkConnected();
if (status) {
if (method.toString() === API_METHODS.GET) {
return API.getAPIService(url);
} else if (method.toString() === API_METHODS.DELETE) {
return API.deleteAPIService(url, requestParam);
} else if (method.toString() === API_METHODS.PUT) {
return API.putAPIService(url, requestParam);
} else if (method.toString() === API_METHODS.POST) {
return API.postAPIService(url, requestParam);
} else {
return Promise.reject('REST METHOD NOT EXITSt');
}
} else {
return Promise.reject(Error(contents('common.internetConnectionError')));
}
}
================================================
FILE: templates/ExpoTemplate/src/store/index.ts
================================================
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import { useDispatch } from 'react-redux';
import {
FLUSH,
PAUSE,
PERSIST,
PersistConfig,
persistReducer,
persistStore,
PURGE,
REGISTER,
REHYDRATE,
} from 'redux-persist';
import { reduxStorage } from '@src/context';
import { newsData, newsDataName, userData } from './reducers';
const rootReducer = combineReducers({
newsData,
userData,
});
export type RootState = ReturnType;
const persistConfig: PersistConfig = {
key: 'root',
storage: reduxStorage,
whitelist: [newsDataName],
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
devTools: true,
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
thunk: {
extraArgument: {},
},
}),
reducer: persistedReducer,
});
export const persistor = persistStore(store);
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch();
export default store;
export * from './reducers';
export * from './observers';
================================================
FILE: templates/ExpoTemplate/src/store/observers/index.ts
================================================
export * from './users';
export * from './news';
================================================
FILE: templates/ExpoTemplate/src/store/observers/news.ts
================================================
import { RootState } from '../index';
export const getNewsData = (state: RootState) => state.newsData.news;
================================================
FILE: templates/ExpoTemplate/src/store/observers/users.ts
================================================
import { RootState } from '../index';
export const usersData = (state: RootState) => state.userData.users;
export const isForceUpdate = (state: RootState) => state.userData.isForceUpdate;
================================================
FILE: templates/ExpoTemplate/src/store/reducers/index.ts
================================================
export * from './usersData';
export * from './newsData';
================================================
FILE: templates/ExpoTemplate/src/store/reducers/newsData.ts
================================================
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { NewsResult } from '@src/services';
type NewsData = {
news: NewsResult[];
};
const initialState: NewsData = {
news: [],
};
export const newsDataSlice = createSlice({
initialState,
name: 'newsData',
reducers: {
resetNewsData: () => initialState,
setNews: (state, { payload }: PayloadAction) => {
state.news = payload;
},
},
});
export const {
actions: { resetNewsData, setNews },
name: newsDataName,
reducer: newsData,
} = newsDataSlice;
================================================
FILE: templates/ExpoTemplate/src/store/reducers/usersData.ts
================================================
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { UserResult } from '@src/services';
type AppData = {
users: UserResult[];
isForceUpdate: boolean;
};
const initialState: AppData = {
isForceUpdate: false,
users: [],
};
export const userDataSlice = createSlice({
initialState,
name: 'userData',
reducers: {
resetUserData: () => initialState,
setForceUpdate: (state, { payload }: PayloadAction) => {
state.isForceUpdate = payload;
},
setUsers: (state, { payload }: PayloadAction) => {
state.users = payload;
},
},
});
export const {
actions: { resetUserData, setForceUpdate, setUsers },
name: userDataName,
reducer: userData,
} = userDataSlice;
================================================
FILE: templates/ExpoTemplate/src/utils/color.ts
================================================
import { ColorSchemeName } from 'react-native/types';
export const color = {
dark: {
backgroundColor: '#212121', // light grey
primaryColor: '#0a84ff', // bright blue
secondaryColor: '#dcdcdc', // dark grey
textColor: '#f8f9fa', // off-white
},
light: {
backgroundColor: '#f8f9fa', // grey
primaryColor: '#000080', // blue
secondaryColor: '#6c757d', // off-white
textColor: '#343a40', // dark grey
},
theme1: {
backgroundColor: '#f8f8f8', // light pink
primaryColor: '#ff5a5f', // red
secondaryColor: '#f2c9c9', // off-white
textColor: '#424242', // dark grey
},
theme2: {
backgroundColor: '#e5e5e5', // wheat
primaryColor: '#000080', // navy blue
secondaryColor: '#f5deb3', // light grey
textColor: '#333333', // dark grey
},
theme3: {
backgroundColor: '#f0f0f0', // light yellow
primaryColor: '#800000', // maroon
secondaryColor: '#ffffe0', // light grey
textColor: '#2f4f4f', // dark slate grey
},
theme4: {
backgroundColor: '#f5f5f5', // misty rose
primaryColor: '#663399', // rebecca purple
secondaryColor: '#ffe4e1', // light grey
textColor: '#333333', // dark grey
},
};
export type Palette = (typeof color)[keyof typeof color];
export type Theme = ColorSchemeName | keyof typeof color;
================================================
FILE: templates/ExpoTemplate/src/utils/dimensions.ts
================================================
import { Dimensions } from 'react-native';
const { height: screenHeight, width: screenWidth } = Dimensions.get('window');
// resolution changes as per design
export const designWidth = 375;
export const designHeight = 812;
const scaleWidth = (val: number) => {
return (screenWidth * val) / designWidth;
};
const scaleHeight = (val: number) => {
return (screenHeight * val) / designHeight;
};
const scale = Math.min(screenWidth / designWidth, screenHeight / designHeight);
const moderateScale = (size: number, factor = 1) =>
size + (scaleWidth(size) - size) * factor;
const scaledSize = (size: number) => Math.ceil(size * scale);
export {
moderateScale,
scaledSize,
scaleHeight,
scaleWidth,
screenHeight,
screenWidth,
};
================================================
FILE: templates/ExpoTemplate/src/utils/helper.ts
================================================
import { createRef } from 'react';
import NetInfo from '@react-native-community/netinfo';
import { scaledSize } from './dimensions';
import { IndicatorRef } from '../../blueprints/Indicator/Indicator';
export const isNetworkConnected = async () => {
const state = await NetInfo.refresh();
return state.isConnected || false;
};
export function isEmpty(obj: object) {
return Object.keys(obj).length === 0;
}
export const logger = (...args: any) => {
if (__DEV__) {
// eslint-disable-next-line no-console
console.log(...args);
}
};
export const scaled = (value: number) => {
return {
height: scaledSize(value),
width: scaledSize(value),
};
};
export function boxShadow(
color: string,
offset = { height: 2, width: 2 },
radius = 8,
opacity = 0.2
) {
return {
elevation: radius,
shadowColor: color,
shadowOffset: offset,
shadowOpacity: opacity,
shadowRadius: radius,
};
}
export function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve as () => void, ms));
}
export const loader = createRef();
================================================
FILE: templates/ExpoTemplate/src/utils/index.ts
================================================
export * from './dimensions';
export * from './helper';
export * from './color';
================================================
FILE: templates/ExpoTemplate/tsconfig.json
================================================
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
/* Basic Options */
"target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "esnext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"lib": [
"esnext"
] /* Specify library files to be included in the compilation. */,
"allowJs": true /* Allow javascript files to be compiled. */,
"jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,
"moduleResolution": "bundler" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"paths": {
"@src/*": ["./src/*"],
"@app/blueprints": ["./blueprints"]
} /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */,
"strict": true /* Enable all strict type-checking options. */,
"noUnusedLocals": true /* Report errors on unused locals. */,
"noUnusedParameters": true /* Report errors on unused parameters. */,
"noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
"noImplicitUseStrict": false,
"noStrictGenericChecks": false,
"noUncheckedIndexedAccess": true,
"types": ["react-native", "jest", "node"],
"typeRoots": ["@types", "./node_modules/@types"],
"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"skipLibCheck": true /* Skip type checking of declaration files. */,
"resolveJsonModule": true /* Allows importing modules with a ‘.json’ extension, which is a common practice in node projects. */
/* Module Resolution Options */
// "importsNotUsedAsValues": "error",
// "baseUrl": "..", /* Base directory to resolve non-absolute module names. */,
// "checkJs": true, /* Report errors in .js files. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true /* Do not emit outputs. */,
// "incremental": true, /* Enable incremental compilation */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
/* Strict Type-Checking Options */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Additional Checks */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
},
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}